CGCall.cpp 176 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588
  1. //===--- CGCall.cpp - Encapsulate calling convention details --------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // These classes wrap the information about a call or function
  10. // definition used to handle ABI compliancy.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CGCall.h"
  14. #include "ABIInfo.h"
  15. #include "CGBlocks.h"
  16. #include "CGCXXABI.h"
  17. #include "CGCleanup.h"
  18. #include "CodeGenFunction.h"
  19. #include "CodeGenModule.h"
  20. #include "TargetInfo.h"
  21. #include "clang/AST/Decl.h"
  22. #include "clang/AST/DeclCXX.h"
  23. #include "clang/AST/DeclObjC.h"
  24. #include "clang/Basic/CodeGenOptions.h"
  25. #include "clang/Basic/TargetBuiltins.h"
  26. #include "clang/Basic/TargetInfo.h"
  27. #include "clang/CodeGen/CGFunctionInfo.h"
  28. #include "clang/CodeGen/SwiftCallingConv.h"
  29. #include "llvm/ADT/StringExtras.h"
  30. #include "llvm/Transforms/Utils/Local.h"
  31. #include "llvm/Analysis/ValueTracking.h"
  32. #include "llvm/IR/Attributes.h"
  33. #include "llvm/IR/CallingConv.h"
  34. #include "llvm/IR/DataLayout.h"
  35. #include "llvm/IR/InlineAsm.h"
  36. #include "llvm/IR/IntrinsicInst.h"
  37. #include "llvm/IR/Intrinsics.h"
  38. using namespace clang;
  39. using namespace CodeGen;
  40. /***/
  41. unsigned CodeGenTypes::ClangCallConvToLLVMCallConv(CallingConv CC) {
  42. switch (CC) {
  43. default: return llvm::CallingConv::C;
  44. case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
  45. case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
  46. case CC_X86RegCall: return llvm::CallingConv::X86_RegCall;
  47. case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
  48. case CC_Win64: return llvm::CallingConv::Win64;
  49. case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
  50. case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
  51. case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
  52. case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
  53. // TODO: Add support for __pascal to LLVM.
  54. case CC_X86Pascal: return llvm::CallingConv::C;
  55. // TODO: Add support for __vectorcall to LLVM.
  56. case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
  57. case CC_AArch64VectorCall: return llvm::CallingConv::AArch64_VectorCall;
  58. case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
  59. case CC_OpenCLKernel: return CGM.getTargetCodeGenInfo().getOpenCLKernelCallingConv();
  60. case CC_PreserveMost: return llvm::CallingConv::PreserveMost;
  61. case CC_PreserveAll: return llvm::CallingConv::PreserveAll;
  62. case CC_Swift: return llvm::CallingConv::Swift;
  63. }
  64. }
  65. /// Derives the 'this' type for codegen purposes, i.e. ignoring method CVR
  66. /// qualification. Either or both of RD and MD may be null. A null RD indicates
  67. /// that there is no meaningful 'this' type, and a null MD can occur when
  68. /// calling a method pointer.
  69. CanQualType CodeGenTypes::DeriveThisType(const CXXRecordDecl *RD,
  70. const CXXMethodDecl *MD) {
  71. QualType RecTy;
  72. if (RD)
  73. RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
  74. else
  75. RecTy = Context.VoidTy;
  76. if (MD)
  77. RecTy = Context.getAddrSpaceQualType(RecTy, MD->getMethodQualifiers().getAddressSpace());
  78. return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
  79. }
  80. /// Returns the canonical formal type of the given C++ method.
  81. static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
  82. return MD->getType()->getCanonicalTypeUnqualified()
  83. .getAs<FunctionProtoType>();
  84. }
  85. /// Returns the "extra-canonicalized" return type, which discards
  86. /// qualifiers on the return type. Codegen doesn't care about them,
  87. /// and it makes ABI code a little easier to be able to assume that
  88. /// all parameter and return types are top-level unqualified.
  89. static CanQualType GetReturnType(QualType RetTy) {
  90. return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
  91. }
  92. /// Arrange the argument and result information for a value of the given
  93. /// unprototyped freestanding function type.
  94. const CGFunctionInfo &
  95. CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
  96. // When translating an unprototyped function type, always use a
  97. // variadic type.
  98. return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
  99. /*instanceMethod=*/false,
  100. /*chainCall=*/false, None,
  101. FTNP->getExtInfo(), {}, RequiredArgs(0));
  102. }
  103. static void addExtParameterInfosForCall(
  104. llvm::SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
  105. const FunctionProtoType *proto,
  106. unsigned prefixArgs,
  107. unsigned totalArgs) {
  108. assert(proto->hasExtParameterInfos());
  109. assert(paramInfos.size() <= prefixArgs);
  110. assert(proto->getNumParams() + prefixArgs <= totalArgs);
  111. paramInfos.reserve(totalArgs);
  112. // Add default infos for any prefix args that don't already have infos.
  113. paramInfos.resize(prefixArgs);
  114. // Add infos for the prototype.
  115. for (const auto &ParamInfo : proto->getExtParameterInfos()) {
  116. paramInfos.push_back(ParamInfo);
  117. // pass_object_size params have no parameter info.
  118. if (ParamInfo.hasPassObjectSize())
  119. paramInfos.emplace_back();
  120. }
  121. assert(paramInfos.size() <= totalArgs &&
  122. "Did we forget to insert pass_object_size args?");
  123. // Add default infos for the variadic and/or suffix arguments.
  124. paramInfos.resize(totalArgs);
  125. }
  126. /// Adds the formal parameters in FPT to the given prefix. If any parameter in
  127. /// FPT has pass_object_size attrs, then we'll add parameters for those, too.
  128. static void appendParameterTypes(const CodeGenTypes &CGT,
  129. SmallVectorImpl<CanQualType> &prefix,
  130. SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
  131. CanQual<FunctionProtoType> FPT) {
  132. // Fast path: don't touch param info if we don't need to.
  133. if (!FPT->hasExtParameterInfos()) {
  134. assert(paramInfos.empty() &&
  135. "We have paramInfos, but the prototype doesn't?");
  136. prefix.append(FPT->param_type_begin(), FPT->param_type_end());
  137. return;
  138. }
  139. unsigned PrefixSize = prefix.size();
  140. // In the vast majority of cases, we'll have precisely FPT->getNumParams()
  141. // parameters; the only thing that can change this is the presence of
  142. // pass_object_size. So, we preallocate for the common case.
  143. prefix.reserve(prefix.size() + FPT->getNumParams());
  144. auto ExtInfos = FPT->getExtParameterInfos();
  145. assert(ExtInfos.size() == FPT->getNumParams());
  146. for (unsigned I = 0, E = FPT->getNumParams(); I != E; ++I) {
  147. prefix.push_back(FPT->getParamType(I));
  148. if (ExtInfos[I].hasPassObjectSize())
  149. prefix.push_back(CGT.getContext().getSizeType());
  150. }
  151. addExtParameterInfosForCall(paramInfos, FPT.getTypePtr(), PrefixSize,
  152. prefix.size());
  153. }
  154. /// Arrange the LLVM function layout for a value of the given function
  155. /// type, on top of any implicit parameters already stored.
  156. static const CGFunctionInfo &
  157. arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
  158. SmallVectorImpl<CanQualType> &prefix,
  159. CanQual<FunctionProtoType> FTP) {
  160. SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
  161. RequiredArgs Required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
  162. // FIXME: Kill copy.
  163. appendParameterTypes(CGT, prefix, paramInfos, FTP);
  164. CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
  165. return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod,
  166. /*chainCall=*/false, prefix,
  167. FTP->getExtInfo(), paramInfos,
  168. Required);
  169. }
  170. /// Arrange the argument and result information for a value of the
  171. /// given freestanding function type.
  172. const CGFunctionInfo &
  173. CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
  174. SmallVector<CanQualType, 16> argTypes;
  175. return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
  176. FTP);
  177. }
  178. static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
  179. // Set the appropriate calling convention for the Function.
  180. if (D->hasAttr<StdCallAttr>())
  181. return CC_X86StdCall;
  182. if (D->hasAttr<FastCallAttr>())
  183. return CC_X86FastCall;
  184. if (D->hasAttr<RegCallAttr>())
  185. return CC_X86RegCall;
  186. if (D->hasAttr<ThisCallAttr>())
  187. return CC_X86ThisCall;
  188. if (D->hasAttr<VectorCallAttr>())
  189. return CC_X86VectorCall;
  190. if (D->hasAttr<PascalAttr>())
  191. return CC_X86Pascal;
  192. if (PcsAttr *PCS = D->getAttr<PcsAttr>())
  193. return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
  194. if (D->hasAttr<AArch64VectorPcsAttr>())
  195. return CC_AArch64VectorCall;
  196. if (D->hasAttr<IntelOclBiccAttr>())
  197. return CC_IntelOclBicc;
  198. if (D->hasAttr<MSABIAttr>())
  199. return IsWindows ? CC_C : CC_Win64;
  200. if (D->hasAttr<SysVABIAttr>())
  201. return IsWindows ? CC_X86_64SysV : CC_C;
  202. if (D->hasAttr<PreserveMostAttr>())
  203. return CC_PreserveMost;
  204. if (D->hasAttr<PreserveAllAttr>())
  205. return CC_PreserveAll;
  206. return CC_C;
  207. }
  208. /// Arrange the argument and result information for a call to an
  209. /// unknown C++ non-static member function of the given abstract type.
  210. /// (A null RD means we don't have any meaningful "this" argument type,
  211. /// so fall back to a generic pointer type).
  212. /// The member function must be an ordinary function, i.e. not a
  213. /// constructor or destructor.
  214. const CGFunctionInfo &
  215. CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
  216. const FunctionProtoType *FTP,
  217. const CXXMethodDecl *MD) {
  218. SmallVector<CanQualType, 16> argTypes;
  219. // Add the 'this' pointer.
  220. argTypes.push_back(DeriveThisType(RD, MD));
  221. return ::arrangeLLVMFunctionInfo(
  222. *this, true, argTypes,
  223. FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
  224. }
  225. /// Set calling convention for CUDA/HIP kernel.
  226. static void setCUDAKernelCallingConvention(CanQualType &FTy, CodeGenModule &CGM,
  227. const FunctionDecl *FD) {
  228. if (FD->hasAttr<CUDAGlobalAttr>()) {
  229. const FunctionType *FT = FTy->getAs<FunctionType>();
  230. CGM.getTargetCodeGenInfo().setCUDAKernelCallingConvention(FT);
  231. FTy = FT->getCanonicalTypeUnqualified();
  232. }
  233. }
  234. /// Arrange the argument and result information for a declaration or
  235. /// definition of the given C++ non-static member function. The
  236. /// member function must be an ordinary function, i.e. not a
  237. /// constructor or destructor.
  238. const CGFunctionInfo &
  239. CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
  240. assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
  241. assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
  242. CanQualType FT = GetFormalType(MD).getAs<Type>();
  243. setCUDAKernelCallingConvention(FT, CGM, MD);
  244. auto prototype = FT.getAs<FunctionProtoType>();
  245. if (MD->isInstance()) {
  246. // The abstract case is perfectly fine.
  247. const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
  248. return arrangeCXXMethodType(ThisType, prototype.getTypePtr(), MD);
  249. }
  250. return arrangeFreeFunctionType(prototype);
  251. }
  252. bool CodeGenTypes::inheritingCtorHasParams(
  253. const InheritedConstructor &Inherited, CXXCtorType Type) {
  254. // Parameters are unnecessary if we're constructing a base class subobject
  255. // and the inherited constructor lives in a virtual base.
  256. return Type == Ctor_Complete ||
  257. !Inherited.getShadowDecl()->constructsVirtualBase() ||
  258. !Target.getCXXABI().hasConstructorVariants();
  259. }
  260. const CGFunctionInfo &
  261. CodeGenTypes::arrangeCXXStructorDeclaration(GlobalDecl GD) {
  262. auto *MD = cast<CXXMethodDecl>(GD.getDecl());
  263. SmallVector<CanQualType, 16> argTypes;
  264. SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
  265. argTypes.push_back(DeriveThisType(MD->getParent(), MD));
  266. bool PassParams = true;
  267. if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
  268. // A base class inheriting constructor doesn't get forwarded arguments
  269. // needed to construct a virtual base (or base class thereof).
  270. if (auto Inherited = CD->getInheritedConstructor())
  271. PassParams = inheritingCtorHasParams(Inherited, GD.getCtorType());
  272. }
  273. CanQual<FunctionProtoType> FTP = GetFormalType(MD);
  274. // Add the formal parameters.
  275. if (PassParams)
  276. appendParameterTypes(*this, argTypes, paramInfos, FTP);
  277. CGCXXABI::AddedStructorArgs AddedArgs =
  278. TheCXXABI.buildStructorSignature(GD, argTypes);
  279. if (!paramInfos.empty()) {
  280. // Note: prefix implies after the first param.
  281. if (AddedArgs.Prefix)
  282. paramInfos.insert(paramInfos.begin() + 1, AddedArgs.Prefix,
  283. FunctionProtoType::ExtParameterInfo{});
  284. if (AddedArgs.Suffix)
  285. paramInfos.append(AddedArgs.Suffix,
  286. FunctionProtoType::ExtParameterInfo{});
  287. }
  288. RequiredArgs required =
  289. (PassParams && MD->isVariadic() ? RequiredArgs(argTypes.size())
  290. : RequiredArgs::All);
  291. FunctionType::ExtInfo extInfo = FTP->getExtInfo();
  292. CanQualType resultType = TheCXXABI.HasThisReturn(GD)
  293. ? argTypes.front()
  294. : TheCXXABI.hasMostDerivedReturn(GD)
  295. ? CGM.getContext().VoidPtrTy
  296. : Context.VoidTy;
  297. return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true,
  298. /*chainCall=*/false, argTypes, extInfo,
  299. paramInfos, required);
  300. }
  301. static SmallVector<CanQualType, 16>
  302. getArgTypesForCall(ASTContext &ctx, const CallArgList &args) {
  303. SmallVector<CanQualType, 16> argTypes;
  304. for (auto &arg : args)
  305. argTypes.push_back(ctx.getCanonicalParamType(arg.Ty));
  306. return argTypes;
  307. }
  308. static SmallVector<CanQualType, 16>
  309. getArgTypesForDeclaration(ASTContext &ctx, const FunctionArgList &args) {
  310. SmallVector<CanQualType, 16> argTypes;
  311. for (auto &arg : args)
  312. argTypes.push_back(ctx.getCanonicalParamType(arg->getType()));
  313. return argTypes;
  314. }
  315. static llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16>
  316. getExtParameterInfosForCall(const FunctionProtoType *proto,
  317. unsigned prefixArgs, unsigned totalArgs) {
  318. llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> result;
  319. if (proto->hasExtParameterInfos()) {
  320. addExtParameterInfosForCall(result, proto, prefixArgs, totalArgs);
  321. }
  322. return result;
  323. }
  324. /// Arrange a call to a C++ method, passing the given arguments.
  325. ///
  326. /// ExtraPrefixArgs is the number of ABI-specific args passed after the `this`
  327. /// parameter.
  328. /// ExtraSuffixArgs is the number of ABI-specific args passed at the end of
  329. /// args.
  330. /// PassProtoArgs indicates whether `args` has args for the parameters in the
  331. /// given CXXConstructorDecl.
  332. const CGFunctionInfo &
  333. CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
  334. const CXXConstructorDecl *D,
  335. CXXCtorType CtorKind,
  336. unsigned ExtraPrefixArgs,
  337. unsigned ExtraSuffixArgs,
  338. bool PassProtoArgs) {
  339. // FIXME: Kill copy.
  340. SmallVector<CanQualType, 16> ArgTypes;
  341. for (const auto &Arg : args)
  342. ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
  343. // +1 for implicit this, which should always be args[0].
  344. unsigned TotalPrefixArgs = 1 + ExtraPrefixArgs;
  345. CanQual<FunctionProtoType> FPT = GetFormalType(D);
  346. RequiredArgs Required = PassProtoArgs
  347. ? RequiredArgs::forPrototypePlus(
  348. FPT, TotalPrefixArgs + ExtraSuffixArgs)
  349. : RequiredArgs::All;
  350. GlobalDecl GD(D, CtorKind);
  351. CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
  352. ? ArgTypes.front()
  353. : TheCXXABI.hasMostDerivedReturn(GD)
  354. ? CGM.getContext().VoidPtrTy
  355. : Context.VoidTy;
  356. FunctionType::ExtInfo Info = FPT->getExtInfo();
  357. llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> ParamInfos;
  358. // If the prototype args are elided, we should only have ABI-specific args,
  359. // which never have param info.
  360. if (PassProtoArgs && FPT->hasExtParameterInfos()) {
  361. // ABI-specific suffix arguments are treated the same as variadic arguments.
  362. addExtParameterInfosForCall(ParamInfos, FPT.getTypePtr(), TotalPrefixArgs,
  363. ArgTypes.size());
  364. }
  365. return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true,
  366. /*chainCall=*/false, ArgTypes, Info,
  367. ParamInfos, Required);
  368. }
  369. /// Arrange the argument and result information for the declaration or
  370. /// definition of the given function.
  371. const CGFunctionInfo &
  372. CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
  373. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
  374. if (MD->isInstance())
  375. return arrangeCXXMethodDeclaration(MD);
  376. CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
  377. assert(isa<FunctionType>(FTy));
  378. setCUDAKernelCallingConvention(FTy, CGM, FD);
  379. // When declaring a function without a prototype, always use a
  380. // non-variadic type.
  381. if (CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>()) {
  382. return arrangeLLVMFunctionInfo(
  383. noProto->getReturnType(), /*instanceMethod=*/false,
  384. /*chainCall=*/false, None, noProto->getExtInfo(), {},RequiredArgs::All);
  385. }
  386. return arrangeFreeFunctionType(FTy.castAs<FunctionProtoType>());
  387. }
  388. /// Arrange the argument and result information for the declaration or
  389. /// definition of an Objective-C method.
  390. const CGFunctionInfo &
  391. CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
  392. // It happens that this is the same as a call with no optional
  393. // arguments, except also using the formal 'self' type.
  394. return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
  395. }
  396. /// Arrange the argument and result information for the function type
  397. /// through which to perform a send to the given Objective-C method,
  398. /// using the given receiver type. The receiver type is not always
  399. /// the 'self' type of the method or even an Objective-C pointer type.
  400. /// This is *not* the right method for actually performing such a
  401. /// message send, due to the possibility of optional arguments.
  402. const CGFunctionInfo &
  403. CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
  404. QualType receiverType) {
  405. SmallVector<CanQualType, 16> argTys;
  406. SmallVector<FunctionProtoType::ExtParameterInfo, 4> extParamInfos(2);
  407. argTys.push_back(Context.getCanonicalParamType(receiverType));
  408. argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
  409. // FIXME: Kill copy?
  410. for (const auto *I : MD->parameters()) {
  411. argTys.push_back(Context.getCanonicalParamType(I->getType()));
  412. auto extParamInfo = FunctionProtoType::ExtParameterInfo().withIsNoEscape(
  413. I->hasAttr<NoEscapeAttr>());
  414. extParamInfos.push_back(extParamInfo);
  415. }
  416. FunctionType::ExtInfo einfo;
  417. bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
  418. einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
  419. if (getContext().getLangOpts().ObjCAutoRefCount &&
  420. MD->hasAttr<NSReturnsRetainedAttr>())
  421. einfo = einfo.withProducesResult(true);
  422. RequiredArgs required =
  423. (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
  424. return arrangeLLVMFunctionInfo(
  425. GetReturnType(MD->getReturnType()), /*instanceMethod=*/false,
  426. /*chainCall=*/false, argTys, einfo, extParamInfos, required);
  427. }
  428. const CGFunctionInfo &
  429. CodeGenTypes::arrangeUnprototypedObjCMessageSend(QualType returnType,
  430. const CallArgList &args) {
  431. auto argTypes = getArgTypesForCall(Context, args);
  432. FunctionType::ExtInfo einfo;
  433. return arrangeLLVMFunctionInfo(
  434. GetReturnType(returnType), /*instanceMethod=*/false,
  435. /*chainCall=*/false, argTypes, einfo, {}, RequiredArgs::All);
  436. }
  437. const CGFunctionInfo &
  438. CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
  439. // FIXME: Do we need to handle ObjCMethodDecl?
  440. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  441. if (isa<CXXConstructorDecl>(GD.getDecl()) ||
  442. isa<CXXDestructorDecl>(GD.getDecl()))
  443. return arrangeCXXStructorDeclaration(GD);
  444. return arrangeFunctionDeclaration(FD);
  445. }
  446. /// Arrange a thunk that takes 'this' as the first parameter followed by
  447. /// varargs. Return a void pointer, regardless of the actual return type.
  448. /// The body of the thunk will end in a musttail call to a function of the
  449. /// correct type, and the caller will bitcast the function to the correct
  450. /// prototype.
  451. const CGFunctionInfo &
  452. CodeGenTypes::arrangeUnprototypedMustTailThunk(const CXXMethodDecl *MD) {
  453. assert(MD->isVirtual() && "only methods have thunks");
  454. CanQual<FunctionProtoType> FTP = GetFormalType(MD);
  455. CanQualType ArgTys[] = {DeriveThisType(MD->getParent(), MD)};
  456. return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false,
  457. /*chainCall=*/false, ArgTys,
  458. FTP->getExtInfo(), {}, RequiredArgs(1));
  459. }
  460. const CGFunctionInfo &
  461. CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl *CD,
  462. CXXCtorType CT) {
  463. assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
  464. CanQual<FunctionProtoType> FTP = GetFormalType(CD);
  465. SmallVector<CanQualType, 2> ArgTys;
  466. const CXXRecordDecl *RD = CD->getParent();
  467. ArgTys.push_back(DeriveThisType(RD, CD));
  468. if (CT == Ctor_CopyingClosure)
  469. ArgTys.push_back(*FTP->param_type_begin());
  470. if (RD->getNumVBases() > 0)
  471. ArgTys.push_back(Context.IntTy);
  472. CallingConv CC = Context.getDefaultCallingConvention(
  473. /*IsVariadic=*/false, /*IsCXXMethod=*/true);
  474. return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/true,
  475. /*chainCall=*/false, ArgTys,
  476. FunctionType::ExtInfo(CC), {},
  477. RequiredArgs::All);
  478. }
  479. /// Arrange a call as unto a free function, except possibly with an
  480. /// additional number of formal parameters considered required.
  481. static const CGFunctionInfo &
  482. arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
  483. CodeGenModule &CGM,
  484. const CallArgList &args,
  485. const FunctionType *fnType,
  486. unsigned numExtraRequiredArgs,
  487. bool chainCall) {
  488. assert(args.size() >= numExtraRequiredArgs);
  489. llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
  490. // In most cases, there are no optional arguments.
  491. RequiredArgs required = RequiredArgs::All;
  492. // If we have a variadic prototype, the required arguments are the
  493. // extra prefix plus the arguments in the prototype.
  494. if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
  495. if (proto->isVariadic())
  496. required = RequiredArgs::forPrototypePlus(proto, numExtraRequiredArgs);
  497. if (proto->hasExtParameterInfos())
  498. addExtParameterInfosForCall(paramInfos, proto, numExtraRequiredArgs,
  499. args.size());
  500. // If we don't have a prototype at all, but we're supposed to
  501. // explicitly use the variadic convention for unprototyped calls,
  502. // treat all of the arguments as required but preserve the nominal
  503. // possibility of variadics.
  504. } else if (CGM.getTargetCodeGenInfo()
  505. .isNoProtoCallVariadic(args,
  506. cast<FunctionNoProtoType>(fnType))) {
  507. required = RequiredArgs(args.size());
  508. }
  509. // FIXME: Kill copy.
  510. SmallVector<CanQualType, 16> argTypes;
  511. for (const auto &arg : args)
  512. argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
  513. return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()),
  514. /*instanceMethod=*/false, chainCall,
  515. argTypes, fnType->getExtInfo(), paramInfos,
  516. required);
  517. }
  518. /// Figure out the rules for calling a function with the given formal
  519. /// type using the given arguments. The arguments are necessary
  520. /// because the function might be unprototyped, in which case it's
  521. /// target-dependent in crazy ways.
  522. const CGFunctionInfo &
  523. CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
  524. const FunctionType *fnType,
  525. bool chainCall) {
  526. return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
  527. chainCall ? 1 : 0, chainCall);
  528. }
  529. /// A block function is essentially a free function with an
  530. /// extra implicit argument.
  531. const CGFunctionInfo &
  532. CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
  533. const FunctionType *fnType) {
  534. return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
  535. /*chainCall=*/false);
  536. }
  537. const CGFunctionInfo &
  538. CodeGenTypes::arrangeBlockFunctionDeclaration(const FunctionProtoType *proto,
  539. const FunctionArgList &params) {
  540. auto paramInfos = getExtParameterInfosForCall(proto, 1, params.size());
  541. auto argTypes = getArgTypesForDeclaration(Context, params);
  542. return arrangeLLVMFunctionInfo(GetReturnType(proto->getReturnType()),
  543. /*instanceMethod*/ false, /*chainCall*/ false,
  544. argTypes, proto->getExtInfo(), paramInfos,
  545. RequiredArgs::forPrototypePlus(proto, 1));
  546. }
  547. const CGFunctionInfo &
  548. CodeGenTypes::arrangeBuiltinFunctionCall(QualType resultType,
  549. const CallArgList &args) {
  550. // FIXME: Kill copy.
  551. SmallVector<CanQualType, 16> argTypes;
  552. for (const auto &Arg : args)
  553. argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
  554. return arrangeLLVMFunctionInfo(
  555. GetReturnType(resultType), /*instanceMethod=*/false,
  556. /*chainCall=*/false, argTypes, FunctionType::ExtInfo(),
  557. /*paramInfos=*/ {}, RequiredArgs::All);
  558. }
  559. const CGFunctionInfo &
  560. CodeGenTypes::arrangeBuiltinFunctionDeclaration(QualType resultType,
  561. const FunctionArgList &args) {
  562. auto argTypes = getArgTypesForDeclaration(Context, args);
  563. return arrangeLLVMFunctionInfo(
  564. GetReturnType(resultType), /*instanceMethod=*/false, /*chainCall=*/false,
  565. argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
  566. }
  567. const CGFunctionInfo &
  568. CodeGenTypes::arrangeBuiltinFunctionDeclaration(CanQualType resultType,
  569. ArrayRef<CanQualType> argTypes) {
  570. return arrangeLLVMFunctionInfo(
  571. resultType, /*instanceMethod=*/false, /*chainCall=*/false,
  572. argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
  573. }
  574. /// Arrange a call to a C++ method, passing the given arguments.
  575. ///
  576. /// numPrefixArgs is the number of ABI-specific prefix arguments we have. It
  577. /// does not count `this`.
  578. const CGFunctionInfo &
  579. CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
  580. const FunctionProtoType *proto,
  581. RequiredArgs required,
  582. unsigned numPrefixArgs) {
  583. assert(numPrefixArgs + 1 <= args.size() &&
  584. "Emitting a call with less args than the required prefix?");
  585. // Add one to account for `this`. It's a bit awkward here, but we don't count
  586. // `this` in similar places elsewhere.
  587. auto paramInfos =
  588. getExtParameterInfosForCall(proto, numPrefixArgs + 1, args.size());
  589. // FIXME: Kill copy.
  590. auto argTypes = getArgTypesForCall(Context, args);
  591. FunctionType::ExtInfo info = proto->getExtInfo();
  592. return arrangeLLVMFunctionInfo(
  593. GetReturnType(proto->getReturnType()), /*instanceMethod=*/true,
  594. /*chainCall=*/false, argTypes, info, paramInfos, required);
  595. }
  596. const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
  597. return arrangeLLVMFunctionInfo(
  598. getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false,
  599. None, FunctionType::ExtInfo(), {}, RequiredArgs::All);
  600. }
  601. const CGFunctionInfo &
  602. CodeGenTypes::arrangeCall(const CGFunctionInfo &signature,
  603. const CallArgList &args) {
  604. assert(signature.arg_size() <= args.size());
  605. if (signature.arg_size() == args.size())
  606. return signature;
  607. SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
  608. auto sigParamInfos = signature.getExtParameterInfos();
  609. if (!sigParamInfos.empty()) {
  610. paramInfos.append(sigParamInfos.begin(), sigParamInfos.end());
  611. paramInfos.resize(args.size());
  612. }
  613. auto argTypes = getArgTypesForCall(Context, args);
  614. assert(signature.getRequiredArgs().allowsOptionalArgs());
  615. return arrangeLLVMFunctionInfo(signature.getReturnType(),
  616. signature.isInstanceMethod(),
  617. signature.isChainCall(),
  618. argTypes,
  619. signature.getExtInfo(),
  620. paramInfos,
  621. signature.getRequiredArgs());
  622. }
  623. namespace clang {
  624. namespace CodeGen {
  625. void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI);
  626. }
  627. }
  628. /// Arrange the argument and result information for an abstract value
  629. /// of a given function type. This is the method which all of the
  630. /// above functions ultimately defer to.
  631. const CGFunctionInfo &
  632. CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
  633. bool instanceMethod,
  634. bool chainCall,
  635. ArrayRef<CanQualType> argTypes,
  636. FunctionType::ExtInfo info,
  637. ArrayRef<FunctionProtoType::ExtParameterInfo> paramInfos,
  638. RequiredArgs required) {
  639. assert(llvm::all_of(argTypes,
  640. [](CanQualType T) { return T.isCanonicalAsParam(); }));
  641. // Lookup or create unique function info.
  642. llvm::FoldingSetNodeID ID;
  643. CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, paramInfos,
  644. required, resultType, argTypes);
  645. void *insertPos = nullptr;
  646. CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
  647. if (FI)
  648. return *FI;
  649. unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
  650. // Construct the function info. We co-allocate the ArgInfos.
  651. FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
  652. paramInfos, resultType, argTypes, required);
  653. FunctionInfos.InsertNode(FI, insertPos);
  654. bool inserted = FunctionsBeingProcessed.insert(FI).second;
  655. (void)inserted;
  656. assert(inserted && "Recursively being processed?");
  657. // Compute ABI information.
  658. if (CC == llvm::CallingConv::SPIR_KERNEL) {
  659. // Force target independent argument handling for the host visible
  660. // kernel functions.
  661. computeSPIRKernelABIInfo(CGM, *FI);
  662. } else if (info.getCC() == CC_Swift) {
  663. swiftcall::computeABIInfo(CGM, *FI);
  664. } else {
  665. getABIInfo().computeInfo(*FI);
  666. }
  667. // Loop over all of the computed argument and return value info. If any of
  668. // them are direct or extend without a specified coerce type, specify the
  669. // default now.
  670. ABIArgInfo &retInfo = FI->getReturnInfo();
  671. if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
  672. retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
  673. for (auto &I : FI->arguments())
  674. if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
  675. I.info.setCoerceToType(ConvertType(I.type));
  676. bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
  677. assert(erased && "Not in set?");
  678. return *FI;
  679. }
  680. CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
  681. bool instanceMethod,
  682. bool chainCall,
  683. const FunctionType::ExtInfo &info,
  684. ArrayRef<ExtParameterInfo> paramInfos,
  685. CanQualType resultType,
  686. ArrayRef<CanQualType> argTypes,
  687. RequiredArgs required) {
  688. assert(paramInfos.empty() || paramInfos.size() == argTypes.size());
  689. assert(!required.allowsOptionalArgs() ||
  690. required.getNumRequiredArgs() <= argTypes.size());
  691. void *buffer =
  692. operator new(totalSizeToAlloc<ArgInfo, ExtParameterInfo>(
  693. argTypes.size() + 1, paramInfos.size()));
  694. CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
  695. FI->CallingConvention = llvmCC;
  696. FI->EffectiveCallingConvention = llvmCC;
  697. FI->ASTCallingConvention = info.getCC();
  698. FI->InstanceMethod = instanceMethod;
  699. FI->ChainCall = chainCall;
  700. FI->NoReturn = info.getNoReturn();
  701. FI->ReturnsRetained = info.getProducesResult();
  702. FI->NoCallerSavedRegs = info.getNoCallerSavedRegs();
  703. FI->NoCfCheck = info.getNoCfCheck();
  704. FI->Required = required;
  705. FI->HasRegParm = info.getHasRegParm();
  706. FI->RegParm = info.getRegParm();
  707. FI->ArgStruct = nullptr;
  708. FI->ArgStructAlign = 0;
  709. FI->NumArgs = argTypes.size();
  710. FI->HasExtParameterInfos = !paramInfos.empty();
  711. FI->getArgsBuffer()[0].type = resultType;
  712. for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
  713. FI->getArgsBuffer()[i + 1].type = argTypes[i];
  714. for (unsigned i = 0, e = paramInfos.size(); i != e; ++i)
  715. FI->getExtParameterInfosBuffer()[i] = paramInfos[i];
  716. return FI;
  717. }
  718. /***/
  719. namespace {
  720. // ABIArgInfo::Expand implementation.
  721. // Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
  722. struct TypeExpansion {
  723. enum TypeExpansionKind {
  724. // Elements of constant arrays are expanded recursively.
  725. TEK_ConstantArray,
  726. // Record fields are expanded recursively (but if record is a union, only
  727. // the field with the largest size is expanded).
  728. TEK_Record,
  729. // For complex types, real and imaginary parts are expanded recursively.
  730. TEK_Complex,
  731. // All other types are not expandable.
  732. TEK_None
  733. };
  734. const TypeExpansionKind Kind;
  735. TypeExpansion(TypeExpansionKind K) : Kind(K) {}
  736. virtual ~TypeExpansion() {}
  737. };
  738. struct ConstantArrayExpansion : TypeExpansion {
  739. QualType EltTy;
  740. uint64_t NumElts;
  741. ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
  742. : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
  743. static bool classof(const TypeExpansion *TE) {
  744. return TE->Kind == TEK_ConstantArray;
  745. }
  746. };
  747. struct RecordExpansion : TypeExpansion {
  748. SmallVector<const CXXBaseSpecifier *, 1> Bases;
  749. SmallVector<const FieldDecl *, 1> Fields;
  750. RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
  751. SmallVector<const FieldDecl *, 1> &&Fields)
  752. : TypeExpansion(TEK_Record), Bases(std::move(Bases)),
  753. Fields(std::move(Fields)) {}
  754. static bool classof(const TypeExpansion *TE) {
  755. return TE->Kind == TEK_Record;
  756. }
  757. };
  758. struct ComplexExpansion : TypeExpansion {
  759. QualType EltTy;
  760. ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
  761. static bool classof(const TypeExpansion *TE) {
  762. return TE->Kind == TEK_Complex;
  763. }
  764. };
  765. struct NoExpansion : TypeExpansion {
  766. NoExpansion() : TypeExpansion(TEK_None) {}
  767. static bool classof(const TypeExpansion *TE) {
  768. return TE->Kind == TEK_None;
  769. }
  770. };
  771. } // namespace
  772. static std::unique_ptr<TypeExpansion>
  773. getTypeExpansion(QualType Ty, const ASTContext &Context) {
  774. if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
  775. return std::make_unique<ConstantArrayExpansion>(
  776. AT->getElementType(), AT->getSize().getZExtValue());
  777. }
  778. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  779. SmallVector<const CXXBaseSpecifier *, 1> Bases;
  780. SmallVector<const FieldDecl *, 1> Fields;
  781. const RecordDecl *RD = RT->getDecl();
  782. assert(!RD->hasFlexibleArrayMember() &&
  783. "Cannot expand structure with flexible array.");
  784. if (RD->isUnion()) {
  785. // Unions can be here only in degenerative cases - all the fields are same
  786. // after flattening. Thus we have to use the "largest" field.
  787. const FieldDecl *LargestFD = nullptr;
  788. CharUnits UnionSize = CharUnits::Zero();
  789. for (const auto *FD : RD->fields()) {
  790. if (FD->isZeroLengthBitField(Context))
  791. continue;
  792. assert(!FD->isBitField() &&
  793. "Cannot expand structure with bit-field members.");
  794. CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
  795. if (UnionSize < FieldSize) {
  796. UnionSize = FieldSize;
  797. LargestFD = FD;
  798. }
  799. }
  800. if (LargestFD)
  801. Fields.push_back(LargestFD);
  802. } else {
  803. if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  804. assert(!CXXRD->isDynamicClass() &&
  805. "cannot expand vtable pointers in dynamic classes");
  806. for (const CXXBaseSpecifier &BS : CXXRD->bases())
  807. Bases.push_back(&BS);
  808. }
  809. for (const auto *FD : RD->fields()) {
  810. if (FD->isZeroLengthBitField(Context))
  811. continue;
  812. assert(!FD->isBitField() &&
  813. "Cannot expand structure with bit-field members.");
  814. Fields.push_back(FD);
  815. }
  816. }
  817. return std::make_unique<RecordExpansion>(std::move(Bases),
  818. std::move(Fields));
  819. }
  820. if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
  821. return std::make_unique<ComplexExpansion>(CT->getElementType());
  822. }
  823. return std::make_unique<NoExpansion>();
  824. }
  825. static int getExpansionSize(QualType Ty, const ASTContext &Context) {
  826. auto Exp = getTypeExpansion(Ty, Context);
  827. if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
  828. return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
  829. }
  830. if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
  831. int Res = 0;
  832. for (auto BS : RExp->Bases)
  833. Res += getExpansionSize(BS->getType(), Context);
  834. for (auto FD : RExp->Fields)
  835. Res += getExpansionSize(FD->getType(), Context);
  836. return Res;
  837. }
  838. if (isa<ComplexExpansion>(Exp.get()))
  839. return 2;
  840. assert(isa<NoExpansion>(Exp.get()));
  841. return 1;
  842. }
  843. void
  844. CodeGenTypes::getExpandedTypes(QualType Ty,
  845. SmallVectorImpl<llvm::Type *>::iterator &TI) {
  846. auto Exp = getTypeExpansion(Ty, Context);
  847. if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
  848. for (int i = 0, n = CAExp->NumElts; i < n; i++) {
  849. getExpandedTypes(CAExp->EltTy, TI);
  850. }
  851. } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
  852. for (auto BS : RExp->Bases)
  853. getExpandedTypes(BS->getType(), TI);
  854. for (auto FD : RExp->Fields)
  855. getExpandedTypes(FD->getType(), TI);
  856. } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
  857. llvm::Type *EltTy = ConvertType(CExp->EltTy);
  858. *TI++ = EltTy;
  859. *TI++ = EltTy;
  860. } else {
  861. assert(isa<NoExpansion>(Exp.get()));
  862. *TI++ = ConvertType(Ty);
  863. }
  864. }
  865. static void forConstantArrayExpansion(CodeGenFunction &CGF,
  866. ConstantArrayExpansion *CAE,
  867. Address BaseAddr,
  868. llvm::function_ref<void(Address)> Fn) {
  869. CharUnits EltSize = CGF.getContext().getTypeSizeInChars(CAE->EltTy);
  870. CharUnits EltAlign =
  871. BaseAddr.getAlignment().alignmentOfArrayElement(EltSize);
  872. for (int i = 0, n = CAE->NumElts; i < n; i++) {
  873. llvm::Value *EltAddr =
  874. CGF.Builder.CreateConstGEP2_32(nullptr, BaseAddr.getPointer(), 0, i);
  875. Fn(Address(EltAddr, EltAlign));
  876. }
  877. }
  878. void CodeGenFunction::ExpandTypeFromArgs(
  879. QualType Ty, LValue LV, SmallVectorImpl<llvm::Value *>::iterator &AI) {
  880. assert(LV.isSimple() &&
  881. "Unexpected non-simple lvalue during struct expansion.");
  882. auto Exp = getTypeExpansion(Ty, getContext());
  883. if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
  884. forConstantArrayExpansion(*this, CAExp, LV.getAddress(),
  885. [&](Address EltAddr) {
  886. LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
  887. ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
  888. });
  889. } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
  890. Address This = LV.getAddress();
  891. for (const CXXBaseSpecifier *BS : RExp->Bases) {
  892. // Perform a single step derived-to-base conversion.
  893. Address Base =
  894. GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
  895. /*NullCheckValue=*/false, SourceLocation());
  896. LValue SubLV = MakeAddrLValue(Base, BS->getType());
  897. // Recurse onto bases.
  898. ExpandTypeFromArgs(BS->getType(), SubLV, AI);
  899. }
  900. for (auto FD : RExp->Fields) {
  901. // FIXME: What are the right qualifiers here?
  902. LValue SubLV = EmitLValueForFieldInitialization(LV, FD);
  903. ExpandTypeFromArgs(FD->getType(), SubLV, AI);
  904. }
  905. } else if (isa<ComplexExpansion>(Exp.get())) {
  906. auto realValue = *AI++;
  907. auto imagValue = *AI++;
  908. EmitStoreOfComplex(ComplexPairTy(realValue, imagValue), LV, /*init*/ true);
  909. } else {
  910. assert(isa<NoExpansion>(Exp.get()));
  911. EmitStoreThroughLValue(RValue::get(*AI++), LV);
  912. }
  913. }
  914. void CodeGenFunction::ExpandTypeToArgs(
  915. QualType Ty, CallArg Arg, llvm::FunctionType *IRFuncTy,
  916. SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
  917. auto Exp = getTypeExpansion(Ty, getContext());
  918. if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
  919. Address Addr = Arg.hasLValue() ? Arg.getKnownLValue().getAddress()
  920. : Arg.getKnownRValue().getAggregateAddress();
  921. forConstantArrayExpansion(
  922. *this, CAExp, Addr, [&](Address EltAddr) {
  923. CallArg EltArg = CallArg(
  924. convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation()),
  925. CAExp->EltTy);
  926. ExpandTypeToArgs(CAExp->EltTy, EltArg, IRFuncTy, IRCallArgs,
  927. IRCallArgPos);
  928. });
  929. } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
  930. Address This = Arg.hasLValue() ? Arg.getKnownLValue().getAddress()
  931. : Arg.getKnownRValue().getAggregateAddress();
  932. for (const CXXBaseSpecifier *BS : RExp->Bases) {
  933. // Perform a single step derived-to-base conversion.
  934. Address Base =
  935. GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
  936. /*NullCheckValue=*/false, SourceLocation());
  937. CallArg BaseArg = CallArg(RValue::getAggregate(Base), BS->getType());
  938. // Recurse onto bases.
  939. ExpandTypeToArgs(BS->getType(), BaseArg, IRFuncTy, IRCallArgs,
  940. IRCallArgPos);
  941. }
  942. LValue LV = MakeAddrLValue(This, Ty);
  943. for (auto FD : RExp->Fields) {
  944. CallArg FldArg =
  945. CallArg(EmitRValueForField(LV, FD, SourceLocation()), FD->getType());
  946. ExpandTypeToArgs(FD->getType(), FldArg, IRFuncTy, IRCallArgs,
  947. IRCallArgPos);
  948. }
  949. } else if (isa<ComplexExpansion>(Exp.get())) {
  950. ComplexPairTy CV = Arg.getKnownRValue().getComplexVal();
  951. IRCallArgs[IRCallArgPos++] = CV.first;
  952. IRCallArgs[IRCallArgPos++] = CV.second;
  953. } else {
  954. assert(isa<NoExpansion>(Exp.get()));
  955. auto RV = Arg.getKnownRValue();
  956. assert(RV.isScalar() &&
  957. "Unexpected non-scalar rvalue during struct expansion.");
  958. // Insert a bitcast as needed.
  959. llvm::Value *V = RV.getScalarVal();
  960. if (IRCallArgPos < IRFuncTy->getNumParams() &&
  961. V->getType() != IRFuncTy->getParamType(IRCallArgPos))
  962. V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
  963. IRCallArgs[IRCallArgPos++] = V;
  964. }
  965. }
  966. /// Create a temporary allocation for the purposes of coercion.
  967. static Address CreateTempAllocaForCoercion(CodeGenFunction &CGF, llvm::Type *Ty,
  968. CharUnits MinAlign) {
  969. // Don't use an alignment that's worse than what LLVM would prefer.
  970. auto PrefAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(Ty);
  971. CharUnits Align = std::max(MinAlign, CharUnits::fromQuantity(PrefAlign));
  972. return CGF.CreateTempAlloca(Ty, Align);
  973. }
  974. /// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
  975. /// accessing some number of bytes out of it, try to gep into the struct to get
  976. /// at its inner goodness. Dive as deep as possible without entering an element
  977. /// with an in-memory size smaller than DstSize.
  978. static Address
  979. EnterStructPointerForCoercedAccess(Address SrcPtr,
  980. llvm::StructType *SrcSTy,
  981. uint64_t DstSize, CodeGenFunction &CGF) {
  982. // We can't dive into a zero-element struct.
  983. if (SrcSTy->getNumElements() == 0) return SrcPtr;
  984. llvm::Type *FirstElt = SrcSTy->getElementType(0);
  985. // If the first elt is at least as large as what we're looking for, or if the
  986. // first element is the same size as the whole struct, we can enter it. The
  987. // comparison must be made on the store size and not the alloca size. Using
  988. // the alloca size may overstate the size of the load.
  989. uint64_t FirstEltSize =
  990. CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
  991. if (FirstEltSize < DstSize &&
  992. FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
  993. return SrcPtr;
  994. // GEP into the first element.
  995. SrcPtr = CGF.Builder.CreateStructGEP(SrcPtr, 0, "coerce.dive");
  996. // If the first element is a struct, recurse.
  997. llvm::Type *SrcTy = SrcPtr.getElementType();
  998. if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
  999. return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
  1000. return SrcPtr;
  1001. }
  1002. /// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
  1003. /// are either integers or pointers. This does a truncation of the value if it
  1004. /// is too large or a zero extension if it is too small.
  1005. ///
  1006. /// This behaves as if the value were coerced through memory, so on big-endian
  1007. /// targets the high bits are preserved in a truncation, while little-endian
  1008. /// targets preserve the low bits.
  1009. static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
  1010. llvm::Type *Ty,
  1011. CodeGenFunction &CGF) {
  1012. if (Val->getType() == Ty)
  1013. return Val;
  1014. if (isa<llvm::PointerType>(Val->getType())) {
  1015. // If this is Pointer->Pointer avoid conversion to and from int.
  1016. if (isa<llvm::PointerType>(Ty))
  1017. return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
  1018. // Convert the pointer to an integer so we can play with its width.
  1019. Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
  1020. }
  1021. llvm::Type *DestIntTy = Ty;
  1022. if (isa<llvm::PointerType>(DestIntTy))
  1023. DestIntTy = CGF.IntPtrTy;
  1024. if (Val->getType() != DestIntTy) {
  1025. const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
  1026. if (DL.isBigEndian()) {
  1027. // Preserve the high bits on big-endian targets.
  1028. // That is what memory coercion does.
  1029. uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
  1030. uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
  1031. if (SrcSize > DstSize) {
  1032. Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
  1033. Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
  1034. } else {
  1035. Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
  1036. Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
  1037. }
  1038. } else {
  1039. // Little-endian targets preserve the low bits. No shifts required.
  1040. Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
  1041. }
  1042. }
  1043. if (isa<llvm::PointerType>(Ty))
  1044. Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
  1045. return Val;
  1046. }
  1047. /// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
  1048. /// a pointer to an object of type \arg Ty, known to be aligned to
  1049. /// \arg SrcAlign bytes.
  1050. ///
  1051. /// This safely handles the case when the src type is smaller than the
  1052. /// destination type; in this situation the values of bits which not
  1053. /// present in the src are undefined.
  1054. static llvm::Value *CreateCoercedLoad(Address Src, llvm::Type *Ty,
  1055. CodeGenFunction &CGF) {
  1056. llvm::Type *SrcTy = Src.getElementType();
  1057. // If SrcTy and Ty are the same, just do a load.
  1058. if (SrcTy == Ty)
  1059. return CGF.Builder.CreateLoad(Src);
  1060. uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
  1061. if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
  1062. Src = EnterStructPointerForCoercedAccess(Src, SrcSTy, DstSize, CGF);
  1063. SrcTy = Src.getType()->getElementType();
  1064. }
  1065. uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
  1066. // If the source and destination are integer or pointer types, just do an
  1067. // extension or truncation to the desired type.
  1068. if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
  1069. (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
  1070. llvm::Value *Load = CGF.Builder.CreateLoad(Src);
  1071. return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
  1072. }
  1073. // If load is legal, just bitcast the src pointer.
  1074. if (SrcSize >= DstSize) {
  1075. // Generally SrcSize is never greater than DstSize, since this means we are
  1076. // losing bits. However, this can happen in cases where the structure has
  1077. // additional padding, for example due to a user specified alignment.
  1078. //
  1079. // FIXME: Assert that we aren't truncating non-padding bits when have access
  1080. // to that information.
  1081. Src = CGF.Builder.CreateBitCast(Src,
  1082. Ty->getPointerTo(Src.getAddressSpace()));
  1083. return CGF.Builder.CreateLoad(Src);
  1084. }
  1085. // Otherwise do coercion through memory. This is stupid, but simple.
  1086. Address Tmp = CreateTempAllocaForCoercion(CGF, Ty, Src.getAlignment());
  1087. Address Casted = CGF.Builder.CreateElementBitCast(Tmp,CGF.Int8Ty);
  1088. Address SrcCasted = CGF.Builder.CreateElementBitCast(Src,CGF.Int8Ty);
  1089. CGF.Builder.CreateMemCpy(Casted, SrcCasted,
  1090. llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
  1091. false);
  1092. return CGF.Builder.CreateLoad(Tmp);
  1093. }
  1094. // Function to store a first-class aggregate into memory. We prefer to
  1095. // store the elements rather than the aggregate to be more friendly to
  1096. // fast-isel.
  1097. // FIXME: Do we need to recurse here?
  1098. static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
  1099. Address Dest, bool DestIsVolatile) {
  1100. // Prefer scalar stores to first-class aggregate stores.
  1101. if (llvm::StructType *STy =
  1102. dyn_cast<llvm::StructType>(Val->getType())) {
  1103. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
  1104. Address EltPtr = CGF.Builder.CreateStructGEP(Dest, i);
  1105. llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
  1106. CGF.Builder.CreateStore(Elt, EltPtr, DestIsVolatile);
  1107. }
  1108. } else {
  1109. CGF.Builder.CreateStore(Val, Dest, DestIsVolatile);
  1110. }
  1111. }
  1112. /// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
  1113. /// where the source and destination may have different types. The
  1114. /// destination is known to be aligned to \arg DstAlign bytes.
  1115. ///
  1116. /// This safely handles the case when the src type is larger than the
  1117. /// destination type; the upper bits of the src will be lost.
  1118. static void CreateCoercedStore(llvm::Value *Src,
  1119. Address Dst,
  1120. bool DstIsVolatile,
  1121. CodeGenFunction &CGF) {
  1122. llvm::Type *SrcTy = Src->getType();
  1123. llvm::Type *DstTy = Dst.getType()->getElementType();
  1124. if (SrcTy == DstTy) {
  1125. CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
  1126. return;
  1127. }
  1128. uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
  1129. if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
  1130. Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy, SrcSize, CGF);
  1131. DstTy = Dst.getType()->getElementType();
  1132. }
  1133. // If the source and destination are integer or pointer types, just do an
  1134. // extension or truncation to the desired type.
  1135. if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
  1136. (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
  1137. Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
  1138. CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
  1139. return;
  1140. }
  1141. uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
  1142. // If store is legal, just bitcast the src pointer.
  1143. if (SrcSize <= DstSize) {
  1144. Dst = CGF.Builder.CreateElementBitCast(Dst, SrcTy);
  1145. BuildAggStore(CGF, Src, Dst, DstIsVolatile);
  1146. } else {
  1147. // Otherwise do coercion through memory. This is stupid, but
  1148. // simple.
  1149. // Generally SrcSize is never greater than DstSize, since this means we are
  1150. // losing bits. However, this can happen in cases where the structure has
  1151. // additional padding, for example due to a user specified alignment.
  1152. //
  1153. // FIXME: Assert that we aren't truncating non-padding bits when have access
  1154. // to that information.
  1155. Address Tmp = CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment());
  1156. CGF.Builder.CreateStore(Src, Tmp);
  1157. Address Casted = CGF.Builder.CreateElementBitCast(Tmp,CGF.Int8Ty);
  1158. Address DstCasted = CGF.Builder.CreateElementBitCast(Dst,CGF.Int8Ty);
  1159. CGF.Builder.CreateMemCpy(DstCasted, Casted,
  1160. llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
  1161. false);
  1162. }
  1163. }
  1164. static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr,
  1165. const ABIArgInfo &info) {
  1166. if (unsigned offset = info.getDirectOffset()) {
  1167. addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8Ty);
  1168. addr = CGF.Builder.CreateConstInBoundsByteGEP(addr,
  1169. CharUnits::fromQuantity(offset));
  1170. addr = CGF.Builder.CreateElementBitCast(addr, info.getCoerceToType());
  1171. }
  1172. return addr;
  1173. }
  1174. namespace {
  1175. /// Encapsulates information about the way function arguments from
  1176. /// CGFunctionInfo should be passed to actual LLVM IR function.
  1177. class ClangToLLVMArgMapping {
  1178. static const unsigned InvalidIndex = ~0U;
  1179. unsigned InallocaArgNo;
  1180. unsigned SRetArgNo;
  1181. unsigned TotalIRArgs;
  1182. /// Arguments of LLVM IR function corresponding to single Clang argument.
  1183. struct IRArgs {
  1184. unsigned PaddingArgIndex;
  1185. // Argument is expanded to IR arguments at positions
  1186. // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
  1187. unsigned FirstArgIndex;
  1188. unsigned NumberOfArgs;
  1189. IRArgs()
  1190. : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
  1191. NumberOfArgs(0) {}
  1192. };
  1193. SmallVector<IRArgs, 8> ArgInfo;
  1194. public:
  1195. ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
  1196. bool OnlyRequiredArgs = false)
  1197. : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
  1198. ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
  1199. construct(Context, FI, OnlyRequiredArgs);
  1200. }
  1201. bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
  1202. unsigned getInallocaArgNo() const {
  1203. assert(hasInallocaArg());
  1204. return InallocaArgNo;
  1205. }
  1206. bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
  1207. unsigned getSRetArgNo() const {
  1208. assert(hasSRetArg());
  1209. return SRetArgNo;
  1210. }
  1211. unsigned totalIRArgs() const { return TotalIRArgs; }
  1212. bool hasPaddingArg(unsigned ArgNo) const {
  1213. assert(ArgNo < ArgInfo.size());
  1214. return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
  1215. }
  1216. unsigned getPaddingArgNo(unsigned ArgNo) const {
  1217. assert(hasPaddingArg(ArgNo));
  1218. return ArgInfo[ArgNo].PaddingArgIndex;
  1219. }
  1220. /// Returns index of first IR argument corresponding to ArgNo, and their
  1221. /// quantity.
  1222. std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
  1223. assert(ArgNo < ArgInfo.size());
  1224. return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
  1225. ArgInfo[ArgNo].NumberOfArgs);
  1226. }
  1227. private:
  1228. void construct(const ASTContext &Context, const CGFunctionInfo &FI,
  1229. bool OnlyRequiredArgs);
  1230. };
  1231. void ClangToLLVMArgMapping::construct(const ASTContext &Context,
  1232. const CGFunctionInfo &FI,
  1233. bool OnlyRequiredArgs) {
  1234. unsigned IRArgNo = 0;
  1235. bool SwapThisWithSRet = false;
  1236. const ABIArgInfo &RetAI = FI.getReturnInfo();
  1237. if (RetAI.getKind() == ABIArgInfo::Indirect) {
  1238. SwapThisWithSRet = RetAI.isSRetAfterThis();
  1239. SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
  1240. }
  1241. unsigned ArgNo = 0;
  1242. unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
  1243. for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
  1244. ++I, ++ArgNo) {
  1245. assert(I != FI.arg_end());
  1246. QualType ArgType = I->type;
  1247. const ABIArgInfo &AI = I->info;
  1248. // Collect data about IR arguments corresponding to Clang argument ArgNo.
  1249. auto &IRArgs = ArgInfo[ArgNo];
  1250. if (AI.getPaddingType())
  1251. IRArgs.PaddingArgIndex = IRArgNo++;
  1252. switch (AI.getKind()) {
  1253. case ABIArgInfo::Extend:
  1254. case ABIArgInfo::Direct: {
  1255. // FIXME: handle sseregparm someday...
  1256. llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
  1257. if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
  1258. IRArgs.NumberOfArgs = STy->getNumElements();
  1259. } else {
  1260. IRArgs.NumberOfArgs = 1;
  1261. }
  1262. break;
  1263. }
  1264. case ABIArgInfo::Indirect:
  1265. IRArgs.NumberOfArgs = 1;
  1266. break;
  1267. case ABIArgInfo::Ignore:
  1268. case ABIArgInfo::InAlloca:
  1269. // ignore and inalloca doesn't have matching LLVM parameters.
  1270. IRArgs.NumberOfArgs = 0;
  1271. break;
  1272. case ABIArgInfo::CoerceAndExpand:
  1273. IRArgs.NumberOfArgs = AI.getCoerceAndExpandTypeSequence().size();
  1274. break;
  1275. case ABIArgInfo::Expand:
  1276. IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
  1277. break;
  1278. }
  1279. if (IRArgs.NumberOfArgs > 0) {
  1280. IRArgs.FirstArgIndex = IRArgNo;
  1281. IRArgNo += IRArgs.NumberOfArgs;
  1282. }
  1283. // Skip over the sret parameter when it comes second. We already handled it
  1284. // above.
  1285. if (IRArgNo == 1 && SwapThisWithSRet)
  1286. IRArgNo++;
  1287. }
  1288. assert(ArgNo == ArgInfo.size());
  1289. if (FI.usesInAlloca())
  1290. InallocaArgNo = IRArgNo++;
  1291. TotalIRArgs = IRArgNo;
  1292. }
  1293. } // namespace
  1294. /***/
  1295. bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
  1296. const auto &RI = FI.getReturnInfo();
  1297. return RI.isIndirect() || (RI.isInAlloca() && RI.getInAllocaSRet());
  1298. }
  1299. bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
  1300. return ReturnTypeUsesSRet(FI) &&
  1301. getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
  1302. }
  1303. bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
  1304. if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
  1305. switch (BT->getKind()) {
  1306. default:
  1307. return false;
  1308. case BuiltinType::Float:
  1309. return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
  1310. case BuiltinType::Double:
  1311. return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
  1312. case BuiltinType::LongDouble:
  1313. return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
  1314. }
  1315. }
  1316. return false;
  1317. }
  1318. bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
  1319. if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
  1320. if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
  1321. if (BT->getKind() == BuiltinType::LongDouble)
  1322. return getTarget().useObjCFP2RetForComplexLongDouble();
  1323. }
  1324. }
  1325. return false;
  1326. }
  1327. llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
  1328. const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
  1329. return GetFunctionType(FI);
  1330. }
  1331. llvm::FunctionType *
  1332. CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
  1333. bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
  1334. (void)Inserted;
  1335. assert(Inserted && "Recursively being processed?");
  1336. llvm::Type *resultType = nullptr;
  1337. const ABIArgInfo &retAI = FI.getReturnInfo();
  1338. switch (retAI.getKind()) {
  1339. case ABIArgInfo::Expand:
  1340. llvm_unreachable("Invalid ABI kind for return argument");
  1341. case ABIArgInfo::Extend:
  1342. case ABIArgInfo::Direct:
  1343. resultType = retAI.getCoerceToType();
  1344. break;
  1345. case ABIArgInfo::InAlloca:
  1346. if (retAI.getInAllocaSRet()) {
  1347. // sret things on win32 aren't void, they return the sret pointer.
  1348. QualType ret = FI.getReturnType();
  1349. llvm::Type *ty = ConvertType(ret);
  1350. unsigned addressSpace = Context.getTargetAddressSpace(ret);
  1351. resultType = llvm::PointerType::get(ty, addressSpace);
  1352. } else {
  1353. resultType = llvm::Type::getVoidTy(getLLVMContext());
  1354. }
  1355. break;
  1356. case ABIArgInfo::Indirect:
  1357. case ABIArgInfo::Ignore:
  1358. resultType = llvm::Type::getVoidTy(getLLVMContext());
  1359. break;
  1360. case ABIArgInfo::CoerceAndExpand:
  1361. resultType = retAI.getUnpaddedCoerceAndExpandType();
  1362. break;
  1363. }
  1364. ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
  1365. SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
  1366. // Add type for sret argument.
  1367. if (IRFunctionArgs.hasSRetArg()) {
  1368. QualType Ret = FI.getReturnType();
  1369. llvm::Type *Ty = ConvertType(Ret);
  1370. unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
  1371. ArgTypes[IRFunctionArgs.getSRetArgNo()] =
  1372. llvm::PointerType::get(Ty, AddressSpace);
  1373. }
  1374. // Add type for inalloca argument.
  1375. if (IRFunctionArgs.hasInallocaArg()) {
  1376. auto ArgStruct = FI.getArgStruct();
  1377. assert(ArgStruct);
  1378. ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
  1379. }
  1380. // Add in all of the required arguments.
  1381. unsigned ArgNo = 0;
  1382. CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
  1383. ie = it + FI.getNumRequiredArgs();
  1384. for (; it != ie; ++it, ++ArgNo) {
  1385. const ABIArgInfo &ArgInfo = it->info;
  1386. // Insert a padding type to ensure proper alignment.
  1387. if (IRFunctionArgs.hasPaddingArg(ArgNo))
  1388. ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
  1389. ArgInfo.getPaddingType();
  1390. unsigned FirstIRArg, NumIRArgs;
  1391. std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
  1392. switch (ArgInfo.getKind()) {
  1393. case ABIArgInfo::Ignore:
  1394. case ABIArgInfo::InAlloca:
  1395. assert(NumIRArgs == 0);
  1396. break;
  1397. case ABIArgInfo::Indirect: {
  1398. assert(NumIRArgs == 1);
  1399. // indirect arguments are always on the stack, which is alloca addr space.
  1400. llvm::Type *LTy = ConvertTypeForMem(it->type);
  1401. ArgTypes[FirstIRArg] = LTy->getPointerTo(
  1402. CGM.getDataLayout().getAllocaAddrSpace());
  1403. break;
  1404. }
  1405. case ABIArgInfo::Extend:
  1406. case ABIArgInfo::Direct: {
  1407. // Fast-isel and the optimizer generally like scalar values better than
  1408. // FCAs, so we flatten them if this is safe to do for this argument.
  1409. llvm::Type *argType = ArgInfo.getCoerceToType();
  1410. llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
  1411. if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
  1412. assert(NumIRArgs == st->getNumElements());
  1413. for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
  1414. ArgTypes[FirstIRArg + i] = st->getElementType(i);
  1415. } else {
  1416. assert(NumIRArgs == 1);
  1417. ArgTypes[FirstIRArg] = argType;
  1418. }
  1419. break;
  1420. }
  1421. case ABIArgInfo::CoerceAndExpand: {
  1422. auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
  1423. for (auto EltTy : ArgInfo.getCoerceAndExpandTypeSequence()) {
  1424. *ArgTypesIter++ = EltTy;
  1425. }
  1426. assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
  1427. break;
  1428. }
  1429. case ABIArgInfo::Expand:
  1430. auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
  1431. getExpandedTypes(it->type, ArgTypesIter);
  1432. assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
  1433. break;
  1434. }
  1435. }
  1436. bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
  1437. assert(Erased && "Not in set?");
  1438. return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
  1439. }
  1440. llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
  1441. const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
  1442. const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
  1443. if (!isFuncTypeConvertible(FPT))
  1444. return llvm::StructType::get(getLLVMContext());
  1445. return GetFunctionType(GD);
  1446. }
  1447. static void AddAttributesFromFunctionProtoType(ASTContext &Ctx,
  1448. llvm::AttrBuilder &FuncAttrs,
  1449. const FunctionProtoType *FPT) {
  1450. if (!FPT)
  1451. return;
  1452. if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
  1453. FPT->isNothrow())
  1454. FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
  1455. }
  1456. void CodeGenModule::ConstructDefaultFnAttrList(StringRef Name, bool HasOptnone,
  1457. bool AttrOnCallSite,
  1458. llvm::AttrBuilder &FuncAttrs) {
  1459. // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
  1460. if (!HasOptnone) {
  1461. if (CodeGenOpts.OptimizeSize)
  1462. FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
  1463. if (CodeGenOpts.OptimizeSize == 2)
  1464. FuncAttrs.addAttribute(llvm::Attribute::MinSize);
  1465. }
  1466. if (CodeGenOpts.DisableRedZone)
  1467. FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
  1468. if (CodeGenOpts.IndirectTlsSegRefs)
  1469. FuncAttrs.addAttribute("indirect-tls-seg-refs");
  1470. if (CodeGenOpts.NoImplicitFloat)
  1471. FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
  1472. if (AttrOnCallSite) {
  1473. // Attributes that should go on the call site only.
  1474. if (!CodeGenOpts.SimplifyLibCalls ||
  1475. CodeGenOpts.isNoBuiltinFunc(Name.data()))
  1476. FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
  1477. if (!CodeGenOpts.TrapFuncName.empty())
  1478. FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName);
  1479. } else {
  1480. StringRef FpKind;
  1481. switch (CodeGenOpts.getFramePointer()) {
  1482. case CodeGenOptions::FramePointerKind::None:
  1483. FpKind = "none";
  1484. break;
  1485. case CodeGenOptions::FramePointerKind::NonLeaf:
  1486. FpKind = "non-leaf";
  1487. break;
  1488. case CodeGenOptions::FramePointerKind::All:
  1489. FpKind = "all";
  1490. break;
  1491. }
  1492. FuncAttrs.addAttribute("frame-pointer", FpKind);
  1493. FuncAttrs.addAttribute("less-precise-fpmad",
  1494. llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
  1495. if (CodeGenOpts.NullPointerIsValid)
  1496. FuncAttrs.addAttribute("null-pointer-is-valid", "true");
  1497. if (!CodeGenOpts.FPDenormalMode.empty())
  1498. FuncAttrs.addAttribute("denormal-fp-math", CodeGenOpts.FPDenormalMode);
  1499. FuncAttrs.addAttribute("no-trapping-math",
  1500. llvm::toStringRef(CodeGenOpts.NoTrappingMath));
  1501. // Strict (compliant) code is the default, so only add this attribute to
  1502. // indicate that we are trying to workaround a problem case.
  1503. if (!CodeGenOpts.StrictFloatCastOverflow)
  1504. FuncAttrs.addAttribute("strict-float-cast-overflow", "false");
  1505. // TODO: Are these all needed?
  1506. // unsafe/inf/nan/nsz are handled by instruction-level FastMathFlags.
  1507. FuncAttrs.addAttribute("no-infs-fp-math",
  1508. llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
  1509. FuncAttrs.addAttribute("no-nans-fp-math",
  1510. llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
  1511. FuncAttrs.addAttribute("unsafe-fp-math",
  1512. llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
  1513. FuncAttrs.addAttribute("use-soft-float",
  1514. llvm::toStringRef(CodeGenOpts.SoftFloat));
  1515. FuncAttrs.addAttribute("stack-protector-buffer-size",
  1516. llvm::utostr(CodeGenOpts.SSPBufferSize));
  1517. FuncAttrs.addAttribute("no-signed-zeros-fp-math",
  1518. llvm::toStringRef(CodeGenOpts.NoSignedZeros));
  1519. FuncAttrs.addAttribute(
  1520. "correctly-rounded-divide-sqrt-fp-math",
  1521. llvm::toStringRef(CodeGenOpts.CorrectlyRoundedDivSqrt));
  1522. if (getLangOpts().OpenCL)
  1523. FuncAttrs.addAttribute("denorms-are-zero",
  1524. llvm::toStringRef(CodeGenOpts.FlushDenorm));
  1525. // TODO: Reciprocal estimate codegen options should apply to instructions?
  1526. const std::vector<std::string> &Recips = CodeGenOpts.Reciprocals;
  1527. if (!Recips.empty())
  1528. FuncAttrs.addAttribute("reciprocal-estimates",
  1529. llvm::join(Recips, ","));
  1530. if (!CodeGenOpts.PreferVectorWidth.empty() &&
  1531. CodeGenOpts.PreferVectorWidth != "none")
  1532. FuncAttrs.addAttribute("prefer-vector-width",
  1533. CodeGenOpts.PreferVectorWidth);
  1534. if (CodeGenOpts.StackRealignment)
  1535. FuncAttrs.addAttribute("stackrealign");
  1536. if (CodeGenOpts.Backchain)
  1537. FuncAttrs.addAttribute("backchain");
  1538. if (CodeGenOpts.SpeculativeLoadHardening)
  1539. FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
  1540. }
  1541. if (getLangOpts().assumeFunctionsAreConvergent()) {
  1542. // Conservatively, mark all functions and calls in CUDA and OpenCL as
  1543. // convergent (meaning, they may call an intrinsically convergent op, such
  1544. // as __syncthreads() / barrier(), and so can't have certain optimizations
  1545. // applied around them). LLVM will remove this attribute where it safely
  1546. // can.
  1547. FuncAttrs.addAttribute(llvm::Attribute::Convergent);
  1548. }
  1549. if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
  1550. // Exceptions aren't supported in CUDA device code.
  1551. FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
  1552. // Respect -fcuda-flush-denormals-to-zero.
  1553. if (CodeGenOpts.FlushDenorm)
  1554. FuncAttrs.addAttribute("nvptx-f32ftz", "true");
  1555. }
  1556. for (StringRef Attr : CodeGenOpts.DefaultFunctionAttrs) {
  1557. StringRef Var, Value;
  1558. std::tie(Var, Value) = Attr.split('=');
  1559. FuncAttrs.addAttribute(Var, Value);
  1560. }
  1561. }
  1562. void CodeGenModule::AddDefaultFnAttrs(llvm::Function &F) {
  1563. llvm::AttrBuilder FuncAttrs;
  1564. ConstructDefaultFnAttrList(F.getName(), F.hasOptNone(),
  1565. /* AttrOnCallSite = */ false, FuncAttrs);
  1566. F.addAttributes(llvm::AttributeList::FunctionIndex, FuncAttrs);
  1567. }
  1568. void CodeGenModule::ConstructAttributeList(
  1569. StringRef Name, const CGFunctionInfo &FI, CGCalleeInfo CalleeInfo,
  1570. llvm::AttributeList &AttrList, unsigned &CallingConv, bool AttrOnCallSite) {
  1571. llvm::AttrBuilder FuncAttrs;
  1572. llvm::AttrBuilder RetAttrs;
  1573. CallingConv = FI.getEffectiveCallingConvention();
  1574. if (FI.isNoReturn())
  1575. FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
  1576. // If we have information about the function prototype, we can learn
  1577. // attributes from there.
  1578. AddAttributesFromFunctionProtoType(getContext(), FuncAttrs,
  1579. CalleeInfo.getCalleeFunctionProtoType());
  1580. const Decl *TargetDecl = CalleeInfo.getCalleeDecl().getDecl();
  1581. bool HasOptnone = false;
  1582. // FIXME: handle sseregparm someday...
  1583. if (TargetDecl) {
  1584. if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
  1585. FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
  1586. if (TargetDecl->hasAttr<NoThrowAttr>())
  1587. FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
  1588. if (TargetDecl->hasAttr<NoReturnAttr>())
  1589. FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
  1590. if (TargetDecl->hasAttr<ColdAttr>())
  1591. FuncAttrs.addAttribute(llvm::Attribute::Cold);
  1592. if (TargetDecl->hasAttr<NoDuplicateAttr>())
  1593. FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
  1594. if (TargetDecl->hasAttr<ConvergentAttr>())
  1595. FuncAttrs.addAttribute(llvm::Attribute::Convergent);
  1596. if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
  1597. AddAttributesFromFunctionProtoType(
  1598. getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>());
  1599. // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
  1600. // These attributes are not inherited by overloads.
  1601. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
  1602. if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
  1603. FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
  1604. }
  1605. // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
  1606. if (TargetDecl->hasAttr<ConstAttr>()) {
  1607. FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
  1608. FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
  1609. } else if (TargetDecl->hasAttr<PureAttr>()) {
  1610. FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
  1611. FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
  1612. } else if (TargetDecl->hasAttr<NoAliasAttr>()) {
  1613. FuncAttrs.addAttribute(llvm::Attribute::ArgMemOnly);
  1614. FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
  1615. }
  1616. if (TargetDecl->hasAttr<RestrictAttr>())
  1617. RetAttrs.addAttribute(llvm::Attribute::NoAlias);
  1618. if (TargetDecl->hasAttr<ReturnsNonNullAttr>() &&
  1619. !CodeGenOpts.NullPointerIsValid)
  1620. RetAttrs.addAttribute(llvm::Attribute::NonNull);
  1621. if (TargetDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())
  1622. FuncAttrs.addAttribute("no_caller_saved_registers");
  1623. if (TargetDecl->hasAttr<AnyX86NoCfCheckAttr>())
  1624. FuncAttrs.addAttribute(llvm::Attribute::NoCfCheck);
  1625. HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
  1626. if (auto *AllocSize = TargetDecl->getAttr<AllocSizeAttr>()) {
  1627. Optional<unsigned> NumElemsParam;
  1628. if (AllocSize->getNumElemsParam().isValid())
  1629. NumElemsParam = AllocSize->getNumElemsParam().getLLVMIndex();
  1630. FuncAttrs.addAllocSizeAttr(AllocSize->getElemSizeParam().getLLVMIndex(),
  1631. NumElemsParam);
  1632. }
  1633. }
  1634. ConstructDefaultFnAttrList(Name, HasOptnone, AttrOnCallSite, FuncAttrs);
  1635. // This must run after constructing the default function attribute list
  1636. // to ensure that the speculative load hardening attribute is removed
  1637. // in the case where the -mspeculative-load-hardening flag was passed.
  1638. if (TargetDecl) {
  1639. if (TargetDecl->hasAttr<NoSpeculativeLoadHardeningAttr>())
  1640. FuncAttrs.removeAttribute(llvm::Attribute::SpeculativeLoadHardening);
  1641. if (TargetDecl->hasAttr<SpeculativeLoadHardeningAttr>())
  1642. FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
  1643. }
  1644. if (CodeGenOpts.EnableSegmentedStacks &&
  1645. !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
  1646. FuncAttrs.addAttribute("split-stack");
  1647. // Add NonLazyBind attribute to function declarations when -fno-plt
  1648. // is used.
  1649. if (TargetDecl && CodeGenOpts.NoPLT) {
  1650. if (auto *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
  1651. if (!Fn->isDefined() && !AttrOnCallSite) {
  1652. FuncAttrs.addAttribute(llvm::Attribute::NonLazyBind);
  1653. }
  1654. }
  1655. }
  1656. if (TargetDecl && TargetDecl->hasAttr<OpenCLKernelAttr>()) {
  1657. if (getLangOpts().OpenCLVersion <= 120) {
  1658. // OpenCL v1.2 Work groups are always uniform
  1659. FuncAttrs.addAttribute("uniform-work-group-size", "true");
  1660. } else {
  1661. // OpenCL v2.0 Work groups may be whether uniform or not.
  1662. // '-cl-uniform-work-group-size' compile option gets a hint
  1663. // to the compiler that the global work-size be a multiple of
  1664. // the work-group size specified to clEnqueueNDRangeKernel
  1665. // (i.e. work groups are uniform).
  1666. FuncAttrs.addAttribute("uniform-work-group-size",
  1667. llvm::toStringRef(CodeGenOpts.UniformWGSize));
  1668. }
  1669. }
  1670. if (!AttrOnCallSite) {
  1671. bool DisableTailCalls = false;
  1672. if (CodeGenOpts.DisableTailCalls)
  1673. DisableTailCalls = true;
  1674. else if (TargetDecl) {
  1675. if (TargetDecl->hasAttr<DisableTailCallsAttr>() ||
  1676. TargetDecl->hasAttr<AnyX86InterruptAttr>())
  1677. DisableTailCalls = true;
  1678. else if (CodeGenOpts.NoEscapingBlockTailCalls) {
  1679. if (const auto *BD = dyn_cast<BlockDecl>(TargetDecl))
  1680. if (!BD->doesNotEscape())
  1681. DisableTailCalls = true;
  1682. }
  1683. }
  1684. FuncAttrs.addAttribute("disable-tail-calls",
  1685. llvm::toStringRef(DisableTailCalls));
  1686. GetCPUAndFeaturesAttributes(CalleeInfo.getCalleeDecl(), FuncAttrs);
  1687. }
  1688. ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
  1689. QualType RetTy = FI.getReturnType();
  1690. const ABIArgInfo &RetAI = FI.getReturnInfo();
  1691. switch (RetAI.getKind()) {
  1692. case ABIArgInfo::Extend:
  1693. if (RetAI.isSignExt())
  1694. RetAttrs.addAttribute(llvm::Attribute::SExt);
  1695. else
  1696. RetAttrs.addAttribute(llvm::Attribute::ZExt);
  1697. LLVM_FALLTHROUGH;
  1698. case ABIArgInfo::Direct:
  1699. if (RetAI.getInReg())
  1700. RetAttrs.addAttribute(llvm::Attribute::InReg);
  1701. break;
  1702. case ABIArgInfo::Ignore:
  1703. break;
  1704. case ABIArgInfo::InAlloca:
  1705. case ABIArgInfo::Indirect: {
  1706. // inalloca and sret disable readnone and readonly
  1707. FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
  1708. .removeAttribute(llvm::Attribute::ReadNone);
  1709. break;
  1710. }
  1711. case ABIArgInfo::CoerceAndExpand:
  1712. break;
  1713. case ABIArgInfo::Expand:
  1714. llvm_unreachable("Invalid ABI kind for return argument");
  1715. }
  1716. if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
  1717. QualType PTy = RefTy->getPointeeType();
  1718. if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
  1719. RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
  1720. .getQuantity());
  1721. else if (getContext().getTargetAddressSpace(PTy) == 0 &&
  1722. !CodeGenOpts.NullPointerIsValid)
  1723. RetAttrs.addAttribute(llvm::Attribute::NonNull);
  1724. }
  1725. bool hasUsedSRet = false;
  1726. SmallVector<llvm::AttributeSet, 4> ArgAttrs(IRFunctionArgs.totalIRArgs());
  1727. // Attach attributes to sret.
  1728. if (IRFunctionArgs.hasSRetArg()) {
  1729. llvm::AttrBuilder SRETAttrs;
  1730. SRETAttrs.addAttribute(llvm::Attribute::StructRet);
  1731. hasUsedSRet = true;
  1732. if (RetAI.getInReg())
  1733. SRETAttrs.addAttribute(llvm::Attribute::InReg);
  1734. ArgAttrs[IRFunctionArgs.getSRetArgNo()] =
  1735. llvm::AttributeSet::get(getLLVMContext(), SRETAttrs);
  1736. }
  1737. // Attach attributes to inalloca argument.
  1738. if (IRFunctionArgs.hasInallocaArg()) {
  1739. llvm::AttrBuilder Attrs;
  1740. Attrs.addAttribute(llvm::Attribute::InAlloca);
  1741. ArgAttrs[IRFunctionArgs.getInallocaArgNo()] =
  1742. llvm::AttributeSet::get(getLLVMContext(), Attrs);
  1743. }
  1744. unsigned ArgNo = 0;
  1745. for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
  1746. E = FI.arg_end();
  1747. I != E; ++I, ++ArgNo) {
  1748. QualType ParamType = I->type;
  1749. const ABIArgInfo &AI = I->info;
  1750. llvm::AttrBuilder Attrs;
  1751. // Add attribute for padding argument, if necessary.
  1752. if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
  1753. if (AI.getPaddingInReg()) {
  1754. ArgAttrs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
  1755. llvm::AttributeSet::get(
  1756. getLLVMContext(),
  1757. llvm::AttrBuilder().addAttribute(llvm::Attribute::InReg));
  1758. }
  1759. }
  1760. // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
  1761. // have the corresponding parameter variable. It doesn't make
  1762. // sense to do it here because parameters are so messed up.
  1763. switch (AI.getKind()) {
  1764. case ABIArgInfo::Extend:
  1765. if (AI.isSignExt())
  1766. Attrs.addAttribute(llvm::Attribute::SExt);
  1767. else
  1768. Attrs.addAttribute(llvm::Attribute::ZExt);
  1769. LLVM_FALLTHROUGH;
  1770. case ABIArgInfo::Direct:
  1771. if (ArgNo == 0 && FI.isChainCall())
  1772. Attrs.addAttribute(llvm::Attribute::Nest);
  1773. else if (AI.getInReg())
  1774. Attrs.addAttribute(llvm::Attribute::InReg);
  1775. break;
  1776. case ABIArgInfo::Indirect: {
  1777. if (AI.getInReg())
  1778. Attrs.addAttribute(llvm::Attribute::InReg);
  1779. if (AI.getIndirectByVal())
  1780. Attrs.addByValAttr(getTypes().ConvertTypeForMem(ParamType));
  1781. CharUnits Align = AI.getIndirectAlign();
  1782. // In a byval argument, it is important that the required
  1783. // alignment of the type is honored, as LLVM might be creating a
  1784. // *new* stack object, and needs to know what alignment to give
  1785. // it. (Sometimes it can deduce a sensible alignment on its own,
  1786. // but not if clang decides it must emit a packed struct, or the
  1787. // user specifies increased alignment requirements.)
  1788. //
  1789. // This is different from indirect *not* byval, where the object
  1790. // exists already, and the align attribute is purely
  1791. // informative.
  1792. assert(!Align.isZero());
  1793. // For now, only add this when we have a byval argument.
  1794. // TODO: be less lazy about updating test cases.
  1795. if (AI.getIndirectByVal())
  1796. Attrs.addAlignmentAttr(Align.getQuantity());
  1797. // byval disables readnone and readonly.
  1798. FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
  1799. .removeAttribute(llvm::Attribute::ReadNone);
  1800. break;
  1801. }
  1802. case ABIArgInfo::Ignore:
  1803. case ABIArgInfo::Expand:
  1804. case ABIArgInfo::CoerceAndExpand:
  1805. break;
  1806. case ABIArgInfo::InAlloca:
  1807. // inalloca disables readnone and readonly.
  1808. FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
  1809. .removeAttribute(llvm::Attribute::ReadNone);
  1810. continue;
  1811. }
  1812. if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
  1813. QualType PTy = RefTy->getPointeeType();
  1814. if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
  1815. Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
  1816. .getQuantity());
  1817. else if (getContext().getTargetAddressSpace(PTy) == 0 &&
  1818. !CodeGenOpts.NullPointerIsValid)
  1819. Attrs.addAttribute(llvm::Attribute::NonNull);
  1820. }
  1821. switch (FI.getExtParameterInfo(ArgNo).getABI()) {
  1822. case ParameterABI::Ordinary:
  1823. break;
  1824. case ParameterABI::SwiftIndirectResult: {
  1825. // Add 'sret' if we haven't already used it for something, but
  1826. // only if the result is void.
  1827. if (!hasUsedSRet && RetTy->isVoidType()) {
  1828. Attrs.addAttribute(llvm::Attribute::StructRet);
  1829. hasUsedSRet = true;
  1830. }
  1831. // Add 'noalias' in either case.
  1832. Attrs.addAttribute(llvm::Attribute::NoAlias);
  1833. // Add 'dereferenceable' and 'alignment'.
  1834. auto PTy = ParamType->getPointeeType();
  1835. if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
  1836. auto info = getContext().getTypeInfoInChars(PTy);
  1837. Attrs.addDereferenceableAttr(info.first.getQuantity());
  1838. Attrs.addAttribute(llvm::Attribute::getWithAlignment(getLLVMContext(),
  1839. info.second.getQuantity()));
  1840. }
  1841. break;
  1842. }
  1843. case ParameterABI::SwiftErrorResult:
  1844. Attrs.addAttribute(llvm::Attribute::SwiftError);
  1845. break;
  1846. case ParameterABI::SwiftContext:
  1847. Attrs.addAttribute(llvm::Attribute::SwiftSelf);
  1848. break;
  1849. }
  1850. if (FI.getExtParameterInfo(ArgNo).isNoEscape())
  1851. Attrs.addAttribute(llvm::Attribute::NoCapture);
  1852. if (Attrs.hasAttributes()) {
  1853. unsigned FirstIRArg, NumIRArgs;
  1854. std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
  1855. for (unsigned i = 0; i < NumIRArgs; i++)
  1856. ArgAttrs[FirstIRArg + i] =
  1857. llvm::AttributeSet::get(getLLVMContext(), Attrs);
  1858. }
  1859. }
  1860. assert(ArgNo == FI.arg_size());
  1861. AttrList = llvm::AttributeList::get(
  1862. getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), FuncAttrs),
  1863. llvm::AttributeSet::get(getLLVMContext(), RetAttrs), ArgAttrs);
  1864. }
  1865. /// An argument came in as a promoted argument; demote it back to its
  1866. /// declared type.
  1867. static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
  1868. const VarDecl *var,
  1869. llvm::Value *value) {
  1870. llvm::Type *varType = CGF.ConvertType(var->getType());
  1871. // This can happen with promotions that actually don't change the
  1872. // underlying type, like the enum promotions.
  1873. if (value->getType() == varType) return value;
  1874. assert((varType->isIntegerTy() || varType->isFloatingPointTy())
  1875. && "unexpected promotion type");
  1876. if (isa<llvm::IntegerType>(varType))
  1877. return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
  1878. return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
  1879. }
  1880. /// Returns the attribute (either parameter attribute, or function
  1881. /// attribute), which declares argument ArgNo to be non-null.
  1882. static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
  1883. QualType ArgType, unsigned ArgNo) {
  1884. // FIXME: __attribute__((nonnull)) can also be applied to:
  1885. // - references to pointers, where the pointee is known to be
  1886. // nonnull (apparently a Clang extension)
  1887. // - transparent unions containing pointers
  1888. // In the former case, LLVM IR cannot represent the constraint. In
  1889. // the latter case, we have no guarantee that the transparent union
  1890. // is in fact passed as a pointer.
  1891. if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
  1892. return nullptr;
  1893. // First, check attribute on parameter itself.
  1894. if (PVD) {
  1895. if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
  1896. return ParmNNAttr;
  1897. }
  1898. // Check function attributes.
  1899. if (!FD)
  1900. return nullptr;
  1901. for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
  1902. if (NNAttr->isNonNull(ArgNo))
  1903. return NNAttr;
  1904. }
  1905. return nullptr;
  1906. }
  1907. namespace {
  1908. struct CopyBackSwiftError final : EHScopeStack::Cleanup {
  1909. Address Temp;
  1910. Address Arg;
  1911. CopyBackSwiftError(Address temp, Address arg) : Temp(temp), Arg(arg) {}
  1912. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1913. llvm::Value *errorValue = CGF.Builder.CreateLoad(Temp);
  1914. CGF.Builder.CreateStore(errorValue, Arg);
  1915. }
  1916. };
  1917. }
  1918. void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
  1919. llvm::Function *Fn,
  1920. const FunctionArgList &Args) {
  1921. if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
  1922. // Naked functions don't have prologues.
  1923. return;
  1924. // If this is an implicit-return-zero function, go ahead and
  1925. // initialize the return value. TODO: it might be nice to have
  1926. // a more general mechanism for this that didn't require synthesized
  1927. // return statements.
  1928. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
  1929. if (FD->hasImplicitReturnZero()) {
  1930. QualType RetTy = FD->getReturnType().getUnqualifiedType();
  1931. llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
  1932. llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
  1933. Builder.CreateStore(Zero, ReturnValue);
  1934. }
  1935. }
  1936. // FIXME: We no longer need the types from FunctionArgList; lift up and
  1937. // simplify.
  1938. ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
  1939. // Flattened function arguments.
  1940. SmallVector<llvm::Value *, 16> FnArgs;
  1941. FnArgs.reserve(IRFunctionArgs.totalIRArgs());
  1942. for (auto &Arg : Fn->args()) {
  1943. FnArgs.push_back(&Arg);
  1944. }
  1945. assert(FnArgs.size() == IRFunctionArgs.totalIRArgs());
  1946. // If we're using inalloca, all the memory arguments are GEPs off of the last
  1947. // parameter, which is a pointer to the complete memory area.
  1948. Address ArgStruct = Address::invalid();
  1949. if (IRFunctionArgs.hasInallocaArg()) {
  1950. ArgStruct = Address(FnArgs[IRFunctionArgs.getInallocaArgNo()],
  1951. FI.getArgStructAlignment());
  1952. assert(ArgStruct.getType() == FI.getArgStruct()->getPointerTo());
  1953. }
  1954. // Name the struct return parameter.
  1955. if (IRFunctionArgs.hasSRetArg()) {
  1956. auto AI = cast<llvm::Argument>(FnArgs[IRFunctionArgs.getSRetArgNo()]);
  1957. AI->setName("agg.result");
  1958. AI->addAttr(llvm::Attribute::NoAlias);
  1959. }
  1960. // Track if we received the parameter as a pointer (indirect, byval, or
  1961. // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
  1962. // into a local alloca for us.
  1963. SmallVector<ParamValue, 16> ArgVals;
  1964. ArgVals.reserve(Args.size());
  1965. // Create a pointer value for every parameter declaration. This usually
  1966. // entails copying one or more LLVM IR arguments into an alloca. Don't push
  1967. // any cleanups or do anything that might unwind. We do that separately, so
  1968. // we can push the cleanups in the correct order for the ABI.
  1969. assert(FI.arg_size() == Args.size() &&
  1970. "Mismatch between function signature & arguments.");
  1971. unsigned ArgNo = 0;
  1972. CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
  1973. for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
  1974. i != e; ++i, ++info_it, ++ArgNo) {
  1975. const VarDecl *Arg = *i;
  1976. const ABIArgInfo &ArgI = info_it->info;
  1977. bool isPromoted =
  1978. isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
  1979. // We are converting from ABIArgInfo type to VarDecl type directly, unless
  1980. // the parameter is promoted. In this case we convert to
  1981. // CGFunctionInfo::ArgInfo type with subsequent argument demotion.
  1982. QualType Ty = isPromoted ? info_it->type : Arg->getType();
  1983. assert(hasScalarEvaluationKind(Ty) ==
  1984. hasScalarEvaluationKind(Arg->getType()));
  1985. unsigned FirstIRArg, NumIRArgs;
  1986. std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
  1987. switch (ArgI.getKind()) {
  1988. case ABIArgInfo::InAlloca: {
  1989. assert(NumIRArgs == 0);
  1990. auto FieldIndex = ArgI.getInAllocaFieldIndex();
  1991. Address V =
  1992. Builder.CreateStructGEP(ArgStruct, FieldIndex, Arg->getName());
  1993. ArgVals.push_back(ParamValue::forIndirect(V));
  1994. break;
  1995. }
  1996. case ABIArgInfo::Indirect: {
  1997. assert(NumIRArgs == 1);
  1998. Address ParamAddr = Address(FnArgs[FirstIRArg], ArgI.getIndirectAlign());
  1999. if (!hasScalarEvaluationKind(Ty)) {
  2000. // Aggregates and complex variables are accessed by reference. All we
  2001. // need to do is realign the value, if requested.
  2002. Address V = ParamAddr;
  2003. if (ArgI.getIndirectRealign()) {
  2004. Address AlignedTemp = CreateMemTemp(Ty, "coerce");
  2005. // Copy from the incoming argument pointer to the temporary with the
  2006. // appropriate alignment.
  2007. //
  2008. // FIXME: We should have a common utility for generating an aggregate
  2009. // copy.
  2010. CharUnits Size = getContext().getTypeSizeInChars(Ty);
  2011. auto SizeVal = llvm::ConstantInt::get(IntPtrTy, Size.getQuantity());
  2012. Address Dst = Builder.CreateBitCast(AlignedTemp, Int8PtrTy);
  2013. Address Src = Builder.CreateBitCast(ParamAddr, Int8PtrTy);
  2014. Builder.CreateMemCpy(Dst, Src, SizeVal, false);
  2015. V = AlignedTemp;
  2016. }
  2017. ArgVals.push_back(ParamValue::forIndirect(V));
  2018. } else {
  2019. // Load scalar value from indirect argument.
  2020. llvm::Value *V =
  2021. EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getBeginLoc());
  2022. if (isPromoted)
  2023. V = emitArgumentDemotion(*this, Arg, V);
  2024. ArgVals.push_back(ParamValue::forDirect(V));
  2025. }
  2026. break;
  2027. }
  2028. case ABIArgInfo::Extend:
  2029. case ABIArgInfo::Direct: {
  2030. // If we have the trivial case, handle it with no muss and fuss.
  2031. if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
  2032. ArgI.getCoerceToType() == ConvertType(Ty) &&
  2033. ArgI.getDirectOffset() == 0) {
  2034. assert(NumIRArgs == 1);
  2035. llvm::Value *V = FnArgs[FirstIRArg];
  2036. auto AI = cast<llvm::Argument>(V);
  2037. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
  2038. if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
  2039. PVD->getFunctionScopeIndex()) &&
  2040. !CGM.getCodeGenOpts().NullPointerIsValid)
  2041. AI->addAttr(llvm::Attribute::NonNull);
  2042. QualType OTy = PVD->getOriginalType();
  2043. if (const auto *ArrTy =
  2044. getContext().getAsConstantArrayType(OTy)) {
  2045. // A C99 array parameter declaration with the static keyword also
  2046. // indicates dereferenceability, and if the size is constant we can
  2047. // use the dereferenceable attribute (which requires the size in
  2048. // bytes).
  2049. if (ArrTy->getSizeModifier() == ArrayType::Static) {
  2050. QualType ETy = ArrTy->getElementType();
  2051. uint64_t ArrSize = ArrTy->getSize().getZExtValue();
  2052. if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
  2053. ArrSize) {
  2054. llvm::AttrBuilder Attrs;
  2055. Attrs.addDereferenceableAttr(
  2056. getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
  2057. AI->addAttrs(Attrs);
  2058. } else if (getContext().getTargetAddressSpace(ETy) == 0 &&
  2059. !CGM.getCodeGenOpts().NullPointerIsValid) {
  2060. AI->addAttr(llvm::Attribute::NonNull);
  2061. }
  2062. }
  2063. } else if (const auto *ArrTy =
  2064. getContext().getAsVariableArrayType(OTy)) {
  2065. // For C99 VLAs with the static keyword, we don't know the size so
  2066. // we can't use the dereferenceable attribute, but in addrspace(0)
  2067. // we know that it must be nonnull.
  2068. if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
  2069. !getContext().getTargetAddressSpace(ArrTy->getElementType()) &&
  2070. !CGM.getCodeGenOpts().NullPointerIsValid)
  2071. AI->addAttr(llvm::Attribute::NonNull);
  2072. }
  2073. const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
  2074. if (!AVAttr)
  2075. if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
  2076. AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
  2077. if (AVAttr && !SanOpts.has(SanitizerKind::Alignment)) {
  2078. // If alignment-assumption sanitizer is enabled, we do *not* add
  2079. // alignment attribute here, but emit normal alignment assumption,
  2080. // so the UBSAN check could function.
  2081. llvm::Value *AlignmentValue =
  2082. EmitScalarExpr(AVAttr->getAlignment());
  2083. llvm::ConstantInt *AlignmentCI =
  2084. cast<llvm::ConstantInt>(AlignmentValue);
  2085. unsigned Alignment = std::min((unsigned)AlignmentCI->getZExtValue(),
  2086. +llvm::Value::MaximumAlignment);
  2087. AI->addAttrs(llvm::AttrBuilder().addAlignmentAttr(Alignment));
  2088. }
  2089. }
  2090. if (Arg->getType().isRestrictQualified())
  2091. AI->addAttr(llvm::Attribute::NoAlias);
  2092. // LLVM expects swifterror parameters to be used in very restricted
  2093. // ways. Copy the value into a less-restricted temporary.
  2094. if (FI.getExtParameterInfo(ArgNo).getABI()
  2095. == ParameterABI::SwiftErrorResult) {
  2096. QualType pointeeTy = Ty->getPointeeType();
  2097. assert(pointeeTy->isPointerType());
  2098. Address temp =
  2099. CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
  2100. Address arg = Address(V, getContext().getTypeAlignInChars(pointeeTy));
  2101. llvm::Value *incomingErrorValue = Builder.CreateLoad(arg);
  2102. Builder.CreateStore(incomingErrorValue, temp);
  2103. V = temp.getPointer();
  2104. // Push a cleanup to copy the value back at the end of the function.
  2105. // The convention does not guarantee that the value will be written
  2106. // back if the function exits with an unwind exception.
  2107. EHStack.pushCleanup<CopyBackSwiftError>(NormalCleanup, temp, arg);
  2108. }
  2109. // Ensure the argument is the correct type.
  2110. if (V->getType() != ArgI.getCoerceToType())
  2111. V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
  2112. if (isPromoted)
  2113. V = emitArgumentDemotion(*this, Arg, V);
  2114. // Because of merging of function types from multiple decls it is
  2115. // possible for the type of an argument to not match the corresponding
  2116. // type in the function type. Since we are codegening the callee
  2117. // in here, add a cast to the argument type.
  2118. llvm::Type *LTy = ConvertType(Arg->getType());
  2119. if (V->getType() != LTy)
  2120. V = Builder.CreateBitCast(V, LTy);
  2121. ArgVals.push_back(ParamValue::forDirect(V));
  2122. break;
  2123. }
  2124. Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
  2125. Arg->getName());
  2126. // Pointer to store into.
  2127. Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
  2128. // Fast-isel and the optimizer generally like scalar values better than
  2129. // FCAs, so we flatten them if this is safe to do for this argument.
  2130. llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
  2131. if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
  2132. STy->getNumElements() > 1) {
  2133. uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
  2134. llvm::Type *DstTy = Ptr.getElementType();
  2135. uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
  2136. Address AddrToStoreInto = Address::invalid();
  2137. if (SrcSize <= DstSize) {
  2138. AddrToStoreInto = Builder.CreateElementBitCast(Ptr, STy);
  2139. } else {
  2140. AddrToStoreInto =
  2141. CreateTempAlloca(STy, Alloca.getAlignment(), "coerce");
  2142. }
  2143. assert(STy->getNumElements() == NumIRArgs);
  2144. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
  2145. auto AI = FnArgs[FirstIRArg + i];
  2146. AI->setName(Arg->getName() + ".coerce" + Twine(i));
  2147. Address EltPtr = Builder.CreateStructGEP(AddrToStoreInto, i);
  2148. Builder.CreateStore(AI, EltPtr);
  2149. }
  2150. if (SrcSize > DstSize) {
  2151. Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
  2152. }
  2153. } else {
  2154. // Simple case, just do a coerced store of the argument into the alloca.
  2155. assert(NumIRArgs == 1);
  2156. auto AI = FnArgs[FirstIRArg];
  2157. AI->setName(Arg->getName() + ".coerce");
  2158. CreateCoercedStore(AI, Ptr, /*DstIsVolatile=*/false, *this);
  2159. }
  2160. // Match to what EmitParmDecl is expecting for this type.
  2161. if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
  2162. llvm::Value *V =
  2163. EmitLoadOfScalar(Alloca, false, Ty, Arg->getBeginLoc());
  2164. if (isPromoted)
  2165. V = emitArgumentDemotion(*this, Arg, V);
  2166. ArgVals.push_back(ParamValue::forDirect(V));
  2167. } else {
  2168. ArgVals.push_back(ParamValue::forIndirect(Alloca));
  2169. }
  2170. break;
  2171. }
  2172. case ABIArgInfo::CoerceAndExpand: {
  2173. // Reconstruct into a temporary.
  2174. Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
  2175. ArgVals.push_back(ParamValue::forIndirect(alloca));
  2176. auto coercionType = ArgI.getCoerceAndExpandType();
  2177. alloca = Builder.CreateElementBitCast(alloca, coercionType);
  2178. unsigned argIndex = FirstIRArg;
  2179. for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
  2180. llvm::Type *eltType = coercionType->getElementType(i);
  2181. if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType))
  2182. continue;
  2183. auto eltAddr = Builder.CreateStructGEP(alloca, i);
  2184. auto elt = FnArgs[argIndex++];
  2185. Builder.CreateStore(elt, eltAddr);
  2186. }
  2187. assert(argIndex == FirstIRArg + NumIRArgs);
  2188. break;
  2189. }
  2190. case ABIArgInfo::Expand: {
  2191. // If this structure was expanded into multiple arguments then
  2192. // we need to create a temporary and reconstruct it from the
  2193. // arguments.
  2194. Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
  2195. LValue LV = MakeAddrLValue(Alloca, Ty);
  2196. ArgVals.push_back(ParamValue::forIndirect(Alloca));
  2197. auto FnArgIter = FnArgs.begin() + FirstIRArg;
  2198. ExpandTypeFromArgs(Ty, LV, FnArgIter);
  2199. assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs);
  2200. for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
  2201. auto AI = FnArgs[FirstIRArg + i];
  2202. AI->setName(Arg->getName() + "." + Twine(i));
  2203. }
  2204. break;
  2205. }
  2206. case ABIArgInfo::Ignore:
  2207. assert(NumIRArgs == 0);
  2208. // Initialize the local variable appropriately.
  2209. if (!hasScalarEvaluationKind(Ty)) {
  2210. ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty)));
  2211. } else {
  2212. llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
  2213. ArgVals.push_back(ParamValue::forDirect(U));
  2214. }
  2215. break;
  2216. }
  2217. }
  2218. if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
  2219. for (int I = Args.size() - 1; I >= 0; --I)
  2220. EmitParmDecl(*Args[I], ArgVals[I], I + 1);
  2221. } else {
  2222. for (unsigned I = 0, E = Args.size(); I != E; ++I)
  2223. EmitParmDecl(*Args[I], ArgVals[I], I + 1);
  2224. }
  2225. }
  2226. static void eraseUnusedBitCasts(llvm::Instruction *insn) {
  2227. while (insn->use_empty()) {
  2228. llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
  2229. if (!bitcast) return;
  2230. // This is "safe" because we would have used a ConstantExpr otherwise.
  2231. insn = cast<llvm::Instruction>(bitcast->getOperand(0));
  2232. bitcast->eraseFromParent();
  2233. }
  2234. }
  2235. /// Try to emit a fused autorelease of a return result.
  2236. static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
  2237. llvm::Value *result) {
  2238. // We must be immediately followed the cast.
  2239. llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
  2240. if (BB->empty()) return nullptr;
  2241. if (&BB->back() != result) return nullptr;
  2242. llvm::Type *resultType = result->getType();
  2243. // result is in a BasicBlock and is therefore an Instruction.
  2244. llvm::Instruction *generator = cast<llvm::Instruction>(result);
  2245. SmallVector<llvm::Instruction *, 4> InstsToKill;
  2246. // Look for:
  2247. // %generator = bitcast %type1* %generator2 to %type2*
  2248. while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
  2249. // We would have emitted this as a constant if the operand weren't
  2250. // an Instruction.
  2251. generator = cast<llvm::Instruction>(bitcast->getOperand(0));
  2252. // Require the generator to be immediately followed by the cast.
  2253. if (generator->getNextNode() != bitcast)
  2254. return nullptr;
  2255. InstsToKill.push_back(bitcast);
  2256. }
  2257. // Look for:
  2258. // %generator = call i8* @objc_retain(i8* %originalResult)
  2259. // or
  2260. // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
  2261. llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
  2262. if (!call) return nullptr;
  2263. bool doRetainAutorelease;
  2264. if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints().objc_retain) {
  2265. doRetainAutorelease = true;
  2266. } else if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints()
  2267. .objc_retainAutoreleasedReturnValue) {
  2268. doRetainAutorelease = false;
  2269. // If we emitted an assembly marker for this call (and the
  2270. // ARCEntrypoints field should have been set if so), go looking
  2271. // for that call. If we can't find it, we can't do this
  2272. // optimization. But it should always be the immediately previous
  2273. // instruction, unless we needed bitcasts around the call.
  2274. if (CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker) {
  2275. llvm::Instruction *prev = call->getPrevNode();
  2276. assert(prev);
  2277. if (isa<llvm::BitCastInst>(prev)) {
  2278. prev = prev->getPrevNode();
  2279. assert(prev);
  2280. }
  2281. assert(isa<llvm::CallInst>(prev));
  2282. assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
  2283. CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker);
  2284. InstsToKill.push_back(prev);
  2285. }
  2286. } else {
  2287. return nullptr;
  2288. }
  2289. result = call->getArgOperand(0);
  2290. InstsToKill.push_back(call);
  2291. // Keep killing bitcasts, for sanity. Note that we no longer care
  2292. // about precise ordering as long as there's exactly one use.
  2293. while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
  2294. if (!bitcast->hasOneUse()) break;
  2295. InstsToKill.push_back(bitcast);
  2296. result = bitcast->getOperand(0);
  2297. }
  2298. // Delete all the unnecessary instructions, from latest to earliest.
  2299. for (auto *I : InstsToKill)
  2300. I->eraseFromParent();
  2301. // Do the fused retain/autorelease if we were asked to.
  2302. if (doRetainAutorelease)
  2303. result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
  2304. // Cast back to the result type.
  2305. return CGF.Builder.CreateBitCast(result, resultType);
  2306. }
  2307. /// If this is a +1 of the value of an immutable 'self', remove it.
  2308. static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
  2309. llvm::Value *result) {
  2310. // This is only applicable to a method with an immutable 'self'.
  2311. const ObjCMethodDecl *method =
  2312. dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
  2313. if (!method) return nullptr;
  2314. const VarDecl *self = method->getSelfDecl();
  2315. if (!self->getType().isConstQualified()) return nullptr;
  2316. // Look for a retain call.
  2317. llvm::CallInst *retainCall =
  2318. dyn_cast<llvm::CallInst>(result->stripPointerCasts());
  2319. if (!retainCall ||
  2320. retainCall->getCalledValue() != CGF.CGM.getObjCEntrypoints().objc_retain)
  2321. return nullptr;
  2322. // Look for an ordinary load of 'self'.
  2323. llvm::Value *retainedValue = retainCall->getArgOperand(0);
  2324. llvm::LoadInst *load =
  2325. dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
  2326. if (!load || load->isAtomic() || load->isVolatile() ||
  2327. load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer())
  2328. return nullptr;
  2329. // Okay! Burn it all down. This relies for correctness on the
  2330. // assumption that the retain is emitted as part of the return and
  2331. // that thereafter everything is used "linearly".
  2332. llvm::Type *resultType = result->getType();
  2333. eraseUnusedBitCasts(cast<llvm::Instruction>(result));
  2334. assert(retainCall->use_empty());
  2335. retainCall->eraseFromParent();
  2336. eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
  2337. return CGF.Builder.CreateBitCast(load, resultType);
  2338. }
  2339. /// Emit an ARC autorelease of the result of a function.
  2340. ///
  2341. /// \return the value to actually return from the function
  2342. static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
  2343. llvm::Value *result) {
  2344. // If we're returning 'self', kill the initial retain. This is a
  2345. // heuristic attempt to "encourage correctness" in the really unfortunate
  2346. // case where we have a return of self during a dealloc and we desperately
  2347. // need to avoid the possible autorelease.
  2348. if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
  2349. return self;
  2350. // At -O0, try to emit a fused retain/autorelease.
  2351. if (CGF.shouldUseFusedARCCalls())
  2352. if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
  2353. return fused;
  2354. return CGF.EmitARCAutoreleaseReturnValue(result);
  2355. }
  2356. /// Heuristically search for a dominating store to the return-value slot.
  2357. static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
  2358. // Check if a User is a store which pointerOperand is the ReturnValue.
  2359. // We are looking for stores to the ReturnValue, not for stores of the
  2360. // ReturnValue to some other location.
  2361. auto GetStoreIfValid = [&CGF](llvm::User *U) -> llvm::StoreInst * {
  2362. auto *SI = dyn_cast<llvm::StoreInst>(U);
  2363. if (!SI || SI->getPointerOperand() != CGF.ReturnValue.getPointer())
  2364. return nullptr;
  2365. // These aren't actually possible for non-coerced returns, and we
  2366. // only care about non-coerced returns on this code path.
  2367. assert(!SI->isAtomic() && !SI->isVolatile());
  2368. return SI;
  2369. };
  2370. // If there are multiple uses of the return-value slot, just check
  2371. // for something immediately preceding the IP. Sometimes this can
  2372. // happen with how we generate implicit-returns; it can also happen
  2373. // with noreturn cleanups.
  2374. if (!CGF.ReturnValue.getPointer()->hasOneUse()) {
  2375. llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
  2376. if (IP->empty()) return nullptr;
  2377. llvm::Instruction *I = &IP->back();
  2378. // Skip lifetime markers
  2379. for (llvm::BasicBlock::reverse_iterator II = IP->rbegin(),
  2380. IE = IP->rend();
  2381. II != IE; ++II) {
  2382. if (llvm::IntrinsicInst *Intrinsic =
  2383. dyn_cast<llvm::IntrinsicInst>(&*II)) {
  2384. if (Intrinsic->getIntrinsicID() == llvm::Intrinsic::lifetime_end) {
  2385. const llvm::Value *CastAddr = Intrinsic->getArgOperand(1);
  2386. ++II;
  2387. if (II == IE)
  2388. break;
  2389. if (isa<llvm::BitCastInst>(&*II) && (CastAddr == &*II))
  2390. continue;
  2391. }
  2392. }
  2393. I = &*II;
  2394. break;
  2395. }
  2396. return GetStoreIfValid(I);
  2397. }
  2398. llvm::StoreInst *store =
  2399. GetStoreIfValid(CGF.ReturnValue.getPointer()->user_back());
  2400. if (!store) return nullptr;
  2401. // Now do a first-and-dirty dominance check: just walk up the
  2402. // single-predecessors chain from the current insertion point.
  2403. llvm::BasicBlock *StoreBB = store->getParent();
  2404. llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
  2405. while (IP != StoreBB) {
  2406. if (!(IP = IP->getSinglePredecessor()))
  2407. return nullptr;
  2408. }
  2409. // Okay, the store's basic block dominates the insertion point; we
  2410. // can do our thing.
  2411. return store;
  2412. }
  2413. void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
  2414. bool EmitRetDbgLoc,
  2415. SourceLocation EndLoc) {
  2416. if (FI.isNoReturn()) {
  2417. // Noreturn functions don't return.
  2418. EmitUnreachable(EndLoc);
  2419. return;
  2420. }
  2421. if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
  2422. // Naked functions don't have epilogues.
  2423. Builder.CreateUnreachable();
  2424. return;
  2425. }
  2426. // Functions with no result always return void.
  2427. if (!ReturnValue.isValid()) {
  2428. Builder.CreateRetVoid();
  2429. return;
  2430. }
  2431. llvm::DebugLoc RetDbgLoc;
  2432. llvm::Value *RV = nullptr;
  2433. QualType RetTy = FI.getReturnType();
  2434. const ABIArgInfo &RetAI = FI.getReturnInfo();
  2435. switch (RetAI.getKind()) {
  2436. case ABIArgInfo::InAlloca:
  2437. // Aggregrates get evaluated directly into the destination. Sometimes we
  2438. // need to return the sret value in a register, though.
  2439. assert(hasAggregateEvaluationKind(RetTy));
  2440. if (RetAI.getInAllocaSRet()) {
  2441. llvm::Function::arg_iterator EI = CurFn->arg_end();
  2442. --EI;
  2443. llvm::Value *ArgStruct = &*EI;
  2444. llvm::Value *SRet = Builder.CreateStructGEP(
  2445. nullptr, ArgStruct, RetAI.getInAllocaFieldIndex());
  2446. RV = Builder.CreateAlignedLoad(SRet, getPointerAlign(), "sret");
  2447. }
  2448. break;
  2449. case ABIArgInfo::Indirect: {
  2450. auto AI = CurFn->arg_begin();
  2451. if (RetAI.isSRetAfterThis())
  2452. ++AI;
  2453. switch (getEvaluationKind(RetTy)) {
  2454. case TEK_Complex: {
  2455. ComplexPairTy RT =
  2456. EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc);
  2457. EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy),
  2458. /*isInit*/ true);
  2459. break;
  2460. }
  2461. case TEK_Aggregate:
  2462. // Do nothing; aggregrates get evaluated directly into the destination.
  2463. break;
  2464. case TEK_Scalar:
  2465. EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
  2466. MakeNaturalAlignAddrLValue(&*AI, RetTy),
  2467. /*isInit*/ true);
  2468. break;
  2469. }
  2470. break;
  2471. }
  2472. case ABIArgInfo::Extend:
  2473. case ABIArgInfo::Direct:
  2474. if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
  2475. RetAI.getDirectOffset() == 0) {
  2476. // The internal return value temp always will have pointer-to-return-type
  2477. // type, just do a load.
  2478. // If there is a dominating store to ReturnValue, we can elide
  2479. // the load, zap the store, and usually zap the alloca.
  2480. if (llvm::StoreInst *SI =
  2481. findDominatingStoreToReturnValue(*this)) {
  2482. // Reuse the debug location from the store unless there is
  2483. // cleanup code to be emitted between the store and return
  2484. // instruction.
  2485. if (EmitRetDbgLoc && !AutoreleaseResult)
  2486. RetDbgLoc = SI->getDebugLoc();
  2487. // Get the stored value and nuke the now-dead store.
  2488. RV = SI->getValueOperand();
  2489. SI->eraseFromParent();
  2490. // Otherwise, we have to do a simple load.
  2491. } else {
  2492. RV = Builder.CreateLoad(ReturnValue);
  2493. }
  2494. } else {
  2495. // If the value is offset in memory, apply the offset now.
  2496. Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
  2497. RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
  2498. }
  2499. // In ARC, end functions that return a retainable type with a call
  2500. // to objc_autoreleaseReturnValue.
  2501. if (AutoreleaseResult) {
  2502. #ifndef NDEBUG
  2503. // Type::isObjCRetainabletype has to be called on a QualType that hasn't
  2504. // been stripped of the typedefs, so we cannot use RetTy here. Get the
  2505. // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from
  2506. // CurCodeDecl or BlockInfo.
  2507. QualType RT;
  2508. if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl))
  2509. RT = FD->getReturnType();
  2510. else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl))
  2511. RT = MD->getReturnType();
  2512. else if (isa<BlockDecl>(CurCodeDecl))
  2513. RT = BlockInfo->BlockExpression->getFunctionType()->getReturnType();
  2514. else
  2515. llvm_unreachable("Unexpected function/method type");
  2516. assert(getLangOpts().ObjCAutoRefCount &&
  2517. !FI.isReturnsRetained() &&
  2518. RT->isObjCRetainableType());
  2519. #endif
  2520. RV = emitAutoreleaseOfResult(*this, RV);
  2521. }
  2522. break;
  2523. case ABIArgInfo::Ignore:
  2524. break;
  2525. case ABIArgInfo::CoerceAndExpand: {
  2526. auto coercionType = RetAI.getCoerceAndExpandType();
  2527. // Load all of the coerced elements out into results.
  2528. llvm::SmallVector<llvm::Value*, 4> results;
  2529. Address addr = Builder.CreateElementBitCast(ReturnValue, coercionType);
  2530. for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
  2531. auto coercedEltType = coercionType->getElementType(i);
  2532. if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType))
  2533. continue;
  2534. auto eltAddr = Builder.CreateStructGEP(addr, i);
  2535. auto elt = Builder.CreateLoad(eltAddr);
  2536. results.push_back(elt);
  2537. }
  2538. // If we have one result, it's the single direct result type.
  2539. if (results.size() == 1) {
  2540. RV = results[0];
  2541. // Otherwise, we need to make a first-class aggregate.
  2542. } else {
  2543. // Construct a return type that lacks padding elements.
  2544. llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType();
  2545. RV = llvm::UndefValue::get(returnType);
  2546. for (unsigned i = 0, e = results.size(); i != e; ++i) {
  2547. RV = Builder.CreateInsertValue(RV, results[i], i);
  2548. }
  2549. }
  2550. break;
  2551. }
  2552. case ABIArgInfo::Expand:
  2553. llvm_unreachable("Invalid ABI kind for return argument");
  2554. }
  2555. llvm::Instruction *Ret;
  2556. if (RV) {
  2557. EmitReturnValueCheck(RV);
  2558. Ret = Builder.CreateRet(RV);
  2559. } else {
  2560. Ret = Builder.CreateRetVoid();
  2561. }
  2562. if (RetDbgLoc)
  2563. Ret->setDebugLoc(std::move(RetDbgLoc));
  2564. }
  2565. void CodeGenFunction::EmitReturnValueCheck(llvm::Value *RV) {
  2566. // A current decl may not be available when emitting vtable thunks.
  2567. if (!CurCodeDecl)
  2568. return;
  2569. ReturnsNonNullAttr *RetNNAttr = nullptr;
  2570. if (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute))
  2571. RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>();
  2572. if (!RetNNAttr && !requiresReturnValueNullabilityCheck())
  2573. return;
  2574. // Prefer the returns_nonnull attribute if it's present.
  2575. SourceLocation AttrLoc;
  2576. SanitizerMask CheckKind;
  2577. SanitizerHandler Handler;
  2578. if (RetNNAttr) {
  2579. assert(!requiresReturnValueNullabilityCheck() &&
  2580. "Cannot check nullability and the nonnull attribute");
  2581. AttrLoc = RetNNAttr->getLocation();
  2582. CheckKind = SanitizerKind::ReturnsNonnullAttribute;
  2583. Handler = SanitizerHandler::NonnullReturn;
  2584. } else {
  2585. if (auto *DD = dyn_cast<DeclaratorDecl>(CurCodeDecl))
  2586. if (auto *TSI = DD->getTypeSourceInfo())
  2587. if (auto FTL = TSI->getTypeLoc().castAs<FunctionTypeLoc>())
  2588. AttrLoc = FTL.getReturnLoc().findNullabilityLoc();
  2589. CheckKind = SanitizerKind::NullabilityReturn;
  2590. Handler = SanitizerHandler::NullabilityReturn;
  2591. }
  2592. SanitizerScope SanScope(this);
  2593. // Make sure the "return" source location is valid. If we're checking a
  2594. // nullability annotation, make sure the preconditions for the check are met.
  2595. llvm::BasicBlock *Check = createBasicBlock("nullcheck");
  2596. llvm::BasicBlock *NoCheck = createBasicBlock("no.nullcheck");
  2597. llvm::Value *SLocPtr = Builder.CreateLoad(ReturnLocation, "return.sloc.load");
  2598. llvm::Value *CanNullCheck = Builder.CreateIsNotNull(SLocPtr);
  2599. if (requiresReturnValueNullabilityCheck())
  2600. CanNullCheck =
  2601. Builder.CreateAnd(CanNullCheck, RetValNullabilityPrecondition);
  2602. Builder.CreateCondBr(CanNullCheck, Check, NoCheck);
  2603. EmitBlock(Check);
  2604. // Now do the null check.
  2605. llvm::Value *Cond = Builder.CreateIsNotNull(RV);
  2606. llvm::Constant *StaticData[] = {EmitCheckSourceLocation(AttrLoc)};
  2607. llvm::Value *DynamicData[] = {SLocPtr};
  2608. EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, DynamicData);
  2609. EmitBlock(NoCheck);
  2610. #ifndef NDEBUG
  2611. // The return location should not be used after the check has been emitted.
  2612. ReturnLocation = Address::invalid();
  2613. #endif
  2614. }
  2615. static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
  2616. const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
  2617. return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
  2618. }
  2619. static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF,
  2620. QualType Ty) {
  2621. // FIXME: Generate IR in one pass, rather than going back and fixing up these
  2622. // placeholders.
  2623. llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
  2624. llvm::Type *IRPtrTy = IRTy->getPointerTo();
  2625. llvm::Value *Placeholder = llvm::UndefValue::get(IRPtrTy->getPointerTo());
  2626. // FIXME: When we generate this IR in one pass, we shouldn't need
  2627. // this win32-specific alignment hack.
  2628. CharUnits Align = CharUnits::fromQuantity(4);
  2629. Placeholder = CGF.Builder.CreateAlignedLoad(IRPtrTy, Placeholder, Align);
  2630. return AggValueSlot::forAddr(Address(Placeholder, Align),
  2631. Ty.getQualifiers(),
  2632. AggValueSlot::IsNotDestructed,
  2633. AggValueSlot::DoesNotNeedGCBarriers,
  2634. AggValueSlot::IsNotAliased,
  2635. AggValueSlot::DoesNotOverlap);
  2636. }
  2637. void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
  2638. const VarDecl *param,
  2639. SourceLocation loc) {
  2640. // StartFunction converted the ABI-lowered parameter(s) into a
  2641. // local alloca. We need to turn that into an r-value suitable
  2642. // for EmitCall.
  2643. Address local = GetAddrOfLocalVar(param);
  2644. QualType type = param->getType();
  2645. if (isInAllocaArgument(CGM.getCXXABI(), type)) {
  2646. CGM.ErrorUnsupported(param, "forwarded non-trivially copyable parameter");
  2647. }
  2648. // GetAddrOfLocalVar returns a pointer-to-pointer for references,
  2649. // but the argument needs to be the original pointer.
  2650. if (type->isReferenceType()) {
  2651. args.add(RValue::get(Builder.CreateLoad(local)), type);
  2652. // In ARC, move out of consumed arguments so that the release cleanup
  2653. // entered by StartFunction doesn't cause an over-release. This isn't
  2654. // optimal -O0 code generation, but it should get cleaned up when
  2655. // optimization is enabled. This also assumes that delegate calls are
  2656. // performed exactly once for a set of arguments, but that should be safe.
  2657. } else if (getLangOpts().ObjCAutoRefCount &&
  2658. param->hasAttr<NSConsumedAttr>() &&
  2659. type->isObjCRetainableType()) {
  2660. llvm::Value *ptr = Builder.CreateLoad(local);
  2661. auto null =
  2662. llvm::ConstantPointerNull::get(cast<llvm::PointerType>(ptr->getType()));
  2663. Builder.CreateStore(null, local);
  2664. args.add(RValue::get(ptr), type);
  2665. // For the most part, we just need to load the alloca, except that
  2666. // aggregate r-values are actually pointers to temporaries.
  2667. } else {
  2668. args.add(convertTempToRValue(local, type, loc), type);
  2669. }
  2670. // Deactivate the cleanup for the callee-destructed param that was pushed.
  2671. if (hasAggregateEvaluationKind(type) && !CurFuncIsThunk &&
  2672. type->getAs<RecordType>()->getDecl()->isParamDestroyedInCallee() &&
  2673. type.isDestructedType()) {
  2674. EHScopeStack::stable_iterator cleanup =
  2675. CalleeDestructedParamCleanups.lookup(cast<ParmVarDecl>(param));
  2676. assert(cleanup.isValid() &&
  2677. "cleanup for callee-destructed param not recorded");
  2678. // This unreachable is a temporary marker which will be removed later.
  2679. llvm::Instruction *isActive = Builder.CreateUnreachable();
  2680. args.addArgCleanupDeactivation(cleanup, isActive);
  2681. }
  2682. }
  2683. static bool isProvablyNull(llvm::Value *addr) {
  2684. return isa<llvm::ConstantPointerNull>(addr);
  2685. }
  2686. /// Emit the actual writing-back of a writeback.
  2687. static void emitWriteback(CodeGenFunction &CGF,
  2688. const CallArgList::Writeback &writeback) {
  2689. const LValue &srcLV = writeback.Source;
  2690. Address srcAddr = srcLV.getAddress();
  2691. assert(!isProvablyNull(srcAddr.getPointer()) &&
  2692. "shouldn't have writeback for provably null argument");
  2693. llvm::BasicBlock *contBB = nullptr;
  2694. // If the argument wasn't provably non-null, we need to null check
  2695. // before doing the store.
  2696. bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(),
  2697. CGF.CGM.getDataLayout());
  2698. if (!provablyNonNull) {
  2699. llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
  2700. contBB = CGF.createBasicBlock("icr.done");
  2701. llvm::Value *isNull =
  2702. CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
  2703. CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
  2704. CGF.EmitBlock(writebackBB);
  2705. }
  2706. // Load the value to writeback.
  2707. llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
  2708. // Cast it back, in case we're writing an id to a Foo* or something.
  2709. value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(),
  2710. "icr.writeback-cast");
  2711. // Perform the writeback.
  2712. // If we have a "to use" value, it's something we need to emit a use
  2713. // of. This has to be carefully threaded in: if it's done after the
  2714. // release it's potentially undefined behavior (and the optimizer
  2715. // will ignore it), and if it happens before the retain then the
  2716. // optimizer could move the release there.
  2717. if (writeback.ToUse) {
  2718. assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
  2719. // Retain the new value. No need to block-copy here: the block's
  2720. // being passed up the stack.
  2721. value = CGF.EmitARCRetainNonBlock(value);
  2722. // Emit the intrinsic use here.
  2723. CGF.EmitARCIntrinsicUse(writeback.ToUse);
  2724. // Load the old value (primitively).
  2725. llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
  2726. // Put the new value in place (primitively).
  2727. CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
  2728. // Release the old value.
  2729. CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
  2730. // Otherwise, we can just do a normal lvalue store.
  2731. } else {
  2732. CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
  2733. }
  2734. // Jump to the continuation block.
  2735. if (!provablyNonNull)
  2736. CGF.EmitBlock(contBB);
  2737. }
  2738. static void emitWritebacks(CodeGenFunction &CGF,
  2739. const CallArgList &args) {
  2740. for (const auto &I : args.writebacks())
  2741. emitWriteback(CGF, I);
  2742. }
  2743. static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
  2744. const CallArgList &CallArgs) {
  2745. ArrayRef<CallArgList::CallArgCleanup> Cleanups =
  2746. CallArgs.getCleanupsToDeactivate();
  2747. // Iterate in reverse to increase the likelihood of popping the cleanup.
  2748. for (const auto &I : llvm::reverse(Cleanups)) {
  2749. CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP);
  2750. I.IsActiveIP->eraseFromParent();
  2751. }
  2752. }
  2753. static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
  2754. if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
  2755. if (uop->getOpcode() == UO_AddrOf)
  2756. return uop->getSubExpr();
  2757. return nullptr;
  2758. }
  2759. /// Emit an argument that's being passed call-by-writeback. That is,
  2760. /// we are passing the address of an __autoreleased temporary; it
  2761. /// might be copy-initialized with the current value of the given
  2762. /// address, but it will definitely be copied out of after the call.
  2763. static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
  2764. const ObjCIndirectCopyRestoreExpr *CRE) {
  2765. LValue srcLV;
  2766. // Make an optimistic effort to emit the address as an l-value.
  2767. // This can fail if the argument expression is more complicated.
  2768. if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
  2769. srcLV = CGF.EmitLValue(lvExpr);
  2770. // Otherwise, just emit it as a scalar.
  2771. } else {
  2772. Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr());
  2773. QualType srcAddrType =
  2774. CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
  2775. srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
  2776. }
  2777. Address srcAddr = srcLV.getAddress();
  2778. // The dest and src types don't necessarily match in LLVM terms
  2779. // because of the crazy ObjC compatibility rules.
  2780. llvm::PointerType *destType =
  2781. cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
  2782. // If the address is a constant null, just pass the appropriate null.
  2783. if (isProvablyNull(srcAddr.getPointer())) {
  2784. args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
  2785. CRE->getType());
  2786. return;
  2787. }
  2788. // Create the temporary.
  2789. Address temp = CGF.CreateTempAlloca(destType->getElementType(),
  2790. CGF.getPointerAlign(),
  2791. "icr.temp");
  2792. // Loading an l-value can introduce a cleanup if the l-value is __weak,
  2793. // and that cleanup will be conditional if we can't prove that the l-value
  2794. // isn't null, so we need to register a dominating point so that the cleanups
  2795. // system will make valid IR.
  2796. CodeGenFunction::ConditionalEvaluation condEval(CGF);
  2797. // Zero-initialize it if we're not doing a copy-initialization.
  2798. bool shouldCopy = CRE->shouldCopy();
  2799. if (!shouldCopy) {
  2800. llvm::Value *null =
  2801. llvm::ConstantPointerNull::get(
  2802. cast<llvm::PointerType>(destType->getElementType()));
  2803. CGF.Builder.CreateStore(null, temp);
  2804. }
  2805. llvm::BasicBlock *contBB = nullptr;
  2806. llvm::BasicBlock *originBB = nullptr;
  2807. // If the address is *not* known to be non-null, we need to switch.
  2808. llvm::Value *finalArgument;
  2809. bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(),
  2810. CGF.CGM.getDataLayout());
  2811. if (provablyNonNull) {
  2812. finalArgument = temp.getPointer();
  2813. } else {
  2814. llvm::Value *isNull =
  2815. CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
  2816. finalArgument = CGF.Builder.CreateSelect(isNull,
  2817. llvm::ConstantPointerNull::get(destType),
  2818. temp.getPointer(), "icr.argument");
  2819. // If we need to copy, then the load has to be conditional, which
  2820. // means we need control flow.
  2821. if (shouldCopy) {
  2822. originBB = CGF.Builder.GetInsertBlock();
  2823. contBB = CGF.createBasicBlock("icr.cont");
  2824. llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
  2825. CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
  2826. CGF.EmitBlock(copyBB);
  2827. condEval.begin(CGF);
  2828. }
  2829. }
  2830. llvm::Value *valueToUse = nullptr;
  2831. // Perform a copy if necessary.
  2832. if (shouldCopy) {
  2833. RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
  2834. assert(srcRV.isScalar());
  2835. llvm::Value *src = srcRV.getScalarVal();
  2836. src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
  2837. "icr.cast");
  2838. // Use an ordinary store, not a store-to-lvalue.
  2839. CGF.Builder.CreateStore(src, temp);
  2840. // If optimization is enabled, and the value was held in a
  2841. // __strong variable, we need to tell the optimizer that this
  2842. // value has to stay alive until we're doing the store back.
  2843. // This is because the temporary is effectively unretained,
  2844. // and so otherwise we can violate the high-level semantics.
  2845. if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
  2846. srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
  2847. valueToUse = src;
  2848. }
  2849. }
  2850. // Finish the control flow if we needed it.
  2851. if (shouldCopy && !provablyNonNull) {
  2852. llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
  2853. CGF.EmitBlock(contBB);
  2854. // Make a phi for the value to intrinsically use.
  2855. if (valueToUse) {
  2856. llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
  2857. "icr.to-use");
  2858. phiToUse->addIncoming(valueToUse, copyBB);
  2859. phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
  2860. originBB);
  2861. valueToUse = phiToUse;
  2862. }
  2863. condEval.end(CGF);
  2864. }
  2865. args.addWriteback(srcLV, temp, valueToUse);
  2866. args.add(RValue::get(finalArgument), CRE->getType());
  2867. }
  2868. void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
  2869. assert(!StackBase);
  2870. // Save the stack.
  2871. llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
  2872. StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save");
  2873. }
  2874. void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
  2875. if (StackBase) {
  2876. // Restore the stack after the call.
  2877. llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
  2878. CGF.Builder.CreateCall(F, StackBase);
  2879. }
  2880. }
  2881. void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType,
  2882. SourceLocation ArgLoc,
  2883. AbstractCallee AC,
  2884. unsigned ParmNum) {
  2885. if (!AC.getDecl() || !(SanOpts.has(SanitizerKind::NonnullAttribute) ||
  2886. SanOpts.has(SanitizerKind::NullabilityArg)))
  2887. return;
  2888. // The param decl may be missing in a variadic function.
  2889. auto PVD = ParmNum < AC.getNumParams() ? AC.getParamDecl(ParmNum) : nullptr;
  2890. unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
  2891. // Prefer the nonnull attribute if it's present.
  2892. const NonNullAttr *NNAttr = nullptr;
  2893. if (SanOpts.has(SanitizerKind::NonnullAttribute))
  2894. NNAttr = getNonNullAttr(AC.getDecl(), PVD, ArgType, ArgNo);
  2895. bool CanCheckNullability = false;
  2896. if (SanOpts.has(SanitizerKind::NullabilityArg) && !NNAttr && PVD) {
  2897. auto Nullability = PVD->getType()->getNullability(getContext());
  2898. CanCheckNullability = Nullability &&
  2899. *Nullability == NullabilityKind::NonNull &&
  2900. PVD->getTypeSourceInfo();
  2901. }
  2902. if (!NNAttr && !CanCheckNullability)
  2903. return;
  2904. SourceLocation AttrLoc;
  2905. SanitizerMask CheckKind;
  2906. SanitizerHandler Handler;
  2907. if (NNAttr) {
  2908. AttrLoc = NNAttr->getLocation();
  2909. CheckKind = SanitizerKind::NonnullAttribute;
  2910. Handler = SanitizerHandler::NonnullArg;
  2911. } else {
  2912. AttrLoc = PVD->getTypeSourceInfo()->getTypeLoc().findNullabilityLoc();
  2913. CheckKind = SanitizerKind::NullabilityArg;
  2914. Handler = SanitizerHandler::NullabilityArg;
  2915. }
  2916. SanitizerScope SanScope(this);
  2917. assert(RV.isScalar());
  2918. llvm::Value *V = RV.getScalarVal();
  2919. llvm::Value *Cond =
  2920. Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
  2921. llvm::Constant *StaticData[] = {
  2922. EmitCheckSourceLocation(ArgLoc), EmitCheckSourceLocation(AttrLoc),
  2923. llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
  2924. };
  2925. EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, None);
  2926. }
  2927. void CodeGenFunction::EmitCallArgs(
  2928. CallArgList &Args, ArrayRef<QualType> ArgTypes,
  2929. llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
  2930. AbstractCallee AC, unsigned ParamsToSkip, EvaluationOrder Order) {
  2931. assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()));
  2932. // We *have* to evaluate arguments from right to left in the MS C++ ABI,
  2933. // because arguments are destroyed left to right in the callee. As a special
  2934. // case, there are certain language constructs that require left-to-right
  2935. // evaluation, and in those cases we consider the evaluation order requirement
  2936. // to trump the "destruction order is reverse construction order" guarantee.
  2937. bool LeftToRight =
  2938. CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()
  2939. ? Order == EvaluationOrder::ForceLeftToRight
  2940. : Order != EvaluationOrder::ForceRightToLeft;
  2941. auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg,
  2942. RValue EmittedArg) {
  2943. if (!AC.hasFunctionDecl() || I >= AC.getNumParams())
  2944. return;
  2945. auto *PS = AC.getParamDecl(I)->getAttr<PassObjectSizeAttr>();
  2946. if (PS == nullptr)
  2947. return;
  2948. const auto &Context = getContext();
  2949. auto SizeTy = Context.getSizeType();
  2950. auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
  2951. assert(EmittedArg.getScalarVal() && "We emitted nothing for the arg?");
  2952. llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T,
  2953. EmittedArg.getScalarVal(),
  2954. PS->isDynamic());
  2955. Args.add(RValue::get(V), SizeTy);
  2956. // If we're emitting args in reverse, be sure to do so with
  2957. // pass_object_size, as well.
  2958. if (!LeftToRight)
  2959. std::swap(Args.back(), *(&Args.back() - 1));
  2960. };
  2961. // Insert a stack save if we're going to need any inalloca args.
  2962. bool HasInAllocaArgs = false;
  2963. if (CGM.getTarget().getCXXABI().isMicrosoft()) {
  2964. for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
  2965. I != E && !HasInAllocaArgs; ++I)
  2966. HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
  2967. if (HasInAllocaArgs) {
  2968. assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
  2969. Args.allocateArgumentMemory(*this);
  2970. }
  2971. }
  2972. // Evaluate each argument in the appropriate order.
  2973. size_t CallArgsStart = Args.size();
  2974. for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
  2975. unsigned Idx = LeftToRight ? I : E - I - 1;
  2976. CallExpr::const_arg_iterator Arg = ArgRange.begin() + Idx;
  2977. unsigned InitialArgSize = Args.size();
  2978. // If *Arg is an ObjCIndirectCopyRestoreExpr, check that either the types of
  2979. // the argument and parameter match or the objc method is parameterized.
  2980. assert((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) ||
  2981. getContext().hasSameUnqualifiedType((*Arg)->getType(),
  2982. ArgTypes[Idx]) ||
  2983. (isa<ObjCMethodDecl>(AC.getDecl()) &&
  2984. isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) &&
  2985. "Argument and parameter types don't match");
  2986. EmitCallArg(Args, *Arg, ArgTypes[Idx]);
  2987. // In particular, we depend on it being the last arg in Args, and the
  2988. // objectsize bits depend on there only being one arg if !LeftToRight.
  2989. assert(InitialArgSize + 1 == Args.size() &&
  2990. "The code below depends on only adding one arg per EmitCallArg");
  2991. (void)InitialArgSize;
  2992. // Since pointer argument are never emitted as LValue, it is safe to emit
  2993. // non-null argument check for r-value only.
  2994. if (!Args.back().hasLValue()) {
  2995. RValue RVArg = Args.back().getKnownRValue();
  2996. EmitNonNullArgCheck(RVArg, ArgTypes[Idx], (*Arg)->getExprLoc(), AC,
  2997. ParamsToSkip + Idx);
  2998. // @llvm.objectsize should never have side-effects and shouldn't need
  2999. // destruction/cleanups, so we can safely "emit" it after its arg,
  3000. // regardless of right-to-leftness
  3001. MaybeEmitImplicitObjectSize(Idx, *Arg, RVArg);
  3002. }
  3003. }
  3004. if (!LeftToRight) {
  3005. // Un-reverse the arguments we just evaluated so they match up with the LLVM
  3006. // IR function.
  3007. std::reverse(Args.begin() + CallArgsStart, Args.end());
  3008. }
  3009. }
  3010. namespace {
  3011. struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
  3012. DestroyUnpassedArg(Address Addr, QualType Ty)
  3013. : Addr(Addr), Ty(Ty) {}
  3014. Address Addr;
  3015. QualType Ty;
  3016. void Emit(CodeGenFunction &CGF, Flags flags) override {
  3017. QualType::DestructionKind DtorKind = Ty.isDestructedType();
  3018. if (DtorKind == QualType::DK_cxx_destructor) {
  3019. const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
  3020. assert(!Dtor->isTrivial());
  3021. CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
  3022. /*Delegating=*/false, Addr, Ty);
  3023. } else {
  3024. CGF.callCStructDestructor(CGF.MakeAddrLValue(Addr, Ty));
  3025. }
  3026. }
  3027. };
  3028. struct DisableDebugLocationUpdates {
  3029. CodeGenFunction &CGF;
  3030. bool disabledDebugInfo;
  3031. DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
  3032. if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
  3033. CGF.disableDebugInfo();
  3034. }
  3035. ~DisableDebugLocationUpdates() {
  3036. if (disabledDebugInfo)
  3037. CGF.enableDebugInfo();
  3038. }
  3039. };
  3040. } // end anonymous namespace
  3041. RValue CallArg::getRValue(CodeGenFunction &CGF) const {
  3042. if (!HasLV)
  3043. return RV;
  3044. LValue Copy = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty), Ty);
  3045. CGF.EmitAggregateCopy(Copy, LV, Ty, AggValueSlot::DoesNotOverlap,
  3046. LV.isVolatile());
  3047. IsUsed = true;
  3048. return RValue::getAggregate(Copy.getAddress());
  3049. }
  3050. void CallArg::copyInto(CodeGenFunction &CGF, Address Addr) const {
  3051. LValue Dst = CGF.MakeAddrLValue(Addr, Ty);
  3052. if (!HasLV && RV.isScalar())
  3053. CGF.EmitStoreOfScalar(RV.getScalarVal(), Dst, /*isInit=*/true);
  3054. else if (!HasLV && RV.isComplex())
  3055. CGF.EmitStoreOfComplex(RV.getComplexVal(), Dst, /*init=*/true);
  3056. else {
  3057. auto Addr = HasLV ? LV.getAddress() : RV.getAggregateAddress();
  3058. LValue SrcLV = CGF.MakeAddrLValue(Addr, Ty);
  3059. // We assume that call args are never copied into subobjects.
  3060. CGF.EmitAggregateCopy(Dst, SrcLV, Ty, AggValueSlot::DoesNotOverlap,
  3061. HasLV ? LV.isVolatileQualified()
  3062. : RV.isVolatileQualified());
  3063. }
  3064. IsUsed = true;
  3065. }
  3066. void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
  3067. QualType type) {
  3068. DisableDebugLocationUpdates Dis(*this, E);
  3069. if (const ObjCIndirectCopyRestoreExpr *CRE
  3070. = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
  3071. assert(getLangOpts().ObjCAutoRefCount);
  3072. return emitWritebackArg(*this, args, CRE);
  3073. }
  3074. assert(type->isReferenceType() == E->isGLValue() &&
  3075. "reference binding to unmaterialized r-value!");
  3076. if (E->isGLValue()) {
  3077. assert(E->getObjectKind() == OK_Ordinary);
  3078. return args.add(EmitReferenceBindingToExpr(E), type);
  3079. }
  3080. bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
  3081. // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
  3082. // However, we still have to push an EH-only cleanup in case we unwind before
  3083. // we make it to the call.
  3084. if (HasAggregateEvalKind &&
  3085. type->getAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
  3086. // If we're using inalloca, use the argument memory. Otherwise, use a
  3087. // temporary.
  3088. AggValueSlot Slot;
  3089. if (args.isUsingInAlloca())
  3090. Slot = createPlaceholderSlot(*this, type);
  3091. else
  3092. Slot = CreateAggTemp(type, "agg.tmp");
  3093. bool DestroyedInCallee = true, NeedsEHCleanup = true;
  3094. if (const auto *RD = type->getAsCXXRecordDecl())
  3095. DestroyedInCallee = RD->hasNonTrivialDestructor();
  3096. else
  3097. NeedsEHCleanup = needsEHCleanup(type.isDestructedType());
  3098. if (DestroyedInCallee)
  3099. Slot.setExternallyDestructed();
  3100. EmitAggExpr(E, Slot);
  3101. RValue RV = Slot.asRValue();
  3102. args.add(RV, type);
  3103. if (DestroyedInCallee && NeedsEHCleanup) {
  3104. // Create a no-op GEP between the placeholder and the cleanup so we can
  3105. // RAUW it successfully. It also serves as a marker of the first
  3106. // instruction where the cleanup is active.
  3107. pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddress(),
  3108. type);
  3109. // This unreachable is a temporary marker which will be removed later.
  3110. llvm::Instruction *IsActive = Builder.CreateUnreachable();
  3111. args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
  3112. }
  3113. return;
  3114. }
  3115. if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
  3116. cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
  3117. LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
  3118. assert(L.isSimple());
  3119. args.addUncopiedAggregate(L, type);
  3120. return;
  3121. }
  3122. args.add(EmitAnyExprToTemp(E), type);
  3123. }
  3124. QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
  3125. // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
  3126. // implicitly widens null pointer constants that are arguments to varargs
  3127. // functions to pointer-sized ints.
  3128. if (!getTarget().getTriple().isOSWindows())
  3129. return Arg->getType();
  3130. if (Arg->getType()->isIntegerType() &&
  3131. getContext().getTypeSize(Arg->getType()) <
  3132. getContext().getTargetInfo().getPointerWidth(0) &&
  3133. Arg->isNullPointerConstant(getContext(),
  3134. Expr::NPC_ValueDependentIsNotNull)) {
  3135. return getContext().getIntPtrType();
  3136. }
  3137. return Arg->getType();
  3138. }
  3139. // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
  3140. // optimizer it can aggressively ignore unwind edges.
  3141. void
  3142. CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
  3143. if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
  3144. !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
  3145. Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
  3146. CGM.getNoObjCARCExceptionsMetadata());
  3147. }
  3148. /// Emits a call to the given no-arguments nounwind runtime function.
  3149. llvm::CallInst *
  3150. CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
  3151. const llvm::Twine &name) {
  3152. return EmitNounwindRuntimeCall(callee, None, name);
  3153. }
  3154. /// Emits a call to the given nounwind runtime function.
  3155. llvm::CallInst *
  3156. CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
  3157. ArrayRef<llvm::Value *> args,
  3158. const llvm::Twine &name) {
  3159. llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
  3160. call->setDoesNotThrow();
  3161. return call;
  3162. }
  3163. /// Emits a simple call (never an invoke) to the given no-arguments
  3164. /// runtime function.
  3165. llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
  3166. const llvm::Twine &name) {
  3167. return EmitRuntimeCall(callee, None, name);
  3168. }
  3169. // Calls which may throw must have operand bundles indicating which funclet
  3170. // they are nested within.
  3171. SmallVector<llvm::OperandBundleDef, 1>
  3172. CodeGenFunction::getBundlesForFunclet(llvm::Value *Callee) {
  3173. SmallVector<llvm::OperandBundleDef, 1> BundleList;
  3174. // There is no need for a funclet operand bundle if we aren't inside a
  3175. // funclet.
  3176. if (!CurrentFuncletPad)
  3177. return BundleList;
  3178. // Skip intrinsics which cannot throw.
  3179. auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts());
  3180. if (CalleeFn && CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow())
  3181. return BundleList;
  3182. BundleList.emplace_back("funclet", CurrentFuncletPad);
  3183. return BundleList;
  3184. }
  3185. /// Emits a simple call (never an invoke) to the given runtime function.
  3186. llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
  3187. ArrayRef<llvm::Value *> args,
  3188. const llvm::Twine &name) {
  3189. llvm::CallInst *call = Builder.CreateCall(
  3190. callee, args, getBundlesForFunclet(callee.getCallee()), name);
  3191. call->setCallingConv(getRuntimeCC());
  3192. return call;
  3193. }
  3194. /// Emits a call or invoke to the given noreturn runtime function.
  3195. void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(
  3196. llvm::FunctionCallee callee, ArrayRef<llvm::Value *> args) {
  3197. SmallVector<llvm::OperandBundleDef, 1> BundleList =
  3198. getBundlesForFunclet(callee.getCallee());
  3199. if (getInvokeDest()) {
  3200. llvm::InvokeInst *invoke =
  3201. Builder.CreateInvoke(callee,
  3202. getUnreachableBlock(),
  3203. getInvokeDest(),
  3204. args,
  3205. BundleList);
  3206. invoke->setDoesNotReturn();
  3207. invoke->setCallingConv(getRuntimeCC());
  3208. } else {
  3209. llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList);
  3210. call->setDoesNotReturn();
  3211. call->setCallingConv(getRuntimeCC());
  3212. Builder.CreateUnreachable();
  3213. }
  3214. }
  3215. /// Emits a call or invoke instruction to the given nullary runtime function.
  3216. llvm::CallBase *
  3217. CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
  3218. const Twine &name) {
  3219. return EmitRuntimeCallOrInvoke(callee, None, name);
  3220. }
  3221. /// Emits a call or invoke instruction to the given runtime function.
  3222. llvm::CallBase *
  3223. CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
  3224. ArrayRef<llvm::Value *> args,
  3225. const Twine &name) {
  3226. llvm::CallBase *call = EmitCallOrInvoke(callee, args, name);
  3227. call->setCallingConv(getRuntimeCC());
  3228. return call;
  3229. }
  3230. /// Emits a call or invoke instruction to the given function, depending
  3231. /// on the current state of the EH stack.
  3232. llvm::CallBase *CodeGenFunction::EmitCallOrInvoke(llvm::FunctionCallee Callee,
  3233. ArrayRef<llvm::Value *> Args,
  3234. const Twine &Name) {
  3235. llvm::BasicBlock *InvokeDest = getInvokeDest();
  3236. SmallVector<llvm::OperandBundleDef, 1> BundleList =
  3237. getBundlesForFunclet(Callee.getCallee());
  3238. llvm::CallBase *Inst;
  3239. if (!InvokeDest)
  3240. Inst = Builder.CreateCall(Callee, Args, BundleList, Name);
  3241. else {
  3242. llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
  3243. Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList,
  3244. Name);
  3245. EmitBlock(ContBB);
  3246. }
  3247. // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
  3248. // optimizer it can aggressively ignore unwind edges.
  3249. if (CGM.getLangOpts().ObjCAutoRefCount)
  3250. AddObjCARCExceptionMetadata(Inst);
  3251. return Inst;
  3252. }
  3253. void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
  3254. llvm::Value *New) {
  3255. DeferredReplacements.push_back(std::make_pair(Old, New));
  3256. }
  3257. RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
  3258. const CGCallee &Callee,
  3259. ReturnValueSlot ReturnValue,
  3260. const CallArgList &CallArgs,
  3261. llvm::CallBase **callOrInvoke,
  3262. SourceLocation Loc) {
  3263. // FIXME: We no longer need the types from CallArgs; lift up and simplify.
  3264. assert(Callee.isOrdinary() || Callee.isVirtual());
  3265. // Handle struct-return functions by passing a pointer to the
  3266. // location that we would like to return into.
  3267. QualType RetTy = CallInfo.getReturnType();
  3268. const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
  3269. llvm::FunctionType *IRFuncTy = getTypes().GetFunctionType(CallInfo);
  3270. const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
  3271. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
  3272. // We can only guarantee that a function is called from the correct
  3273. // context/function based on the appropriate target attributes,
  3274. // so only check in the case where we have both always_inline and target
  3275. // since otherwise we could be making a conditional call after a check for
  3276. // the proper cpu features (and it won't cause code generation issues due to
  3277. // function based code generation).
  3278. if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
  3279. TargetDecl->hasAttr<TargetAttr>())
  3280. checkTargetFeatures(Loc, FD);
  3281. #ifndef NDEBUG
  3282. if (!(CallInfo.isVariadic() && CallInfo.getArgStruct())) {
  3283. // For an inalloca varargs function, we don't expect CallInfo to match the
  3284. // function pointer's type, because the inalloca struct a will have extra
  3285. // fields in it for the varargs parameters. Code later in this function
  3286. // bitcasts the function pointer to the type derived from CallInfo.
  3287. //
  3288. // In other cases, we assert that the types match up (until pointers stop
  3289. // having pointee types).
  3290. llvm::Type *TypeFromVal;
  3291. if (Callee.isVirtual())
  3292. TypeFromVal = Callee.getVirtualFunctionType();
  3293. else
  3294. TypeFromVal =
  3295. Callee.getFunctionPointer()->getType()->getPointerElementType();
  3296. assert(IRFuncTy == TypeFromVal);
  3297. }
  3298. #endif
  3299. // 1. Set up the arguments.
  3300. // If we're using inalloca, insert the allocation after the stack save.
  3301. // FIXME: Do this earlier rather than hacking it in here!
  3302. Address ArgMemory = Address::invalid();
  3303. if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
  3304. const llvm::DataLayout &DL = CGM.getDataLayout();
  3305. llvm::Instruction *IP = CallArgs.getStackBase();
  3306. llvm::AllocaInst *AI;
  3307. if (IP) {
  3308. IP = IP->getNextNode();
  3309. AI = new llvm::AllocaInst(ArgStruct, DL.getAllocaAddrSpace(),
  3310. "argmem", IP);
  3311. } else {
  3312. AI = CreateTempAlloca(ArgStruct, "argmem");
  3313. }
  3314. auto Align = CallInfo.getArgStructAlignment();
  3315. AI->setAlignment(Align.getQuantity());
  3316. AI->setUsedWithInAlloca(true);
  3317. assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
  3318. ArgMemory = Address(AI, Align);
  3319. }
  3320. ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
  3321. SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
  3322. // If the call returns a temporary with struct return, create a temporary
  3323. // alloca to hold the result, unless one is given to us.
  3324. Address SRetPtr = Address::invalid();
  3325. Address SRetAlloca = Address::invalid();
  3326. llvm::Value *UnusedReturnSizePtr = nullptr;
  3327. if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) {
  3328. if (!ReturnValue.isNull()) {
  3329. SRetPtr = ReturnValue.getValue();
  3330. } else {
  3331. SRetPtr = CreateMemTemp(RetTy, "tmp", &SRetAlloca);
  3332. if (HaveInsertPoint() && ReturnValue.isUnused()) {
  3333. uint64_t size =
  3334. CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
  3335. UnusedReturnSizePtr = EmitLifetimeStart(size, SRetAlloca.getPointer());
  3336. }
  3337. }
  3338. if (IRFunctionArgs.hasSRetArg()) {
  3339. IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr.getPointer();
  3340. } else if (RetAI.isInAlloca()) {
  3341. Address Addr =
  3342. Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex());
  3343. Builder.CreateStore(SRetPtr.getPointer(), Addr);
  3344. }
  3345. }
  3346. Address swiftErrorTemp = Address::invalid();
  3347. Address swiftErrorArg = Address::invalid();
  3348. // Translate all of the arguments as necessary to match the IR lowering.
  3349. assert(CallInfo.arg_size() == CallArgs.size() &&
  3350. "Mismatch between function signature & arguments.");
  3351. unsigned ArgNo = 0;
  3352. CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
  3353. for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
  3354. I != E; ++I, ++info_it, ++ArgNo) {
  3355. const ABIArgInfo &ArgInfo = info_it->info;
  3356. // Insert a padding argument to ensure proper alignment.
  3357. if (IRFunctionArgs.hasPaddingArg(ArgNo))
  3358. IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
  3359. llvm::UndefValue::get(ArgInfo.getPaddingType());
  3360. unsigned FirstIRArg, NumIRArgs;
  3361. std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
  3362. switch (ArgInfo.getKind()) {
  3363. case ABIArgInfo::InAlloca: {
  3364. assert(NumIRArgs == 0);
  3365. assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
  3366. if (I->isAggregate()) {
  3367. // Replace the placeholder with the appropriate argument slot GEP.
  3368. Address Addr = I->hasLValue()
  3369. ? I->getKnownLValue().getAddress()
  3370. : I->getKnownRValue().getAggregateAddress();
  3371. llvm::Instruction *Placeholder =
  3372. cast<llvm::Instruction>(Addr.getPointer());
  3373. CGBuilderTy::InsertPoint IP = Builder.saveIP();
  3374. Builder.SetInsertPoint(Placeholder);
  3375. Addr =
  3376. Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
  3377. Builder.restoreIP(IP);
  3378. deferPlaceholderReplacement(Placeholder, Addr.getPointer());
  3379. } else {
  3380. // Store the RValue into the argument struct.
  3381. Address Addr =
  3382. Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
  3383. unsigned AS = Addr.getType()->getPointerAddressSpace();
  3384. llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
  3385. // There are some cases where a trivial bitcast is not avoidable. The
  3386. // definition of a type later in a translation unit may change it's type
  3387. // from {}* to (%struct.foo*)*.
  3388. if (Addr.getType() != MemType)
  3389. Addr = Builder.CreateBitCast(Addr, MemType);
  3390. I->copyInto(*this, Addr);
  3391. }
  3392. break;
  3393. }
  3394. case ABIArgInfo::Indirect: {
  3395. assert(NumIRArgs == 1);
  3396. if (!I->isAggregate()) {
  3397. // Make a temporary alloca to pass the argument.
  3398. Address Addr = CreateMemTempWithoutCast(
  3399. I->Ty, ArgInfo.getIndirectAlign(), "indirect-arg-temp");
  3400. IRCallArgs[FirstIRArg] = Addr.getPointer();
  3401. I->copyInto(*this, Addr);
  3402. } else {
  3403. // We want to avoid creating an unnecessary temporary+copy here;
  3404. // however, we need one in three cases:
  3405. // 1. If the argument is not byval, and we are required to copy the
  3406. // source. (This case doesn't occur on any common architecture.)
  3407. // 2. If the argument is byval, RV is not sufficiently aligned, and
  3408. // we cannot force it to be sufficiently aligned.
  3409. // 3. If the argument is byval, but RV is not located in default
  3410. // or alloca address space.
  3411. Address Addr = I->hasLValue()
  3412. ? I->getKnownLValue().getAddress()
  3413. : I->getKnownRValue().getAggregateAddress();
  3414. llvm::Value *V = Addr.getPointer();
  3415. CharUnits Align = ArgInfo.getIndirectAlign();
  3416. const llvm::DataLayout *TD = &CGM.getDataLayout();
  3417. assert((FirstIRArg >= IRFuncTy->getNumParams() ||
  3418. IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() ==
  3419. TD->getAllocaAddrSpace()) &&
  3420. "indirect argument must be in alloca address space");
  3421. bool NeedCopy = false;
  3422. if (Addr.getAlignment() < Align &&
  3423. llvm::getOrEnforceKnownAlignment(V, Align.getQuantity(), *TD) <
  3424. Align.getQuantity()) {
  3425. NeedCopy = true;
  3426. } else if (I->hasLValue()) {
  3427. auto LV = I->getKnownLValue();
  3428. auto AS = LV.getAddressSpace();
  3429. if ((!ArgInfo.getIndirectByVal() &&
  3430. (LV.getAlignment() >=
  3431. getContext().getTypeAlignInChars(I->Ty)))) {
  3432. NeedCopy = true;
  3433. }
  3434. if (!getLangOpts().OpenCL) {
  3435. if ((ArgInfo.getIndirectByVal() &&
  3436. (AS != LangAS::Default &&
  3437. AS != CGM.getASTAllocaAddressSpace()))) {
  3438. NeedCopy = true;
  3439. }
  3440. }
  3441. // For OpenCL even if RV is located in default or alloca address space
  3442. // we don't want to perform address space cast for it.
  3443. else if ((ArgInfo.getIndirectByVal() &&
  3444. Addr.getType()->getAddressSpace() != IRFuncTy->
  3445. getParamType(FirstIRArg)->getPointerAddressSpace())) {
  3446. NeedCopy = true;
  3447. }
  3448. }
  3449. if (NeedCopy) {
  3450. // Create an aligned temporary, and copy to it.
  3451. Address AI = CreateMemTempWithoutCast(
  3452. I->Ty, ArgInfo.getIndirectAlign(), "byval-temp");
  3453. IRCallArgs[FirstIRArg] = AI.getPointer();
  3454. I->copyInto(*this, AI);
  3455. } else {
  3456. // Skip the extra memcpy call.
  3457. auto *T = V->getType()->getPointerElementType()->getPointerTo(
  3458. CGM.getDataLayout().getAllocaAddrSpace());
  3459. IRCallArgs[FirstIRArg] = getTargetHooks().performAddrSpaceCast(
  3460. *this, V, LangAS::Default, CGM.getASTAllocaAddressSpace(), T,
  3461. true);
  3462. }
  3463. }
  3464. break;
  3465. }
  3466. case ABIArgInfo::Ignore:
  3467. assert(NumIRArgs == 0);
  3468. break;
  3469. case ABIArgInfo::Extend:
  3470. case ABIArgInfo::Direct: {
  3471. if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
  3472. ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
  3473. ArgInfo.getDirectOffset() == 0) {
  3474. assert(NumIRArgs == 1);
  3475. llvm::Value *V;
  3476. if (!I->isAggregate())
  3477. V = I->getKnownRValue().getScalarVal();
  3478. else
  3479. V = Builder.CreateLoad(
  3480. I->hasLValue() ? I->getKnownLValue().getAddress()
  3481. : I->getKnownRValue().getAggregateAddress());
  3482. // Implement swifterror by copying into a new swifterror argument.
  3483. // We'll write back in the normal path out of the call.
  3484. if (CallInfo.getExtParameterInfo(ArgNo).getABI()
  3485. == ParameterABI::SwiftErrorResult) {
  3486. assert(!swiftErrorTemp.isValid() && "multiple swifterror args");
  3487. QualType pointeeTy = I->Ty->getPointeeType();
  3488. swiftErrorArg =
  3489. Address(V, getContext().getTypeAlignInChars(pointeeTy));
  3490. swiftErrorTemp =
  3491. CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
  3492. V = swiftErrorTemp.getPointer();
  3493. cast<llvm::AllocaInst>(V)->setSwiftError(true);
  3494. llvm::Value *errorValue = Builder.CreateLoad(swiftErrorArg);
  3495. Builder.CreateStore(errorValue, swiftErrorTemp);
  3496. }
  3497. // We might have to widen integers, but we should never truncate.
  3498. if (ArgInfo.getCoerceToType() != V->getType() &&
  3499. V->getType()->isIntegerTy())
  3500. V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
  3501. // If the argument doesn't match, perform a bitcast to coerce it. This
  3502. // can happen due to trivial type mismatches.
  3503. if (FirstIRArg < IRFuncTy->getNumParams() &&
  3504. V->getType() != IRFuncTy->getParamType(FirstIRArg))
  3505. V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
  3506. IRCallArgs[FirstIRArg] = V;
  3507. break;
  3508. }
  3509. // FIXME: Avoid the conversion through memory if possible.
  3510. Address Src = Address::invalid();
  3511. if (!I->isAggregate()) {
  3512. Src = CreateMemTemp(I->Ty, "coerce");
  3513. I->copyInto(*this, Src);
  3514. } else {
  3515. Src = I->hasLValue() ? I->getKnownLValue().getAddress()
  3516. : I->getKnownRValue().getAggregateAddress();
  3517. }
  3518. // If the value is offset in memory, apply the offset now.
  3519. Src = emitAddressAtOffset(*this, Src, ArgInfo);
  3520. // Fast-isel and the optimizer generally like scalar values better than
  3521. // FCAs, so we flatten them if this is safe to do for this argument.
  3522. llvm::StructType *STy =
  3523. dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
  3524. if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
  3525. llvm::Type *SrcTy = Src.getType()->getElementType();
  3526. uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
  3527. uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
  3528. // If the source type is smaller than the destination type of the
  3529. // coerce-to logic, copy the source value into a temp alloca the size
  3530. // of the destination type to allow loading all of it. The bits past
  3531. // the source value are left undef.
  3532. if (SrcSize < DstSize) {
  3533. Address TempAlloca
  3534. = CreateTempAlloca(STy, Src.getAlignment(),
  3535. Src.getName() + ".coerce");
  3536. Builder.CreateMemCpy(TempAlloca, Src, SrcSize);
  3537. Src = TempAlloca;
  3538. } else {
  3539. Src = Builder.CreateBitCast(Src,
  3540. STy->getPointerTo(Src.getAddressSpace()));
  3541. }
  3542. assert(NumIRArgs == STy->getNumElements());
  3543. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
  3544. Address EltPtr = Builder.CreateStructGEP(Src, i);
  3545. llvm::Value *LI = Builder.CreateLoad(EltPtr);
  3546. IRCallArgs[FirstIRArg + i] = LI;
  3547. }
  3548. } else {
  3549. // In the simple case, just pass the coerced loaded value.
  3550. assert(NumIRArgs == 1);
  3551. IRCallArgs[FirstIRArg] =
  3552. CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this);
  3553. }
  3554. break;
  3555. }
  3556. case ABIArgInfo::CoerceAndExpand: {
  3557. auto coercionType = ArgInfo.getCoerceAndExpandType();
  3558. auto layout = CGM.getDataLayout().getStructLayout(coercionType);
  3559. llvm::Value *tempSize = nullptr;
  3560. Address addr = Address::invalid();
  3561. Address AllocaAddr = Address::invalid();
  3562. if (I->isAggregate()) {
  3563. addr = I->hasLValue() ? I->getKnownLValue().getAddress()
  3564. : I->getKnownRValue().getAggregateAddress();
  3565. } else {
  3566. RValue RV = I->getKnownRValue();
  3567. assert(RV.isScalar()); // complex should always just be direct
  3568. llvm::Type *scalarType = RV.getScalarVal()->getType();
  3569. auto scalarSize = CGM.getDataLayout().getTypeAllocSize(scalarType);
  3570. auto scalarAlign = CGM.getDataLayout().getPrefTypeAlignment(scalarType);
  3571. // Materialize to a temporary.
  3572. addr = CreateTempAlloca(RV.getScalarVal()->getType(),
  3573. CharUnits::fromQuantity(std::max(
  3574. layout->getAlignment(), scalarAlign)),
  3575. "tmp",
  3576. /*ArraySize=*/nullptr, &AllocaAddr);
  3577. tempSize = EmitLifetimeStart(scalarSize, AllocaAddr.getPointer());
  3578. Builder.CreateStore(RV.getScalarVal(), addr);
  3579. }
  3580. addr = Builder.CreateElementBitCast(addr, coercionType);
  3581. unsigned IRArgPos = FirstIRArg;
  3582. for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
  3583. llvm::Type *eltType = coercionType->getElementType(i);
  3584. if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
  3585. Address eltAddr = Builder.CreateStructGEP(addr, i);
  3586. llvm::Value *elt = Builder.CreateLoad(eltAddr);
  3587. IRCallArgs[IRArgPos++] = elt;
  3588. }
  3589. assert(IRArgPos == FirstIRArg + NumIRArgs);
  3590. if (tempSize) {
  3591. EmitLifetimeEnd(tempSize, AllocaAddr.getPointer());
  3592. }
  3593. break;
  3594. }
  3595. case ABIArgInfo::Expand:
  3596. unsigned IRArgPos = FirstIRArg;
  3597. ExpandTypeToArgs(I->Ty, *I, IRFuncTy, IRCallArgs, IRArgPos);
  3598. assert(IRArgPos == FirstIRArg + NumIRArgs);
  3599. break;
  3600. }
  3601. }
  3602. const CGCallee &ConcreteCallee = Callee.prepareConcreteCallee(*this);
  3603. llvm::Value *CalleePtr = ConcreteCallee.getFunctionPointer();
  3604. // If we're using inalloca, set up that argument.
  3605. if (ArgMemory.isValid()) {
  3606. llvm::Value *Arg = ArgMemory.getPointer();
  3607. if (CallInfo.isVariadic()) {
  3608. // When passing non-POD arguments by value to variadic functions, we will
  3609. // end up with a variadic prototype and an inalloca call site. In such
  3610. // cases, we can't do any parameter mismatch checks. Give up and bitcast
  3611. // the callee.
  3612. unsigned CalleeAS = CalleePtr->getType()->getPointerAddressSpace();
  3613. CalleePtr =
  3614. Builder.CreateBitCast(CalleePtr, IRFuncTy->getPointerTo(CalleeAS));
  3615. } else {
  3616. llvm::Type *LastParamTy =
  3617. IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
  3618. if (Arg->getType() != LastParamTy) {
  3619. #ifndef NDEBUG
  3620. // Assert that these structs have equivalent element types.
  3621. llvm::StructType *FullTy = CallInfo.getArgStruct();
  3622. llvm::StructType *DeclaredTy = cast<llvm::StructType>(
  3623. cast<llvm::PointerType>(LastParamTy)->getElementType());
  3624. assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
  3625. for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
  3626. DE = DeclaredTy->element_end(),
  3627. FI = FullTy->element_begin();
  3628. DI != DE; ++DI, ++FI)
  3629. assert(*DI == *FI);
  3630. #endif
  3631. Arg = Builder.CreateBitCast(Arg, LastParamTy);
  3632. }
  3633. }
  3634. assert(IRFunctionArgs.hasInallocaArg());
  3635. IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
  3636. }
  3637. // 2. Prepare the function pointer.
  3638. // If the callee is a bitcast of a non-variadic function to have a
  3639. // variadic function pointer type, check to see if we can remove the
  3640. // bitcast. This comes up with unprototyped functions.
  3641. //
  3642. // This makes the IR nicer, but more importantly it ensures that we
  3643. // can inline the function at -O0 if it is marked always_inline.
  3644. auto simplifyVariadicCallee = [](llvm::FunctionType *CalleeFT,
  3645. llvm::Value *Ptr) -> llvm::Function * {
  3646. if (!CalleeFT->isVarArg())
  3647. return nullptr;
  3648. // Get underlying value if it's a bitcast
  3649. if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Ptr)) {
  3650. if (CE->getOpcode() == llvm::Instruction::BitCast)
  3651. Ptr = CE->getOperand(0);
  3652. }
  3653. llvm::Function *OrigFn = dyn_cast<llvm::Function>(Ptr);
  3654. if (!OrigFn)
  3655. return nullptr;
  3656. llvm::FunctionType *OrigFT = OrigFn->getFunctionType();
  3657. // If the original type is variadic, or if any of the component types
  3658. // disagree, we cannot remove the cast.
  3659. if (OrigFT->isVarArg() ||
  3660. OrigFT->getNumParams() != CalleeFT->getNumParams() ||
  3661. OrigFT->getReturnType() != CalleeFT->getReturnType())
  3662. return nullptr;
  3663. for (unsigned i = 0, e = OrigFT->getNumParams(); i != e; ++i)
  3664. if (OrigFT->getParamType(i) != CalleeFT->getParamType(i))
  3665. return nullptr;
  3666. return OrigFn;
  3667. };
  3668. if (llvm::Function *OrigFn = simplifyVariadicCallee(IRFuncTy, CalleePtr)) {
  3669. CalleePtr = OrigFn;
  3670. IRFuncTy = OrigFn->getFunctionType();
  3671. }
  3672. // 3. Perform the actual call.
  3673. // Deactivate any cleanups that we're supposed to do immediately before
  3674. // the call.
  3675. if (!CallArgs.getCleanupsToDeactivate().empty())
  3676. deactivateArgCleanupsBeforeCall(*this, CallArgs);
  3677. // Assert that the arguments we computed match up. The IR verifier
  3678. // will catch this, but this is a common enough source of problems
  3679. // during IRGen changes that it's way better for debugging to catch
  3680. // it ourselves here.
  3681. #ifndef NDEBUG
  3682. assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
  3683. for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
  3684. // Inalloca argument can have different type.
  3685. if (IRFunctionArgs.hasInallocaArg() &&
  3686. i == IRFunctionArgs.getInallocaArgNo())
  3687. continue;
  3688. if (i < IRFuncTy->getNumParams())
  3689. assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
  3690. }
  3691. #endif
  3692. // Update the largest vector width if any arguments have vector types.
  3693. for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
  3694. if (auto *VT = dyn_cast<llvm::VectorType>(IRCallArgs[i]->getType()))
  3695. LargestVectorWidth = std::max(LargestVectorWidth,
  3696. VT->getPrimitiveSizeInBits());
  3697. }
  3698. // Compute the calling convention and attributes.
  3699. unsigned CallingConv;
  3700. llvm::AttributeList Attrs;
  3701. CGM.ConstructAttributeList(CalleePtr->getName(), CallInfo,
  3702. Callee.getAbstractInfo(), Attrs, CallingConv,
  3703. /*AttrOnCallSite=*/true);
  3704. // Apply some call-site-specific attributes.
  3705. // TODO: work this into building the attribute set.
  3706. // Apply always_inline to all calls within flatten functions.
  3707. // FIXME: should this really take priority over __try, below?
  3708. if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
  3709. !(TargetDecl && TargetDecl->hasAttr<NoInlineAttr>())) {
  3710. Attrs =
  3711. Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
  3712. llvm::Attribute::AlwaysInline);
  3713. }
  3714. // Disable inlining inside SEH __try blocks.
  3715. if (isSEHTryScope()) {
  3716. Attrs =
  3717. Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
  3718. llvm::Attribute::NoInline);
  3719. }
  3720. // Decide whether to use a call or an invoke.
  3721. bool CannotThrow;
  3722. if (currentFunctionUsesSEHTry()) {
  3723. // SEH cares about asynchronous exceptions, so everything can "throw."
  3724. CannotThrow = false;
  3725. } else if (isCleanupPadScope() &&
  3726. EHPersonality::get(*this).isMSVCXXPersonality()) {
  3727. // The MSVC++ personality will implicitly terminate the program if an
  3728. // exception is thrown during a cleanup outside of a try/catch.
  3729. // We don't need to model anything in IR to get this behavior.
  3730. CannotThrow = true;
  3731. } else {
  3732. // Otherwise, nounwind call sites will never throw.
  3733. CannotThrow = Attrs.hasAttribute(llvm::AttributeList::FunctionIndex,
  3734. llvm::Attribute::NoUnwind);
  3735. }
  3736. // If we made a temporary, be sure to clean up after ourselves. Note that we
  3737. // can't depend on being inside of an ExprWithCleanups, so we need to manually
  3738. // pop this cleanup later on. Being eager about this is OK, since this
  3739. // temporary is 'invisible' outside of the callee.
  3740. if (UnusedReturnSizePtr)
  3741. pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, SRetAlloca,
  3742. UnusedReturnSizePtr);
  3743. llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest();
  3744. SmallVector<llvm::OperandBundleDef, 1> BundleList =
  3745. getBundlesForFunclet(CalleePtr);
  3746. // Emit the actual call/invoke instruction.
  3747. llvm::CallBase *CI;
  3748. if (!InvokeDest) {
  3749. CI = Builder.CreateCall(IRFuncTy, CalleePtr, IRCallArgs, BundleList);
  3750. } else {
  3751. llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
  3752. CI = Builder.CreateInvoke(IRFuncTy, CalleePtr, Cont, InvokeDest, IRCallArgs,
  3753. BundleList);
  3754. EmitBlock(Cont);
  3755. }
  3756. if (callOrInvoke)
  3757. *callOrInvoke = CI;
  3758. // Apply the attributes and calling convention.
  3759. CI->setAttributes(Attrs);
  3760. CI->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
  3761. // Apply various metadata.
  3762. if (!CI->getType()->isVoidTy())
  3763. CI->setName("call");
  3764. // Update largest vector width from the return type.
  3765. if (auto *VT = dyn_cast<llvm::VectorType>(CI->getType()))
  3766. LargestVectorWidth = std::max(LargestVectorWidth,
  3767. VT->getPrimitiveSizeInBits());
  3768. // Insert instrumentation or attach profile metadata at indirect call sites.
  3769. // For more details, see the comment before the definition of
  3770. // IPVK_IndirectCallTarget in InstrProfData.inc.
  3771. if (!CI->getCalledFunction())
  3772. PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget,
  3773. CI, CalleePtr);
  3774. // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
  3775. // optimizer it can aggressively ignore unwind edges.
  3776. if (CGM.getLangOpts().ObjCAutoRefCount)
  3777. AddObjCARCExceptionMetadata(CI);
  3778. // Suppress tail calls if requested.
  3779. if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) {
  3780. if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>())
  3781. Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
  3782. }
  3783. // Add metadata for calls to MSAllocator functions
  3784. if (getDebugInfo() && TargetDecl &&
  3785. TargetDecl->hasAttr<MSAllocatorAttr>())
  3786. getDebugInfo()->addHeapAllocSiteMetadata(CI, RetTy, Loc);
  3787. // 4. Finish the call.
  3788. // If the call doesn't return, finish the basic block and clear the
  3789. // insertion point; this allows the rest of IRGen to discard
  3790. // unreachable code.
  3791. if (CI->doesNotReturn()) {
  3792. if (UnusedReturnSizePtr)
  3793. PopCleanupBlock();
  3794. // Strip away the noreturn attribute to better diagnose unreachable UB.
  3795. if (SanOpts.has(SanitizerKind::Unreachable)) {
  3796. // Also remove from function since CallBase::hasFnAttr additionally checks
  3797. // attributes of the called function.
  3798. if (auto *F = CI->getCalledFunction())
  3799. F->removeFnAttr(llvm::Attribute::NoReturn);
  3800. CI->removeAttribute(llvm::AttributeList::FunctionIndex,
  3801. llvm::Attribute::NoReturn);
  3802. // Avoid incompatibility with ASan which relies on the `noreturn`
  3803. // attribute to insert handler calls.
  3804. if (SanOpts.hasOneOf(SanitizerKind::Address |
  3805. SanitizerKind::KernelAddress)) {
  3806. SanitizerScope SanScope(this);
  3807. llvm::IRBuilder<>::InsertPointGuard IPGuard(Builder);
  3808. Builder.SetInsertPoint(CI);
  3809. auto *FnType = llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
  3810. llvm::FunctionCallee Fn =
  3811. CGM.CreateRuntimeFunction(FnType, "__asan_handle_no_return");
  3812. EmitNounwindRuntimeCall(Fn);
  3813. }
  3814. }
  3815. EmitUnreachable(Loc);
  3816. Builder.ClearInsertionPoint();
  3817. // FIXME: For now, emit a dummy basic block because expr emitters in
  3818. // generally are not ready to handle emitting expressions at unreachable
  3819. // points.
  3820. EnsureInsertPoint();
  3821. // Return a reasonable RValue.
  3822. return GetUndefRValue(RetTy);
  3823. }
  3824. // Perform the swifterror writeback.
  3825. if (swiftErrorTemp.isValid()) {
  3826. llvm::Value *errorResult = Builder.CreateLoad(swiftErrorTemp);
  3827. Builder.CreateStore(errorResult, swiftErrorArg);
  3828. }
  3829. // Emit any call-associated writebacks immediately. Arguably this
  3830. // should happen after any return-value munging.
  3831. if (CallArgs.hasWritebacks())
  3832. emitWritebacks(*this, CallArgs);
  3833. // The stack cleanup for inalloca arguments has to run out of the normal
  3834. // lexical order, so deactivate it and run it manually here.
  3835. CallArgs.freeArgumentMemory(*this);
  3836. // Extract the return value.
  3837. RValue Ret = [&] {
  3838. switch (RetAI.getKind()) {
  3839. case ABIArgInfo::CoerceAndExpand: {
  3840. auto coercionType = RetAI.getCoerceAndExpandType();
  3841. Address addr = SRetPtr;
  3842. addr = Builder.CreateElementBitCast(addr, coercionType);
  3843. assert(CI->getType() == RetAI.getUnpaddedCoerceAndExpandType());
  3844. bool requiresExtract = isa<llvm::StructType>(CI->getType());
  3845. unsigned unpaddedIndex = 0;
  3846. for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
  3847. llvm::Type *eltType = coercionType->getElementType(i);
  3848. if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
  3849. Address eltAddr = Builder.CreateStructGEP(addr, i);
  3850. llvm::Value *elt = CI;
  3851. if (requiresExtract)
  3852. elt = Builder.CreateExtractValue(elt, unpaddedIndex++);
  3853. else
  3854. assert(unpaddedIndex == 0);
  3855. Builder.CreateStore(elt, eltAddr);
  3856. }
  3857. // FALLTHROUGH
  3858. LLVM_FALLTHROUGH;
  3859. }
  3860. case ABIArgInfo::InAlloca:
  3861. case ABIArgInfo::Indirect: {
  3862. RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
  3863. if (UnusedReturnSizePtr)
  3864. PopCleanupBlock();
  3865. return ret;
  3866. }
  3867. case ABIArgInfo::Ignore:
  3868. // If we are ignoring an argument that had a result, make sure to
  3869. // construct the appropriate return value for our caller.
  3870. return GetUndefRValue(RetTy);
  3871. case ABIArgInfo::Extend:
  3872. case ABIArgInfo::Direct: {
  3873. llvm::Type *RetIRTy = ConvertType(RetTy);
  3874. if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
  3875. switch (getEvaluationKind(RetTy)) {
  3876. case TEK_Complex: {
  3877. llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
  3878. llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
  3879. return RValue::getComplex(std::make_pair(Real, Imag));
  3880. }
  3881. case TEK_Aggregate: {
  3882. Address DestPtr = ReturnValue.getValue();
  3883. bool DestIsVolatile = ReturnValue.isVolatile();
  3884. if (!DestPtr.isValid()) {
  3885. DestPtr = CreateMemTemp(RetTy, "agg.tmp");
  3886. DestIsVolatile = false;
  3887. }
  3888. BuildAggStore(*this, CI, DestPtr, DestIsVolatile);
  3889. return RValue::getAggregate(DestPtr);
  3890. }
  3891. case TEK_Scalar: {
  3892. // If the argument doesn't match, perform a bitcast to coerce it. This
  3893. // can happen due to trivial type mismatches.
  3894. llvm::Value *V = CI;
  3895. if (V->getType() != RetIRTy)
  3896. V = Builder.CreateBitCast(V, RetIRTy);
  3897. return RValue::get(V);
  3898. }
  3899. }
  3900. llvm_unreachable("bad evaluation kind");
  3901. }
  3902. Address DestPtr = ReturnValue.getValue();
  3903. bool DestIsVolatile = ReturnValue.isVolatile();
  3904. if (!DestPtr.isValid()) {
  3905. DestPtr = CreateMemTemp(RetTy, "coerce");
  3906. DestIsVolatile = false;
  3907. }
  3908. // If the value is offset in memory, apply the offset now.
  3909. Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI);
  3910. CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
  3911. return convertTempToRValue(DestPtr, RetTy, SourceLocation());
  3912. }
  3913. case ABIArgInfo::Expand:
  3914. llvm_unreachable("Invalid ABI kind for return argument");
  3915. }
  3916. llvm_unreachable("Unhandled ABIArgInfo::Kind");
  3917. } ();
  3918. // Emit the assume_aligned check on the return value.
  3919. if (Ret.isScalar() && TargetDecl) {
  3920. if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) {
  3921. llvm::Value *OffsetValue = nullptr;
  3922. if (const auto *Offset = AA->getOffset())
  3923. OffsetValue = EmitScalarExpr(Offset);
  3924. llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment());
  3925. llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment);
  3926. EmitAlignmentAssumption(Ret.getScalarVal(), RetTy, Loc, AA->getLocation(),
  3927. AlignmentCI->getZExtValue(), OffsetValue);
  3928. } else if (const auto *AA = TargetDecl->getAttr<AllocAlignAttr>()) {
  3929. llvm::Value *AlignmentVal = CallArgs[AA->getParamIndex().getLLVMIndex()]
  3930. .getRValue(*this)
  3931. .getScalarVal();
  3932. EmitAlignmentAssumption(Ret.getScalarVal(), RetTy, Loc, AA->getLocation(),
  3933. AlignmentVal);
  3934. }
  3935. }
  3936. return Ret;
  3937. }
  3938. CGCallee CGCallee::prepareConcreteCallee(CodeGenFunction &CGF) const {
  3939. if (isVirtual()) {
  3940. const CallExpr *CE = getVirtualCallExpr();
  3941. return CGF.CGM.getCXXABI().getVirtualFunctionPointer(
  3942. CGF, getVirtualMethodDecl(), getThisAddress(), getVirtualFunctionType(),
  3943. CE ? CE->getBeginLoc() : SourceLocation());
  3944. }
  3945. return *this;
  3946. }
  3947. /* VarArg handling */
  3948. Address CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr) {
  3949. VAListAddr = VE->isMicrosoftABI()
  3950. ? EmitMSVAListRef(VE->getSubExpr())
  3951. : EmitVAListRef(VE->getSubExpr());
  3952. QualType Ty = VE->getType();
  3953. if (VE->isMicrosoftABI())
  3954. return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty);
  3955. return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty);
  3956. }