CodeGenFunction.h 148 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517
  1. //===-- CodeGenFunction.h - Per-Function state for LLVM CodeGen -*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This is the internal per-function state used for llvm translation.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H
  14. #define LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H
  15. #include "CGBuilder.h"
  16. #include "CGDebugInfo.h"
  17. #include "CGLoopInfo.h"
  18. #include "CGValue.h"
  19. #include "CodeGenModule.h"
  20. #include "CodeGenPGO.h"
  21. #include "EHScopeStack.h"
  22. #include "clang/AST/CharUnits.h"
  23. #include "clang/AST/ExprCXX.h"
  24. #include "clang/AST/ExprObjC.h"
  25. #include "clang/AST/ExprOpenMP.h"
  26. #include "clang/AST/Type.h"
  27. #include "clang/Basic/ABI.h"
  28. #include "clang/Basic/CapturedStmt.h"
  29. #include "clang/Basic/OpenMPKinds.h"
  30. #include "clang/Basic/TargetInfo.h"
  31. #include "clang/Frontend/CodeGenOptions.h"
  32. #include "llvm/ADT/ArrayRef.h"
  33. #include "llvm/ADT/DenseMap.h"
  34. #include "llvm/ADT/SmallVector.h"
  35. #include "llvm/IR/ValueHandle.h"
  36. #include "llvm/Support/Debug.h"
  37. #include "llvm/Transforms/Utils/SanitizerStats.h"
  38. namespace llvm {
  39. class BasicBlock;
  40. class LLVMContext;
  41. class MDNode;
  42. class Module;
  43. class SwitchInst;
  44. class Twine;
  45. class Value;
  46. class CallSite;
  47. }
  48. namespace clang {
  49. class ASTContext;
  50. class BlockDecl;
  51. class CXXDestructorDecl;
  52. class CXXForRangeStmt;
  53. class CXXTryStmt;
  54. class Decl;
  55. class LabelDecl;
  56. class EnumConstantDecl;
  57. class FunctionDecl;
  58. class FunctionProtoType;
  59. class LabelStmt;
  60. class ObjCContainerDecl;
  61. class ObjCInterfaceDecl;
  62. class ObjCIvarDecl;
  63. class ObjCMethodDecl;
  64. class ObjCImplementationDecl;
  65. class ObjCPropertyImplDecl;
  66. class TargetInfo;
  67. class VarDecl;
  68. class ObjCForCollectionStmt;
  69. class ObjCAtTryStmt;
  70. class ObjCAtThrowStmt;
  71. class ObjCAtSynchronizedStmt;
  72. class ObjCAutoreleasePoolStmt;
  73. namespace CodeGen {
  74. class CodeGenTypes;
  75. class CGFunctionInfo;
  76. class CGRecordLayout;
  77. class CGBlockInfo;
  78. class CGCXXABI;
  79. class BlockByrefHelpers;
  80. class BlockByrefInfo;
  81. class BlockFlags;
  82. class BlockFieldFlags;
  83. class RegionCodeGenTy;
  84. class TargetCodeGenInfo;
  85. struct OMPTaskDataTy;
  86. /// The kind of evaluation to perform on values of a particular
  87. /// type. Basically, is the code in CGExprScalar, CGExprComplex, or
  88. /// CGExprAgg?
  89. ///
  90. /// TODO: should vectors maybe be split out into their own thing?
  91. enum TypeEvaluationKind {
  92. TEK_Scalar,
  93. TEK_Complex,
  94. TEK_Aggregate
  95. };
  96. /// CodeGenFunction - This class organizes the per-function state that is used
  97. /// while generating LLVM code.
  98. class CodeGenFunction : public CodeGenTypeCache {
  99. CodeGenFunction(const CodeGenFunction &) = delete;
  100. void operator=(const CodeGenFunction &) = delete;
  101. friend class CGCXXABI;
  102. public:
  103. /// A jump destination is an abstract label, branching to which may
  104. /// require a jump out through normal cleanups.
  105. struct JumpDest {
  106. JumpDest() : Block(nullptr), ScopeDepth(), Index(0) {}
  107. JumpDest(llvm::BasicBlock *Block,
  108. EHScopeStack::stable_iterator Depth,
  109. unsigned Index)
  110. : Block(Block), ScopeDepth(Depth), Index(Index) {}
  111. bool isValid() const { return Block != nullptr; }
  112. llvm::BasicBlock *getBlock() const { return Block; }
  113. EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
  114. unsigned getDestIndex() const { return Index; }
  115. // This should be used cautiously.
  116. void setScopeDepth(EHScopeStack::stable_iterator depth) {
  117. ScopeDepth = depth;
  118. }
  119. private:
  120. llvm::BasicBlock *Block;
  121. EHScopeStack::stable_iterator ScopeDepth;
  122. unsigned Index;
  123. };
  124. CodeGenModule &CGM; // Per-module state.
  125. const TargetInfo &Target;
  126. typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
  127. LoopInfoStack LoopStack;
  128. CGBuilderTy Builder;
  129. /// \brief CGBuilder insert helper. This function is called after an
  130. /// instruction is created using Builder.
  131. void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name,
  132. llvm::BasicBlock *BB,
  133. llvm::BasicBlock::iterator InsertPt) const;
  134. /// CurFuncDecl - Holds the Decl for the current outermost
  135. /// non-closure context.
  136. const Decl *CurFuncDecl;
  137. /// CurCodeDecl - This is the inner-most code context, which includes blocks.
  138. const Decl *CurCodeDecl;
  139. const CGFunctionInfo *CurFnInfo;
  140. QualType FnRetTy;
  141. llvm::Function *CurFn;
  142. /// CurGD - The GlobalDecl for the current function being compiled.
  143. GlobalDecl CurGD;
  144. /// PrologueCleanupDepth - The cleanup depth enclosing all the
  145. /// cleanups associated with the parameters.
  146. EHScopeStack::stable_iterator PrologueCleanupDepth;
  147. /// ReturnBlock - Unified return block.
  148. JumpDest ReturnBlock;
  149. /// ReturnValue - The temporary alloca to hold the return
  150. /// value. This is invalid iff the function has no return value.
  151. Address ReturnValue;
  152. /// AllocaInsertPoint - This is an instruction in the entry block before which
  153. /// we prefer to insert allocas.
  154. llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
  155. /// \brief API for captured statement code generation.
  156. class CGCapturedStmtInfo {
  157. public:
  158. explicit CGCapturedStmtInfo(CapturedRegionKind K = CR_Default)
  159. : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {}
  160. explicit CGCapturedStmtInfo(const CapturedStmt &S,
  161. CapturedRegionKind K = CR_Default)
  162. : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {
  163. RecordDecl::field_iterator Field =
  164. S.getCapturedRecordDecl()->field_begin();
  165. for (CapturedStmt::const_capture_iterator I = S.capture_begin(),
  166. E = S.capture_end();
  167. I != E; ++I, ++Field) {
  168. if (I->capturesThis())
  169. CXXThisFieldDecl = *Field;
  170. else if (I->capturesVariable())
  171. CaptureFields[I->getCapturedVar()] = *Field;
  172. else if (I->capturesVariableByCopy())
  173. CaptureFields[I->getCapturedVar()] = *Field;
  174. }
  175. }
  176. virtual ~CGCapturedStmtInfo();
  177. CapturedRegionKind getKind() const { return Kind; }
  178. virtual void setContextValue(llvm::Value *V) { ThisValue = V; }
  179. // \brief Retrieve the value of the context parameter.
  180. virtual llvm::Value *getContextValue() const { return ThisValue; }
  181. /// \brief Lookup the captured field decl for a variable.
  182. virtual const FieldDecl *lookup(const VarDecl *VD) const {
  183. return CaptureFields.lookup(VD);
  184. }
  185. bool isCXXThisExprCaptured() const { return getThisFieldDecl() != nullptr; }
  186. virtual FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; }
  187. static bool classof(const CGCapturedStmtInfo *) {
  188. return true;
  189. }
  190. /// \brief Emit the captured statement body.
  191. virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) {
  192. CGF.incrementProfileCounter(S);
  193. CGF.EmitStmt(S);
  194. }
  195. /// \brief Get the name of the capture helper.
  196. virtual StringRef getHelperName() const { return "__captured_stmt"; }
  197. private:
  198. /// \brief The kind of captured statement being generated.
  199. CapturedRegionKind Kind;
  200. /// \brief Keep the map between VarDecl and FieldDecl.
  201. llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields;
  202. /// \brief The base address of the captured record, passed in as the first
  203. /// argument of the parallel region function.
  204. llvm::Value *ThisValue;
  205. /// \brief Captured 'this' type.
  206. FieldDecl *CXXThisFieldDecl;
  207. };
  208. CGCapturedStmtInfo *CapturedStmtInfo;
  209. /// \brief RAII for correct setting/restoring of CapturedStmtInfo.
  210. class CGCapturedStmtRAII {
  211. private:
  212. CodeGenFunction &CGF;
  213. CGCapturedStmtInfo *PrevCapturedStmtInfo;
  214. public:
  215. CGCapturedStmtRAII(CodeGenFunction &CGF,
  216. CGCapturedStmtInfo *NewCapturedStmtInfo)
  217. : CGF(CGF), PrevCapturedStmtInfo(CGF.CapturedStmtInfo) {
  218. CGF.CapturedStmtInfo = NewCapturedStmtInfo;
  219. }
  220. ~CGCapturedStmtRAII() { CGF.CapturedStmtInfo = PrevCapturedStmtInfo; }
  221. };
  222. /// \brief Sanitizers enabled for this function.
  223. SanitizerSet SanOpts;
  224. /// \brief True if CodeGen currently emits code implementing sanitizer checks.
  225. bool IsSanitizerScope;
  226. /// \brief RAII object to set/unset CodeGenFunction::IsSanitizerScope.
  227. class SanitizerScope {
  228. CodeGenFunction *CGF;
  229. public:
  230. SanitizerScope(CodeGenFunction *CGF);
  231. ~SanitizerScope();
  232. };
  233. /// In C++, whether we are code generating a thunk. This controls whether we
  234. /// should emit cleanups.
  235. bool CurFuncIsThunk;
  236. /// In ARC, whether we should autorelease the return value.
  237. bool AutoreleaseResult;
  238. /// Whether we processed a Microsoft-style asm block during CodeGen. These can
  239. /// potentially set the return value.
  240. bool SawAsmBlock;
  241. const FunctionDecl *CurSEHParent = nullptr;
  242. /// True if the current function is an outlined SEH helper. This can be a
  243. /// finally block or filter expression.
  244. bool IsOutlinedSEHHelper;
  245. const CodeGen::CGBlockInfo *BlockInfo;
  246. llvm::Value *BlockPointer;
  247. llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
  248. FieldDecl *LambdaThisCaptureField;
  249. /// \brief A mapping from NRVO variables to the flags used to indicate
  250. /// when the NRVO has been applied to this variable.
  251. llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
  252. EHScopeStack EHStack;
  253. llvm::SmallVector<char, 256> LifetimeExtendedCleanupStack;
  254. llvm::SmallVector<const JumpDest *, 2> SEHTryEpilogueStack;
  255. llvm::Instruction *CurrentFuncletPad = nullptr;
  256. class CallLifetimeEnd final : public EHScopeStack::Cleanup {
  257. llvm::Value *Addr;
  258. llvm::Value *Size;
  259. public:
  260. CallLifetimeEnd(Address addr, llvm::Value *size)
  261. : Addr(addr.getPointer()), Size(size) {}
  262. void Emit(CodeGenFunction &CGF, Flags flags) override {
  263. CGF.EmitLifetimeEnd(Size, Addr);
  264. }
  265. };
  266. /// Header for data within LifetimeExtendedCleanupStack.
  267. struct LifetimeExtendedCleanupHeader {
  268. /// The size of the following cleanup object.
  269. unsigned Size;
  270. /// The kind of cleanup to push: a value from the CleanupKind enumeration.
  271. CleanupKind Kind;
  272. size_t getSize() const { return Size; }
  273. CleanupKind getKind() const { return Kind; }
  274. };
  275. /// i32s containing the indexes of the cleanup destinations.
  276. llvm::AllocaInst *NormalCleanupDest;
  277. unsigned NextCleanupDestIndex;
  278. /// FirstBlockInfo - The head of a singly-linked-list of block layouts.
  279. CGBlockInfo *FirstBlockInfo;
  280. /// EHResumeBlock - Unified block containing a call to llvm.eh.resume.
  281. llvm::BasicBlock *EHResumeBlock;
  282. /// The exception slot. All landing pads write the current exception pointer
  283. /// into this alloca.
  284. llvm::Value *ExceptionSlot;
  285. /// The selector slot. Under the MandatoryCleanup model, all landing pads
  286. /// write the current selector value into this alloca.
  287. llvm::AllocaInst *EHSelectorSlot;
  288. /// A stack of exception code slots. Entering an __except block pushes a slot
  289. /// on the stack and leaving pops one. The __exception_code() intrinsic loads
  290. /// a value from the top of the stack.
  291. SmallVector<Address, 1> SEHCodeSlotStack;
  292. /// Value returned by __exception_info intrinsic.
  293. llvm::Value *SEHInfo = nullptr;
  294. /// Emits a landing pad for the current EH stack.
  295. llvm::BasicBlock *EmitLandingPad();
  296. llvm::BasicBlock *getInvokeDestImpl();
  297. template <class T>
  298. typename DominatingValue<T>::saved_type saveValueInCond(T value) {
  299. return DominatingValue<T>::save(*this, value);
  300. }
  301. public:
  302. /// ObjCEHValueStack - Stack of Objective-C exception values, used for
  303. /// rethrows.
  304. SmallVector<llvm::Value*, 8> ObjCEHValueStack;
  305. /// A class controlling the emission of a finally block.
  306. class FinallyInfo {
  307. /// Where the catchall's edge through the cleanup should go.
  308. JumpDest RethrowDest;
  309. /// A function to call to enter the catch.
  310. llvm::Constant *BeginCatchFn;
  311. /// An i1 variable indicating whether or not the @finally is
  312. /// running for an exception.
  313. llvm::AllocaInst *ForEHVar;
  314. /// An i8* variable into which the exception pointer to rethrow
  315. /// has been saved.
  316. llvm::AllocaInst *SavedExnVar;
  317. public:
  318. void enter(CodeGenFunction &CGF, const Stmt *Finally,
  319. llvm::Constant *beginCatchFn, llvm::Constant *endCatchFn,
  320. llvm::Constant *rethrowFn);
  321. void exit(CodeGenFunction &CGF);
  322. };
  323. /// Returns true inside SEH __try blocks.
  324. bool isSEHTryScope() const { return !SEHTryEpilogueStack.empty(); }
  325. /// Returns true while emitting a cleanuppad.
  326. bool isCleanupPadScope() const {
  327. return CurrentFuncletPad && isa<llvm::CleanupPadInst>(CurrentFuncletPad);
  328. }
  329. /// pushFullExprCleanup - Push a cleanup to be run at the end of the
  330. /// current full-expression. Safe against the possibility that
  331. /// we're currently inside a conditionally-evaluated expression.
  332. template <class T, class... As>
  333. void pushFullExprCleanup(CleanupKind kind, As... A) {
  334. // If we're not in a conditional branch, or if none of the
  335. // arguments requires saving, then use the unconditional cleanup.
  336. if (!isInConditionalBranch())
  337. return EHStack.pushCleanup<T>(kind, A...);
  338. // Stash values in a tuple so we can guarantee the order of saves.
  339. typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple;
  340. SavedTuple Saved{saveValueInCond(A)...};
  341. typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType;
  342. EHStack.pushCleanupTuple<CleanupType>(kind, Saved);
  343. initFullExprCleanup();
  344. }
  345. /// \brief Queue a cleanup to be pushed after finishing the current
  346. /// full-expression.
  347. template <class T, class... As>
  348. void pushCleanupAfterFullExpr(CleanupKind Kind, As... A) {
  349. assert(!isInConditionalBranch() && "can't defer conditional cleanup");
  350. LifetimeExtendedCleanupHeader Header = { sizeof(T), Kind };
  351. size_t OldSize = LifetimeExtendedCleanupStack.size();
  352. LifetimeExtendedCleanupStack.resize(
  353. LifetimeExtendedCleanupStack.size() + sizeof(Header) + Header.Size);
  354. static_assert(sizeof(Header) % llvm::AlignOf<T>::Alignment == 0,
  355. "Cleanup will be allocated on misaligned address");
  356. char *Buffer = &LifetimeExtendedCleanupStack[OldSize];
  357. new (Buffer) LifetimeExtendedCleanupHeader(Header);
  358. new (Buffer + sizeof(Header)) T(A...);
  359. }
  360. /// Set up the last cleaup that was pushed as a conditional
  361. /// full-expression cleanup.
  362. void initFullExprCleanup();
  363. /// PushDestructorCleanup - Push a cleanup to call the
  364. /// complete-object destructor of an object of the given type at the
  365. /// given address. Does nothing if T is not a C++ class type with a
  366. /// non-trivial destructor.
  367. void PushDestructorCleanup(QualType T, Address Addr);
  368. /// PushDestructorCleanup - Push a cleanup to call the
  369. /// complete-object variant of the given destructor on the object at
  370. /// the given address.
  371. void PushDestructorCleanup(const CXXDestructorDecl *Dtor, Address Addr);
  372. /// PopCleanupBlock - Will pop the cleanup entry on the stack and
  373. /// process all branch fixups.
  374. void PopCleanupBlock(bool FallThroughIsBranchThrough = false);
  375. /// DeactivateCleanupBlock - Deactivates the given cleanup block.
  376. /// The block cannot be reactivated. Pops it if it's the top of the
  377. /// stack.
  378. ///
  379. /// \param DominatingIP - An instruction which is known to
  380. /// dominate the current IP (if set) and which lies along
  381. /// all paths of execution between the current IP and the
  382. /// the point at which the cleanup comes into scope.
  383. void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
  384. llvm::Instruction *DominatingIP);
  385. /// ActivateCleanupBlock - Activates an initially-inactive cleanup.
  386. /// Cannot be used to resurrect a deactivated cleanup.
  387. ///
  388. /// \param DominatingIP - An instruction which is known to
  389. /// dominate the current IP (if set) and which lies along
  390. /// all paths of execution between the current IP and the
  391. /// the point at which the cleanup comes into scope.
  392. void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
  393. llvm::Instruction *DominatingIP);
  394. /// \brief Enters a new scope for capturing cleanups, all of which
  395. /// will be executed once the scope is exited.
  396. class RunCleanupsScope {
  397. EHScopeStack::stable_iterator CleanupStackDepth;
  398. size_t LifetimeExtendedCleanupStackSize;
  399. bool OldDidCallStackSave;
  400. protected:
  401. bool PerformCleanup;
  402. private:
  403. RunCleanupsScope(const RunCleanupsScope &) = delete;
  404. void operator=(const RunCleanupsScope &) = delete;
  405. protected:
  406. CodeGenFunction& CGF;
  407. public:
  408. /// \brief Enter a new cleanup scope.
  409. explicit RunCleanupsScope(CodeGenFunction &CGF)
  410. : PerformCleanup(true), CGF(CGF)
  411. {
  412. CleanupStackDepth = CGF.EHStack.stable_begin();
  413. LifetimeExtendedCleanupStackSize =
  414. CGF.LifetimeExtendedCleanupStack.size();
  415. OldDidCallStackSave = CGF.DidCallStackSave;
  416. CGF.DidCallStackSave = false;
  417. }
  418. /// \brief Exit this cleanup scope, emitting any accumulated
  419. /// cleanups.
  420. ~RunCleanupsScope() {
  421. if (PerformCleanup) {
  422. CGF.DidCallStackSave = OldDidCallStackSave;
  423. CGF.PopCleanupBlocks(CleanupStackDepth,
  424. LifetimeExtendedCleanupStackSize);
  425. }
  426. }
  427. /// \brief Determine whether this scope requires any cleanups.
  428. bool requiresCleanups() const {
  429. return CGF.EHStack.stable_begin() != CleanupStackDepth;
  430. }
  431. /// \brief Force the emission of cleanups now, instead of waiting
  432. /// until this object is destroyed.
  433. void ForceCleanup() {
  434. assert(PerformCleanup && "Already forced cleanup");
  435. CGF.DidCallStackSave = OldDidCallStackSave;
  436. CGF.PopCleanupBlocks(CleanupStackDepth,
  437. LifetimeExtendedCleanupStackSize);
  438. PerformCleanup = false;
  439. }
  440. };
  441. class LexicalScope : public RunCleanupsScope {
  442. SourceRange Range;
  443. SmallVector<const LabelDecl*, 4> Labels;
  444. LexicalScope *ParentScope;
  445. LexicalScope(const LexicalScope &) = delete;
  446. void operator=(const LexicalScope &) = delete;
  447. public:
  448. /// \brief Enter a new cleanup scope.
  449. explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range)
  450. : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) {
  451. CGF.CurLexicalScope = this;
  452. if (CGDebugInfo *DI = CGF.getDebugInfo())
  453. DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin());
  454. }
  455. void addLabel(const LabelDecl *label) {
  456. assert(PerformCleanup && "adding label to dead scope?");
  457. Labels.push_back(label);
  458. }
  459. /// \brief Exit this cleanup scope, emitting any accumulated
  460. /// cleanups.
  461. ~LexicalScope() {
  462. if (CGDebugInfo *DI = CGF.getDebugInfo())
  463. DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd());
  464. // If we should perform a cleanup, force them now. Note that
  465. // this ends the cleanup scope before rescoping any labels.
  466. if (PerformCleanup) {
  467. ApplyDebugLocation DL(CGF, Range.getEnd());
  468. ForceCleanup();
  469. }
  470. }
  471. /// \brief Force the emission of cleanups now, instead of waiting
  472. /// until this object is destroyed.
  473. void ForceCleanup() {
  474. CGF.CurLexicalScope = ParentScope;
  475. RunCleanupsScope::ForceCleanup();
  476. if (!Labels.empty())
  477. rescopeLabels();
  478. }
  479. void rescopeLabels();
  480. };
  481. typedef llvm::DenseMap<const Decl *, Address> DeclMapTy;
  482. /// \brief The scope used to remap some variables as private in the OpenMP
  483. /// loop body (or other captured region emitted without outlining), and to
  484. /// restore old vars back on exit.
  485. class OMPPrivateScope : public RunCleanupsScope {
  486. DeclMapTy SavedLocals;
  487. DeclMapTy SavedPrivates;
  488. private:
  489. OMPPrivateScope(const OMPPrivateScope &) = delete;
  490. void operator=(const OMPPrivateScope &) = delete;
  491. public:
  492. /// \brief Enter a new OpenMP private scope.
  493. explicit OMPPrivateScope(CodeGenFunction &CGF) : RunCleanupsScope(CGF) {}
  494. /// \brief Registers \a LocalVD variable as a private and apply \a
  495. /// PrivateGen function for it to generate corresponding private variable.
  496. /// \a PrivateGen returns an address of the generated private variable.
  497. /// \return true if the variable is registered as private, false if it has
  498. /// been privatized already.
  499. bool
  500. addPrivate(const VarDecl *LocalVD,
  501. llvm::function_ref<Address()> PrivateGen) {
  502. assert(PerformCleanup && "adding private to dead scope");
  503. // Only save it once.
  504. if (SavedLocals.count(LocalVD)) return false;
  505. // Copy the existing local entry to SavedLocals.
  506. auto it = CGF.LocalDeclMap.find(LocalVD);
  507. if (it != CGF.LocalDeclMap.end()) {
  508. SavedLocals.insert({LocalVD, it->second});
  509. } else {
  510. SavedLocals.insert({LocalVD, Address::invalid()});
  511. }
  512. // Generate the private entry.
  513. Address Addr = PrivateGen();
  514. QualType VarTy = LocalVD->getType();
  515. if (VarTy->isReferenceType()) {
  516. Address Temp = CGF.CreateMemTemp(VarTy);
  517. CGF.Builder.CreateStore(Addr.getPointer(), Temp);
  518. Addr = Temp;
  519. }
  520. SavedPrivates.insert({LocalVD, Addr});
  521. return true;
  522. }
  523. /// \brief Privatizes local variables previously registered as private.
  524. /// Registration is separate from the actual privatization to allow
  525. /// initializers use values of the original variables, not the private one.
  526. /// This is important, for example, if the private variable is a class
  527. /// variable initialized by a constructor that references other private
  528. /// variables. But at initialization original variables must be used, not
  529. /// private copies.
  530. /// \return true if at least one variable was privatized, false otherwise.
  531. bool Privatize() {
  532. copyInto(SavedPrivates, CGF.LocalDeclMap);
  533. SavedPrivates.clear();
  534. return !SavedLocals.empty();
  535. }
  536. void ForceCleanup() {
  537. RunCleanupsScope::ForceCleanup();
  538. copyInto(SavedLocals, CGF.LocalDeclMap);
  539. SavedLocals.clear();
  540. }
  541. /// \brief Exit scope - all the mapped variables are restored.
  542. ~OMPPrivateScope() {
  543. if (PerformCleanup)
  544. ForceCleanup();
  545. }
  546. /// Checks if the global variable is captured in current function.
  547. bool isGlobalVarCaptured(const VarDecl *VD) const {
  548. return !VD->isLocalVarDeclOrParm() && CGF.LocalDeclMap.count(VD) > 0;
  549. }
  550. private:
  551. /// Copy all the entries in the source map over the corresponding
  552. /// entries in the destination, which must exist.
  553. static void copyInto(const DeclMapTy &src, DeclMapTy &dest) {
  554. for (auto &pair : src) {
  555. if (!pair.second.isValid()) {
  556. dest.erase(pair.first);
  557. continue;
  558. }
  559. auto it = dest.find(pair.first);
  560. if (it != dest.end()) {
  561. it->second = pair.second;
  562. } else {
  563. dest.insert(pair);
  564. }
  565. }
  566. }
  567. };
  568. /// \brief Takes the old cleanup stack size and emits the cleanup blocks
  569. /// that have been added.
  570. void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize);
  571. /// \brief Takes the old cleanup stack size and emits the cleanup blocks
  572. /// that have been added, then adds all lifetime-extended cleanups from
  573. /// the given position to the stack.
  574. void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
  575. size_t OldLifetimeExtendedStackSize);
  576. void ResolveBranchFixups(llvm::BasicBlock *Target);
  577. /// The given basic block lies in the current EH scope, but may be a
  578. /// target of a potentially scope-crossing jump; get a stable handle
  579. /// to which we can perform this jump later.
  580. JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) {
  581. return JumpDest(Target,
  582. EHStack.getInnermostNormalCleanup(),
  583. NextCleanupDestIndex++);
  584. }
  585. /// The given basic block lies in the current EH scope, but may be a
  586. /// target of a potentially scope-crossing jump; get a stable handle
  587. /// to which we can perform this jump later.
  588. JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) {
  589. return getJumpDestInCurrentScope(createBasicBlock(Name));
  590. }
  591. /// EmitBranchThroughCleanup - Emit a branch from the current insert
  592. /// block through the normal cleanup handling code (if any) and then
  593. /// on to \arg Dest.
  594. void EmitBranchThroughCleanup(JumpDest Dest);
  595. /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
  596. /// specified destination obviously has no cleanups to run. 'false' is always
  597. /// a conservatively correct answer for this method.
  598. bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const;
  599. /// popCatchScope - Pops the catch scope at the top of the EHScope
  600. /// stack, emitting any required code (other than the catch handlers
  601. /// themselves).
  602. void popCatchScope();
  603. llvm::BasicBlock *getEHResumeBlock(bool isCleanup);
  604. llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope);
  605. llvm::BasicBlock *getMSVCDispatchBlock(EHScopeStack::stable_iterator scope);
  606. /// An object to manage conditionally-evaluated expressions.
  607. class ConditionalEvaluation {
  608. llvm::BasicBlock *StartBB;
  609. public:
  610. ConditionalEvaluation(CodeGenFunction &CGF)
  611. : StartBB(CGF.Builder.GetInsertBlock()) {}
  612. void begin(CodeGenFunction &CGF) {
  613. assert(CGF.OutermostConditional != this);
  614. if (!CGF.OutermostConditional)
  615. CGF.OutermostConditional = this;
  616. }
  617. void end(CodeGenFunction &CGF) {
  618. assert(CGF.OutermostConditional != nullptr);
  619. if (CGF.OutermostConditional == this)
  620. CGF.OutermostConditional = nullptr;
  621. }
  622. /// Returns a block which will be executed prior to each
  623. /// evaluation of the conditional code.
  624. llvm::BasicBlock *getStartingBlock() const {
  625. return StartBB;
  626. }
  627. };
  628. /// isInConditionalBranch - Return true if we're currently emitting
  629. /// one branch or the other of a conditional expression.
  630. bool isInConditionalBranch() const { return OutermostConditional != nullptr; }
  631. void setBeforeOutermostConditional(llvm::Value *value, Address addr) {
  632. assert(isInConditionalBranch());
  633. llvm::BasicBlock *block = OutermostConditional->getStartingBlock();
  634. auto store = new llvm::StoreInst(value, addr.getPointer(), &block->back());
  635. store->setAlignment(addr.getAlignment().getQuantity());
  636. }
  637. /// An RAII object to record that we're evaluating a statement
  638. /// expression.
  639. class StmtExprEvaluation {
  640. CodeGenFunction &CGF;
  641. /// We have to save the outermost conditional: cleanups in a
  642. /// statement expression aren't conditional just because the
  643. /// StmtExpr is.
  644. ConditionalEvaluation *SavedOutermostConditional;
  645. public:
  646. StmtExprEvaluation(CodeGenFunction &CGF)
  647. : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) {
  648. CGF.OutermostConditional = nullptr;
  649. }
  650. ~StmtExprEvaluation() {
  651. CGF.OutermostConditional = SavedOutermostConditional;
  652. CGF.EnsureInsertPoint();
  653. }
  654. };
  655. /// An object which temporarily prevents a value from being
  656. /// destroyed by aggressive peephole optimizations that assume that
  657. /// all uses of a value have been realized in the IR.
  658. class PeepholeProtection {
  659. llvm::Instruction *Inst;
  660. friend class CodeGenFunction;
  661. public:
  662. PeepholeProtection() : Inst(nullptr) {}
  663. };
  664. /// A non-RAII class containing all the information about a bound
  665. /// opaque value. OpaqueValueMapping, below, is a RAII wrapper for
  666. /// this which makes individual mappings very simple; using this
  667. /// class directly is useful when you have a variable number of
  668. /// opaque values or don't want the RAII functionality for some
  669. /// reason.
  670. class OpaqueValueMappingData {
  671. const OpaqueValueExpr *OpaqueValue;
  672. bool BoundLValue;
  673. CodeGenFunction::PeepholeProtection Protection;
  674. OpaqueValueMappingData(const OpaqueValueExpr *ov,
  675. bool boundLValue)
  676. : OpaqueValue(ov), BoundLValue(boundLValue) {}
  677. public:
  678. OpaqueValueMappingData() : OpaqueValue(nullptr) {}
  679. static bool shouldBindAsLValue(const Expr *expr) {
  680. // gl-values should be bound as l-values for obvious reasons.
  681. // Records should be bound as l-values because IR generation
  682. // always keeps them in memory. Expressions of function type
  683. // act exactly like l-values but are formally required to be
  684. // r-values in C.
  685. return expr->isGLValue() ||
  686. expr->getType()->isFunctionType() ||
  687. hasAggregateEvaluationKind(expr->getType());
  688. }
  689. static OpaqueValueMappingData bind(CodeGenFunction &CGF,
  690. const OpaqueValueExpr *ov,
  691. const Expr *e) {
  692. if (shouldBindAsLValue(ov))
  693. return bind(CGF, ov, CGF.EmitLValue(e));
  694. return bind(CGF, ov, CGF.EmitAnyExpr(e));
  695. }
  696. static OpaqueValueMappingData bind(CodeGenFunction &CGF,
  697. const OpaqueValueExpr *ov,
  698. const LValue &lv) {
  699. assert(shouldBindAsLValue(ov));
  700. CGF.OpaqueLValues.insert(std::make_pair(ov, lv));
  701. return OpaqueValueMappingData(ov, true);
  702. }
  703. static OpaqueValueMappingData bind(CodeGenFunction &CGF,
  704. const OpaqueValueExpr *ov,
  705. const RValue &rv) {
  706. assert(!shouldBindAsLValue(ov));
  707. CGF.OpaqueRValues.insert(std::make_pair(ov, rv));
  708. OpaqueValueMappingData data(ov, false);
  709. // Work around an extremely aggressive peephole optimization in
  710. // EmitScalarConversion which assumes that all other uses of a
  711. // value are extant.
  712. data.Protection = CGF.protectFromPeepholes(rv);
  713. return data;
  714. }
  715. bool isValid() const { return OpaqueValue != nullptr; }
  716. void clear() { OpaqueValue = nullptr; }
  717. void unbind(CodeGenFunction &CGF) {
  718. assert(OpaqueValue && "no data to unbind!");
  719. if (BoundLValue) {
  720. CGF.OpaqueLValues.erase(OpaqueValue);
  721. } else {
  722. CGF.OpaqueRValues.erase(OpaqueValue);
  723. CGF.unprotectFromPeepholes(Protection);
  724. }
  725. }
  726. };
  727. /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
  728. class OpaqueValueMapping {
  729. CodeGenFunction &CGF;
  730. OpaqueValueMappingData Data;
  731. public:
  732. static bool shouldBindAsLValue(const Expr *expr) {
  733. return OpaqueValueMappingData::shouldBindAsLValue(expr);
  734. }
  735. /// Build the opaque value mapping for the given conditional
  736. /// operator if it's the GNU ?: extension. This is a common
  737. /// enough pattern that the convenience operator is really
  738. /// helpful.
  739. ///
  740. OpaqueValueMapping(CodeGenFunction &CGF,
  741. const AbstractConditionalOperator *op) : CGF(CGF) {
  742. if (isa<ConditionalOperator>(op))
  743. // Leave Data empty.
  744. return;
  745. const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op);
  746. Data = OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(),
  747. e->getCommon());
  748. }
  749. OpaqueValueMapping(CodeGenFunction &CGF,
  750. const OpaqueValueExpr *opaqueValue,
  751. LValue lvalue)
  752. : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) {
  753. }
  754. OpaqueValueMapping(CodeGenFunction &CGF,
  755. const OpaqueValueExpr *opaqueValue,
  756. RValue rvalue)
  757. : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) {
  758. }
  759. void pop() {
  760. Data.unbind(CGF);
  761. Data.clear();
  762. }
  763. ~OpaqueValueMapping() {
  764. if (Data.isValid()) Data.unbind(CGF);
  765. }
  766. };
  767. private:
  768. CGDebugInfo *DebugInfo;
  769. bool DisableDebugInfo;
  770. /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
  771. /// calling llvm.stacksave for multiple VLAs in the same scope.
  772. bool DidCallStackSave;
  773. /// IndirectBranch - The first time an indirect goto is seen we create a block
  774. /// with an indirect branch. Every time we see the address of a label taken,
  775. /// we add the label to the indirect goto. Every subsequent indirect goto is
  776. /// codegen'd as a jump to the IndirectBranch's basic block.
  777. llvm::IndirectBrInst *IndirectBranch;
  778. /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
  779. /// decls.
  780. DeclMapTy LocalDeclMap;
  781. /// SizeArguments - If a ParmVarDecl had the pass_object_size attribute, this
  782. /// will contain a mapping from said ParmVarDecl to its implicit "object_size"
  783. /// parameter.
  784. llvm::SmallDenseMap<const ParmVarDecl *, const ImplicitParamDecl *, 2>
  785. SizeArguments;
  786. /// Track escaped local variables with auto storage. Used during SEH
  787. /// outlining to produce a call to llvm.localescape.
  788. llvm::DenseMap<llvm::AllocaInst *, int> EscapedLocals;
  789. /// LabelMap - This keeps track of the LLVM basic block for each C label.
  790. llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap;
  791. // BreakContinueStack - This keeps track of where break and continue
  792. // statements should jump to.
  793. struct BreakContinue {
  794. BreakContinue(JumpDest Break, JumpDest Continue)
  795. : BreakBlock(Break), ContinueBlock(Continue) {}
  796. JumpDest BreakBlock;
  797. JumpDest ContinueBlock;
  798. };
  799. SmallVector<BreakContinue, 8> BreakContinueStack;
  800. CodeGenPGO PGO;
  801. /// Calculate branch weights appropriate for PGO data
  802. llvm::MDNode *createProfileWeights(uint64_t TrueCount, uint64_t FalseCount);
  803. llvm::MDNode *createProfileWeights(ArrayRef<uint64_t> Weights);
  804. llvm::MDNode *createProfileWeightsForLoop(const Stmt *Cond,
  805. uint64_t LoopCount);
  806. public:
  807. /// Increment the profiler's counter for the given statement.
  808. void incrementProfileCounter(const Stmt *S) {
  809. if (CGM.getCodeGenOpts().hasProfileClangInstr())
  810. PGO.emitCounterIncrement(Builder, S);
  811. PGO.setCurrentStmt(S);
  812. }
  813. /// Get the profiler's count for the given statement.
  814. uint64_t getProfileCount(const Stmt *S) {
  815. Optional<uint64_t> Count = PGO.getStmtCount(S);
  816. if (!Count.hasValue())
  817. return 0;
  818. return *Count;
  819. }
  820. /// Set the profiler's current count.
  821. void setCurrentProfileCount(uint64_t Count) {
  822. PGO.setCurrentRegionCount(Count);
  823. }
  824. /// Get the profiler's current count. This is generally the count for the most
  825. /// recently incremented counter.
  826. uint64_t getCurrentProfileCount() {
  827. return PGO.getCurrentRegionCount();
  828. }
  829. private:
  830. /// SwitchInsn - This is nearest current switch instruction. It is null if
  831. /// current context is not in a switch.
  832. llvm::SwitchInst *SwitchInsn;
  833. /// The branch weights of SwitchInsn when doing instrumentation based PGO.
  834. SmallVector<uint64_t, 16> *SwitchWeights;
  835. /// CaseRangeBlock - This block holds if condition check for last case
  836. /// statement range in current switch instruction.
  837. llvm::BasicBlock *CaseRangeBlock;
  838. /// OpaqueLValues - Keeps track of the current set of opaque value
  839. /// expressions.
  840. llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues;
  841. llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues;
  842. // VLASizeMap - This keeps track of the associated size for each VLA type.
  843. // We track this by the size expression rather than the type itself because
  844. // in certain situations, like a const qualifier applied to an VLA typedef,
  845. // multiple VLA types can share the same size expression.
  846. // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
  847. // enter/leave scopes.
  848. llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
  849. /// A block containing a single 'unreachable' instruction. Created
  850. /// lazily by getUnreachableBlock().
  851. llvm::BasicBlock *UnreachableBlock;
  852. /// Counts of the number return expressions in the function.
  853. unsigned NumReturnExprs;
  854. /// Count the number of simple (constant) return expressions in the function.
  855. unsigned NumSimpleReturnExprs;
  856. /// The last regular (non-return) debug location (breakpoint) in the function.
  857. SourceLocation LastStopPoint;
  858. public:
  859. /// A scope within which we are constructing the fields of an object which
  860. /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use
  861. /// if we need to evaluate a CXXDefaultInitExpr within the evaluation.
  862. class FieldConstructionScope {
  863. public:
  864. FieldConstructionScope(CodeGenFunction &CGF, Address This)
  865. : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) {
  866. CGF.CXXDefaultInitExprThis = This;
  867. }
  868. ~FieldConstructionScope() {
  869. CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis;
  870. }
  871. private:
  872. CodeGenFunction &CGF;
  873. Address OldCXXDefaultInitExprThis;
  874. };
  875. /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this'
  876. /// is overridden to be the object under construction.
  877. class CXXDefaultInitExprScope {
  878. public:
  879. CXXDefaultInitExprScope(CodeGenFunction &CGF)
  880. : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue),
  881. OldCXXThisAlignment(CGF.CXXThisAlignment) {
  882. CGF.CXXThisValue = CGF.CXXDefaultInitExprThis.getPointer();
  883. CGF.CXXThisAlignment = CGF.CXXDefaultInitExprThis.getAlignment();
  884. }
  885. ~CXXDefaultInitExprScope() {
  886. CGF.CXXThisValue = OldCXXThisValue;
  887. CGF.CXXThisAlignment = OldCXXThisAlignment;
  888. }
  889. public:
  890. CodeGenFunction &CGF;
  891. llvm::Value *OldCXXThisValue;
  892. CharUnits OldCXXThisAlignment;
  893. };
  894. class InlinedInheritingConstructorScope {
  895. public:
  896. InlinedInheritingConstructorScope(CodeGenFunction &CGF, GlobalDecl GD)
  897. : CGF(CGF), OldCurGD(CGF.CurGD), OldCurFuncDecl(CGF.CurFuncDecl),
  898. OldCurCodeDecl(CGF.CurCodeDecl),
  899. OldCXXABIThisDecl(CGF.CXXABIThisDecl),
  900. OldCXXABIThisValue(CGF.CXXABIThisValue),
  901. OldCXXThisValue(CGF.CXXThisValue),
  902. OldCXXABIThisAlignment(CGF.CXXABIThisAlignment),
  903. OldCXXThisAlignment(CGF.CXXThisAlignment),
  904. OldReturnValue(CGF.ReturnValue), OldFnRetTy(CGF.FnRetTy),
  905. OldCXXInheritedCtorInitExprArgs(
  906. std::move(CGF.CXXInheritedCtorInitExprArgs)) {
  907. CGF.CurGD = GD;
  908. CGF.CurFuncDecl = CGF.CurCodeDecl =
  909. cast<CXXConstructorDecl>(GD.getDecl());
  910. CGF.CXXABIThisDecl = nullptr;
  911. CGF.CXXABIThisValue = nullptr;
  912. CGF.CXXThisValue = nullptr;
  913. CGF.CXXABIThisAlignment = CharUnits();
  914. CGF.CXXThisAlignment = CharUnits();
  915. CGF.ReturnValue = Address::invalid();
  916. CGF.FnRetTy = QualType();
  917. CGF.CXXInheritedCtorInitExprArgs.clear();
  918. }
  919. ~InlinedInheritingConstructorScope() {
  920. CGF.CurGD = OldCurGD;
  921. CGF.CurFuncDecl = OldCurFuncDecl;
  922. CGF.CurCodeDecl = OldCurCodeDecl;
  923. CGF.CXXABIThisDecl = OldCXXABIThisDecl;
  924. CGF.CXXABIThisValue = OldCXXABIThisValue;
  925. CGF.CXXThisValue = OldCXXThisValue;
  926. CGF.CXXABIThisAlignment = OldCXXABIThisAlignment;
  927. CGF.CXXThisAlignment = OldCXXThisAlignment;
  928. CGF.ReturnValue = OldReturnValue;
  929. CGF.FnRetTy = OldFnRetTy;
  930. CGF.CXXInheritedCtorInitExprArgs =
  931. std::move(OldCXXInheritedCtorInitExprArgs);
  932. }
  933. private:
  934. CodeGenFunction &CGF;
  935. GlobalDecl OldCurGD;
  936. const Decl *OldCurFuncDecl;
  937. const Decl *OldCurCodeDecl;
  938. ImplicitParamDecl *OldCXXABIThisDecl;
  939. llvm::Value *OldCXXABIThisValue;
  940. llvm::Value *OldCXXThisValue;
  941. CharUnits OldCXXABIThisAlignment;
  942. CharUnits OldCXXThisAlignment;
  943. Address OldReturnValue;
  944. QualType OldFnRetTy;
  945. CallArgList OldCXXInheritedCtorInitExprArgs;
  946. };
  947. private:
  948. /// CXXThisDecl - When generating code for a C++ member function,
  949. /// this will hold the implicit 'this' declaration.
  950. ImplicitParamDecl *CXXABIThisDecl;
  951. llvm::Value *CXXABIThisValue;
  952. llvm::Value *CXXThisValue;
  953. CharUnits CXXABIThisAlignment;
  954. CharUnits CXXThisAlignment;
  955. /// The value of 'this' to use when evaluating CXXDefaultInitExprs within
  956. /// this expression.
  957. Address CXXDefaultInitExprThis = Address::invalid();
  958. /// The values of function arguments to use when evaluating
  959. /// CXXInheritedCtorInitExprs within this context.
  960. CallArgList CXXInheritedCtorInitExprArgs;
  961. /// CXXStructorImplicitParamDecl - When generating code for a constructor or
  962. /// destructor, this will hold the implicit argument (e.g. VTT).
  963. ImplicitParamDecl *CXXStructorImplicitParamDecl;
  964. llvm::Value *CXXStructorImplicitParamValue;
  965. /// OutermostConditional - Points to the outermost active
  966. /// conditional control. This is used so that we know if a
  967. /// temporary should be destroyed conditionally.
  968. ConditionalEvaluation *OutermostConditional;
  969. /// The current lexical scope.
  970. LexicalScope *CurLexicalScope;
  971. /// The current source location that should be used for exception
  972. /// handling code.
  973. SourceLocation CurEHLocation;
  974. /// BlockByrefInfos - For each __block variable, contains
  975. /// information about the layout of the variable.
  976. llvm::DenseMap<const ValueDecl *, BlockByrefInfo> BlockByrefInfos;
  977. llvm::BasicBlock *TerminateLandingPad;
  978. llvm::BasicBlock *TerminateHandler;
  979. llvm::BasicBlock *TrapBB;
  980. /// Add a kernel metadata node to the named metadata node 'opencl.kernels'.
  981. /// In the kernel metadata node, reference the kernel function and metadata
  982. /// nodes for its optional attribute qualifiers (OpenCL 1.1 6.7.2):
  983. /// - A node for the vec_type_hint(<type>) qualifier contains string
  984. /// "vec_type_hint", an undefined value of the <type> data type,
  985. /// and a Boolean that is true if the <type> is integer and signed.
  986. /// - A node for the work_group_size_hint(X,Y,Z) qualifier contains string
  987. /// "work_group_size_hint", and three 32-bit integers X, Y and Z.
  988. /// - A node for the reqd_work_group_size(X,Y,Z) qualifier contains string
  989. /// "reqd_work_group_size", and three 32-bit integers X, Y and Z.
  990. void EmitOpenCLKernelMetadata(const FunctionDecl *FD,
  991. llvm::Function *Fn);
  992. public:
  993. CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false);
  994. ~CodeGenFunction();
  995. CodeGenTypes &getTypes() const { return CGM.getTypes(); }
  996. ASTContext &getContext() const { return CGM.getContext(); }
  997. CGDebugInfo *getDebugInfo() {
  998. if (DisableDebugInfo)
  999. return nullptr;
  1000. return DebugInfo;
  1001. }
  1002. void disableDebugInfo() { DisableDebugInfo = true; }
  1003. void enableDebugInfo() { DisableDebugInfo = false; }
  1004. bool shouldUseFusedARCCalls() {
  1005. return CGM.getCodeGenOpts().OptimizationLevel == 0;
  1006. }
  1007. const LangOptions &getLangOpts() const { return CGM.getLangOpts(); }
  1008. /// Returns a pointer to the function's exception object and selector slot,
  1009. /// which is assigned in every landing pad.
  1010. Address getExceptionSlot();
  1011. Address getEHSelectorSlot();
  1012. /// Returns the contents of the function's exception object and selector
  1013. /// slots.
  1014. llvm::Value *getExceptionFromSlot();
  1015. llvm::Value *getSelectorFromSlot();
  1016. Address getNormalCleanupDestSlot();
  1017. llvm::BasicBlock *getUnreachableBlock() {
  1018. if (!UnreachableBlock) {
  1019. UnreachableBlock = createBasicBlock("unreachable");
  1020. new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock);
  1021. }
  1022. return UnreachableBlock;
  1023. }
  1024. llvm::BasicBlock *getInvokeDest() {
  1025. if (!EHStack.requiresLandingPad()) return nullptr;
  1026. return getInvokeDestImpl();
  1027. }
  1028. bool currentFunctionUsesSEHTry() const { return CurSEHParent != nullptr; }
  1029. const TargetInfo &getTarget() const { return Target; }
  1030. llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); }
  1031. //===--------------------------------------------------------------------===//
  1032. // Cleanups
  1033. //===--------------------------------------------------------------------===//
  1034. typedef void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty);
  1035. void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
  1036. Address arrayEndPointer,
  1037. QualType elementType,
  1038. CharUnits elementAlignment,
  1039. Destroyer *destroyer);
  1040. void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
  1041. llvm::Value *arrayEnd,
  1042. QualType elementType,
  1043. CharUnits elementAlignment,
  1044. Destroyer *destroyer);
  1045. void pushDestroy(QualType::DestructionKind dtorKind,
  1046. Address addr, QualType type);
  1047. void pushEHDestroy(QualType::DestructionKind dtorKind,
  1048. Address addr, QualType type);
  1049. void pushDestroy(CleanupKind kind, Address addr, QualType type,
  1050. Destroyer *destroyer, bool useEHCleanupForArray);
  1051. void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr,
  1052. QualType type, Destroyer *destroyer,
  1053. bool useEHCleanupForArray);
  1054. void pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
  1055. llvm::Value *CompletePtr,
  1056. QualType ElementType);
  1057. void pushStackRestore(CleanupKind kind, Address SPMem);
  1058. void emitDestroy(Address addr, QualType type, Destroyer *destroyer,
  1059. bool useEHCleanupForArray);
  1060. llvm::Function *generateDestroyHelper(Address addr, QualType type,
  1061. Destroyer *destroyer,
  1062. bool useEHCleanupForArray,
  1063. const VarDecl *VD);
  1064. void emitArrayDestroy(llvm::Value *begin, llvm::Value *end,
  1065. QualType elementType, CharUnits elementAlign,
  1066. Destroyer *destroyer,
  1067. bool checkZeroLength, bool useEHCleanup);
  1068. Destroyer *getDestroyer(QualType::DestructionKind destructionKind);
  1069. /// Determines whether an EH cleanup is required to destroy a type
  1070. /// with the given destruction kind.
  1071. bool needsEHCleanup(QualType::DestructionKind kind) {
  1072. switch (kind) {
  1073. case QualType::DK_none:
  1074. return false;
  1075. case QualType::DK_cxx_destructor:
  1076. case QualType::DK_objc_weak_lifetime:
  1077. return getLangOpts().Exceptions;
  1078. case QualType::DK_objc_strong_lifetime:
  1079. return getLangOpts().Exceptions &&
  1080. CGM.getCodeGenOpts().ObjCAutoRefCountExceptions;
  1081. }
  1082. llvm_unreachable("bad destruction kind");
  1083. }
  1084. CleanupKind getCleanupKind(QualType::DestructionKind kind) {
  1085. return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup);
  1086. }
  1087. //===--------------------------------------------------------------------===//
  1088. // Objective-C
  1089. //===--------------------------------------------------------------------===//
  1090. void GenerateObjCMethod(const ObjCMethodDecl *OMD);
  1091. void StartObjCMethod(const ObjCMethodDecl *MD, const ObjCContainerDecl *CD);
  1092. /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
  1093. void GenerateObjCGetter(ObjCImplementationDecl *IMP,
  1094. const ObjCPropertyImplDecl *PID);
  1095. void generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
  1096. const ObjCPropertyImplDecl *propImpl,
  1097. const ObjCMethodDecl *GetterMothodDecl,
  1098. llvm::Constant *AtomicHelperFn);
  1099. void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
  1100. ObjCMethodDecl *MD, bool ctor);
  1101. /// GenerateObjCSetter - Synthesize an Objective-C property setter function
  1102. /// for the given property.
  1103. void GenerateObjCSetter(ObjCImplementationDecl *IMP,
  1104. const ObjCPropertyImplDecl *PID);
  1105. void generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
  1106. const ObjCPropertyImplDecl *propImpl,
  1107. llvm::Constant *AtomicHelperFn);
  1108. //===--------------------------------------------------------------------===//
  1109. // Block Bits
  1110. //===--------------------------------------------------------------------===//
  1111. llvm::Value *EmitBlockLiteral(const BlockExpr *);
  1112. llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info);
  1113. static void destroyBlockInfos(CGBlockInfo *info);
  1114. llvm::Function *GenerateBlockFunction(GlobalDecl GD,
  1115. const CGBlockInfo &Info,
  1116. const DeclMapTy &ldm,
  1117. bool IsLambdaConversionToBlock);
  1118. llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo);
  1119. llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo);
  1120. llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction(
  1121. const ObjCPropertyImplDecl *PID);
  1122. llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction(
  1123. const ObjCPropertyImplDecl *PID);
  1124. llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty);
  1125. void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags);
  1126. class AutoVarEmission;
  1127. void emitByrefStructureInit(const AutoVarEmission &emission);
  1128. void enterByrefCleanup(const AutoVarEmission &emission);
  1129. void setBlockContextParameter(const ImplicitParamDecl *D, unsigned argNum,
  1130. llvm::Value *ptr);
  1131. Address LoadBlockStruct();
  1132. Address GetAddrOfBlockDecl(const VarDecl *var, bool ByRef);
  1133. /// BuildBlockByrefAddress - Computes the location of the
  1134. /// data in a variable which is declared as __block.
  1135. Address emitBlockByrefAddress(Address baseAddr, const VarDecl *V,
  1136. bool followForward = true);
  1137. Address emitBlockByrefAddress(Address baseAddr,
  1138. const BlockByrefInfo &info,
  1139. bool followForward,
  1140. const llvm::Twine &name);
  1141. const BlockByrefInfo &getBlockByrefInfo(const VarDecl *var);
  1142. QualType BuildFunctionArgList(GlobalDecl GD, FunctionArgList &Args);
  1143. void GenerateCode(GlobalDecl GD, llvm::Function *Fn,
  1144. const CGFunctionInfo &FnInfo);
  1145. /// \brief Emit code for the start of a function.
  1146. /// \param Loc The location to be associated with the function.
  1147. /// \param StartLoc The location of the function body.
  1148. void StartFunction(GlobalDecl GD,
  1149. QualType RetTy,
  1150. llvm::Function *Fn,
  1151. const CGFunctionInfo &FnInfo,
  1152. const FunctionArgList &Args,
  1153. SourceLocation Loc = SourceLocation(),
  1154. SourceLocation StartLoc = SourceLocation());
  1155. void EmitConstructorBody(FunctionArgList &Args);
  1156. void EmitDestructorBody(FunctionArgList &Args);
  1157. void emitImplicitAssignmentOperatorBody(FunctionArgList &Args);
  1158. void EmitFunctionBody(FunctionArgList &Args, const Stmt *Body);
  1159. void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S);
  1160. void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator,
  1161. CallArgList &CallArgs);
  1162. void EmitLambdaToBlockPointerBody(FunctionArgList &Args);
  1163. void EmitLambdaBlockInvokeBody();
  1164. void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD);
  1165. void EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD);
  1166. void EmitAsanPrologueOrEpilogue(bool Prologue);
  1167. /// \brief Emit the unified return block, trying to avoid its emission when
  1168. /// possible.
  1169. /// \return The debug location of the user written return statement if the
  1170. /// return block is is avoided.
  1171. llvm::DebugLoc EmitReturnBlock();
  1172. /// FinishFunction - Complete IR generation of the current function. It is
  1173. /// legal to call this function even if there is no current insertion point.
  1174. void FinishFunction(SourceLocation EndLoc=SourceLocation());
  1175. void StartThunk(llvm::Function *Fn, GlobalDecl GD,
  1176. const CGFunctionInfo &FnInfo);
  1177. void EmitCallAndReturnForThunk(llvm::Value *Callee, const ThunkInfo *Thunk);
  1178. void FinishThunk();
  1179. /// Emit a musttail call for a thunk with a potentially adjusted this pointer.
  1180. void EmitMustTailThunk(const CXXMethodDecl *MD, llvm::Value *AdjustedThisPtr,
  1181. llvm::Value *Callee);
  1182. /// Generate a thunk for the given method.
  1183. void generateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
  1184. GlobalDecl GD, const ThunkInfo &Thunk);
  1185. llvm::Function *GenerateVarArgsThunk(llvm::Function *Fn,
  1186. const CGFunctionInfo &FnInfo,
  1187. GlobalDecl GD, const ThunkInfo &Thunk);
  1188. void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
  1189. FunctionArgList &Args);
  1190. void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init,
  1191. ArrayRef<VarDecl *> ArrayIndexes);
  1192. /// Struct with all informations about dynamic [sub]class needed to set vptr.
  1193. struct VPtr {
  1194. BaseSubobject Base;
  1195. const CXXRecordDecl *NearestVBase;
  1196. CharUnits OffsetFromNearestVBase;
  1197. const CXXRecordDecl *VTableClass;
  1198. };
  1199. /// Initialize the vtable pointer of the given subobject.
  1200. void InitializeVTablePointer(const VPtr &vptr);
  1201. typedef llvm::SmallVector<VPtr, 4> VPtrsVector;
  1202. typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
  1203. VPtrsVector getVTablePointers(const CXXRecordDecl *VTableClass);
  1204. void getVTablePointers(BaseSubobject Base, const CXXRecordDecl *NearestVBase,
  1205. CharUnits OffsetFromNearestVBase,
  1206. bool BaseIsNonVirtualPrimaryBase,
  1207. const CXXRecordDecl *VTableClass,
  1208. VisitedVirtualBasesSetTy &VBases, VPtrsVector &vptrs);
  1209. void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
  1210. /// GetVTablePtr - Return the Value of the vtable pointer member pointed
  1211. /// to by This.
  1212. llvm::Value *GetVTablePtr(Address This, llvm::Type *VTableTy,
  1213. const CXXRecordDecl *VTableClass);
  1214. enum CFITypeCheckKind {
  1215. CFITCK_VCall,
  1216. CFITCK_NVCall,
  1217. CFITCK_DerivedCast,
  1218. CFITCK_UnrelatedCast,
  1219. CFITCK_ICall,
  1220. };
  1221. /// \brief Derived is the presumed address of an object of type T after a
  1222. /// cast. If T is a polymorphic class type, emit a check that the virtual
  1223. /// table for Derived belongs to a class derived from T.
  1224. void EmitVTablePtrCheckForCast(QualType T, llvm::Value *Derived,
  1225. bool MayBeNull, CFITypeCheckKind TCK,
  1226. SourceLocation Loc);
  1227. /// EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable.
  1228. /// If vptr CFI is enabled, emit a check that VTable is valid.
  1229. void EmitVTablePtrCheckForCall(const CXXRecordDecl *RD, llvm::Value *VTable,
  1230. CFITypeCheckKind TCK, SourceLocation Loc);
  1231. /// EmitVTablePtrCheck - Emit a check that VTable is a valid virtual table for
  1232. /// RD using llvm.type.test.
  1233. void EmitVTablePtrCheck(const CXXRecordDecl *RD, llvm::Value *VTable,
  1234. CFITypeCheckKind TCK, SourceLocation Loc);
  1235. /// If whole-program virtual table optimization is enabled, emit an assumption
  1236. /// that VTable is a member of RD's type identifier. Or, if vptr CFI is
  1237. /// enabled, emit a check that VTable is a member of RD's type identifier.
  1238. void EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
  1239. llvm::Value *VTable, SourceLocation Loc);
  1240. /// Returns whether we should perform a type checked load when loading a
  1241. /// virtual function for virtual calls to members of RD. This is generally
  1242. /// true when both vcall CFI and whole-program-vtables are enabled.
  1243. bool ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD);
  1244. /// Emit a type checked load from the given vtable.
  1245. llvm::Value *EmitVTableTypeCheckedLoad(const CXXRecordDecl *RD, llvm::Value *VTable,
  1246. uint64_t VTableByteOffset);
  1247. /// CanDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
  1248. /// expr can be devirtualized.
  1249. bool CanDevirtualizeMemberFunctionCall(const Expr *Base,
  1250. const CXXMethodDecl *MD);
  1251. /// EnterDtorCleanups - Enter the cleanups necessary to complete the
  1252. /// given phase of destruction for a destructor. The end result
  1253. /// should call destructors on members and base classes in reverse
  1254. /// order of their construction.
  1255. void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type);
  1256. /// ShouldInstrumentFunction - Return true if the current function should be
  1257. /// instrumented with __cyg_profile_func_* calls
  1258. bool ShouldInstrumentFunction();
  1259. /// ShouldXRayInstrument - Return true if the current function should be
  1260. /// instrumented with XRay nop sleds.
  1261. bool ShouldXRayInstrumentFunction() const;
  1262. /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
  1263. /// instrumentation function with the current function and the call site, if
  1264. /// function instrumentation is enabled.
  1265. void EmitFunctionInstrumentation(const char *Fn);
  1266. /// EmitMCountInstrumentation - Emit call to .mcount.
  1267. void EmitMCountInstrumentation();
  1268. /// EmitFunctionProlog - Emit the target specific LLVM code to load the
  1269. /// arguments for the given function. This is also responsible for naming the
  1270. /// LLVM function arguments.
  1271. void EmitFunctionProlog(const CGFunctionInfo &FI,
  1272. llvm::Function *Fn,
  1273. const FunctionArgList &Args);
  1274. /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
  1275. /// given temporary.
  1276. void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc,
  1277. SourceLocation EndLoc);
  1278. /// EmitStartEHSpec - Emit the start of the exception spec.
  1279. void EmitStartEHSpec(const Decl *D);
  1280. /// EmitEndEHSpec - Emit the end of the exception spec.
  1281. void EmitEndEHSpec(const Decl *D);
  1282. /// getTerminateLandingPad - Return a landing pad that just calls terminate.
  1283. llvm::BasicBlock *getTerminateLandingPad();
  1284. /// getTerminateHandler - Return a handler (not a landing pad, just
  1285. /// a catch handler) that just calls terminate. This is used when
  1286. /// a terminate scope encloses a try.
  1287. llvm::BasicBlock *getTerminateHandler();
  1288. llvm::Type *ConvertTypeForMem(QualType T);
  1289. llvm::Type *ConvertType(QualType T);
  1290. llvm::Type *ConvertType(const TypeDecl *T) {
  1291. return ConvertType(getContext().getTypeDeclType(T));
  1292. }
  1293. /// LoadObjCSelf - Load the value of self. This function is only valid while
  1294. /// generating code for an Objective-C method.
  1295. llvm::Value *LoadObjCSelf();
  1296. /// TypeOfSelfObject - Return type of object that this self represents.
  1297. QualType TypeOfSelfObject();
  1298. /// hasAggregateLLVMType - Return true if the specified AST type will map into
  1299. /// an aggregate LLVM type or is void.
  1300. static TypeEvaluationKind getEvaluationKind(QualType T);
  1301. static bool hasScalarEvaluationKind(QualType T) {
  1302. return getEvaluationKind(T) == TEK_Scalar;
  1303. }
  1304. static bool hasAggregateEvaluationKind(QualType T) {
  1305. return getEvaluationKind(T) == TEK_Aggregate;
  1306. }
  1307. /// createBasicBlock - Create an LLVM basic block.
  1308. llvm::BasicBlock *createBasicBlock(const Twine &name = "",
  1309. llvm::Function *parent = nullptr,
  1310. llvm::BasicBlock *before = nullptr) {
  1311. #ifdef NDEBUG
  1312. return llvm::BasicBlock::Create(getLLVMContext(), "", parent, before);
  1313. #else
  1314. return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before);
  1315. #endif
  1316. }
  1317. /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
  1318. /// label maps to.
  1319. JumpDest getJumpDestForLabel(const LabelDecl *S);
  1320. /// SimplifyForwardingBlocks - If the given basic block is only a branch to
  1321. /// another basic block, simplify it. This assumes that no other code could
  1322. /// potentially reference the basic block.
  1323. void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
  1324. /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
  1325. /// adding a fall-through branch from the current insert block if
  1326. /// necessary. It is legal to call this function even if there is no current
  1327. /// insertion point.
  1328. ///
  1329. /// IsFinished - If true, indicates that the caller has finished emitting
  1330. /// branches to the given block and does not expect to emit code into it. This
  1331. /// means the block can be ignored if it is unreachable.
  1332. void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
  1333. /// EmitBlockAfterUses - Emit the given block somewhere hopefully
  1334. /// near its uses, and leave the insertion point in it.
  1335. void EmitBlockAfterUses(llvm::BasicBlock *BB);
  1336. /// EmitBranch - Emit a branch to the specified basic block from the current
  1337. /// insert block, taking care to avoid creation of branches from dummy
  1338. /// blocks. It is legal to call this function even if there is no current
  1339. /// insertion point.
  1340. ///
  1341. /// This function clears the current insertion point. The caller should follow
  1342. /// calls to this function with calls to Emit*Block prior to generation new
  1343. /// code.
  1344. void EmitBranch(llvm::BasicBlock *Block);
  1345. /// HaveInsertPoint - True if an insertion point is defined. If not, this
  1346. /// indicates that the current code being emitted is unreachable.
  1347. bool HaveInsertPoint() const {
  1348. return Builder.GetInsertBlock() != nullptr;
  1349. }
  1350. /// EnsureInsertPoint - Ensure that an insertion point is defined so that
  1351. /// emitted IR has a place to go. Note that by definition, if this function
  1352. /// creates a block then that block is unreachable; callers may do better to
  1353. /// detect when no insertion point is defined and simply skip IR generation.
  1354. void EnsureInsertPoint() {
  1355. if (!HaveInsertPoint())
  1356. EmitBlock(createBasicBlock());
  1357. }
  1358. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  1359. /// specified stmt yet.
  1360. void ErrorUnsupported(const Stmt *S, const char *Type);
  1361. //===--------------------------------------------------------------------===//
  1362. // Helpers
  1363. //===--------------------------------------------------------------------===//
  1364. LValue MakeAddrLValue(Address Addr, QualType T,
  1365. AlignmentSource AlignSource = AlignmentSource::Type) {
  1366. return LValue::MakeAddr(Addr, T, getContext(), AlignSource,
  1367. CGM.getTBAAInfo(T));
  1368. }
  1369. LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment,
  1370. AlignmentSource AlignSource = AlignmentSource::Type) {
  1371. return LValue::MakeAddr(Address(V, Alignment), T, getContext(),
  1372. AlignSource, CGM.getTBAAInfo(T));
  1373. }
  1374. LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T);
  1375. LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T);
  1376. CharUnits getNaturalTypeAlignment(QualType T,
  1377. AlignmentSource *Source = nullptr,
  1378. bool forPointeeType = false);
  1379. CharUnits getNaturalPointeeTypeAlignment(QualType T,
  1380. AlignmentSource *Source = nullptr);
  1381. Address EmitLoadOfReference(Address Ref, const ReferenceType *RefTy,
  1382. AlignmentSource *Source = nullptr);
  1383. LValue EmitLoadOfReferenceLValue(Address Ref, const ReferenceType *RefTy);
  1384. Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy,
  1385. AlignmentSource *Source = nullptr);
  1386. LValue EmitLoadOfPointerLValue(Address Ptr, const PointerType *PtrTy);
  1387. /// CreateTempAlloca - This creates a alloca and inserts it into the entry
  1388. /// block. The caller is responsible for setting an appropriate alignment on
  1389. /// the alloca.
  1390. llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty,
  1391. const Twine &Name = "tmp");
  1392. Address CreateTempAlloca(llvm::Type *Ty, CharUnits align,
  1393. const Twine &Name = "tmp");
  1394. /// CreateDefaultAlignedTempAlloca - This creates an alloca with the
  1395. /// default ABI alignment of the given LLVM type.
  1396. ///
  1397. /// IMPORTANT NOTE: This is *not* generally the right alignment for
  1398. /// any given AST type that happens to have been lowered to the
  1399. /// given IR type. This should only ever be used for function-local,
  1400. /// IR-driven manipulations like saving and restoring a value. Do
  1401. /// not hand this address off to arbitrary IRGen routines, and especially
  1402. /// do not pass it as an argument to a function that might expect a
  1403. /// properly ABI-aligned value.
  1404. Address CreateDefaultAlignTempAlloca(llvm::Type *Ty,
  1405. const Twine &Name = "tmp");
  1406. /// InitTempAlloca - Provide an initial value for the given alloca which
  1407. /// will be observable at all locations in the function.
  1408. ///
  1409. /// The address should be something that was returned from one of
  1410. /// the CreateTempAlloca or CreateMemTemp routines, and the
  1411. /// initializer must be valid in the entry block (i.e. it must
  1412. /// either be a constant or an argument value).
  1413. void InitTempAlloca(Address Alloca, llvm::Value *Value);
  1414. /// CreateIRTemp - Create a temporary IR object of the given type, with
  1415. /// appropriate alignment. This routine should only be used when an temporary
  1416. /// value needs to be stored into an alloca (for example, to avoid explicit
  1417. /// PHI construction), but the type is the IR type, not the type appropriate
  1418. /// for storing in memory.
  1419. ///
  1420. /// That is, this is exactly equivalent to CreateMemTemp, but calling
  1421. /// ConvertType instead of ConvertTypeForMem.
  1422. Address CreateIRTemp(QualType T, const Twine &Name = "tmp");
  1423. /// CreateMemTemp - Create a temporary memory object of the given type, with
  1424. /// appropriate alignment.
  1425. Address CreateMemTemp(QualType T, const Twine &Name = "tmp");
  1426. Address CreateMemTemp(QualType T, CharUnits Align, const Twine &Name = "tmp");
  1427. /// CreateAggTemp - Create a temporary memory object for the given
  1428. /// aggregate type.
  1429. AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp") {
  1430. return AggValueSlot::forAddr(CreateMemTemp(T, Name),
  1431. T.getQualifiers(),
  1432. AggValueSlot::IsNotDestructed,
  1433. AggValueSlot::DoesNotNeedGCBarriers,
  1434. AggValueSlot::IsNotAliased);
  1435. }
  1436. /// Emit a cast to void* in the appropriate address space.
  1437. llvm::Value *EmitCastToVoidPtr(llvm::Value *value);
  1438. /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
  1439. /// expression and compare the result against zero, returning an Int1Ty value.
  1440. llvm::Value *EvaluateExprAsBool(const Expr *E);
  1441. /// EmitIgnoredExpr - Emit an expression in a context which ignores the result.
  1442. void EmitIgnoredExpr(const Expr *E);
  1443. /// EmitAnyExpr - Emit code to compute the specified expression which can have
  1444. /// any type. The result is returned as an RValue struct. If this is an
  1445. /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
  1446. /// the result should be returned.
  1447. ///
  1448. /// \param ignoreResult True if the resulting value isn't used.
  1449. RValue EmitAnyExpr(const Expr *E,
  1450. AggValueSlot aggSlot = AggValueSlot::ignored(),
  1451. bool ignoreResult = false);
  1452. // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
  1453. // or the value of the expression, depending on how va_list is defined.
  1454. Address EmitVAListRef(const Expr *E);
  1455. /// Emit a "reference" to a __builtin_ms_va_list; this is
  1456. /// always the value of the expression, because a __builtin_ms_va_list is a
  1457. /// pointer to a char.
  1458. Address EmitMSVAListRef(const Expr *E);
  1459. /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
  1460. /// always be accessible even if no aggregate location is provided.
  1461. RValue EmitAnyExprToTemp(const Expr *E);
  1462. /// EmitAnyExprToMem - Emits the code necessary to evaluate an
  1463. /// arbitrary expression into the given memory location.
  1464. void EmitAnyExprToMem(const Expr *E, Address Location,
  1465. Qualifiers Quals, bool IsInitializer);
  1466. void EmitAnyExprToExn(const Expr *E, Address Addr);
  1467. /// EmitExprAsInit - Emits the code necessary to initialize a
  1468. /// location in memory with the given initializer.
  1469. void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue,
  1470. bool capturedByInit);
  1471. /// hasVolatileMember - returns true if aggregate type has a volatile
  1472. /// member.
  1473. bool hasVolatileMember(QualType T) {
  1474. if (const RecordType *RT = T->getAs<RecordType>()) {
  1475. const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
  1476. return RD->hasVolatileMember();
  1477. }
  1478. return false;
  1479. }
  1480. /// EmitAggregateCopy - Emit an aggregate assignment.
  1481. ///
  1482. /// The difference to EmitAggregateCopy is that tail padding is not copied.
  1483. /// This is required for correctness when assigning non-POD structures in C++.
  1484. void EmitAggregateAssign(Address DestPtr, Address SrcPtr,
  1485. QualType EltTy) {
  1486. bool IsVolatile = hasVolatileMember(EltTy);
  1487. EmitAggregateCopy(DestPtr, SrcPtr, EltTy, IsVolatile, true);
  1488. }
  1489. void EmitAggregateCopyCtor(Address DestPtr, Address SrcPtr,
  1490. QualType DestTy, QualType SrcTy) {
  1491. EmitAggregateCopy(DestPtr, SrcPtr, SrcTy, /*IsVolatile=*/false,
  1492. /*IsAssignment=*/false);
  1493. }
  1494. /// EmitAggregateCopy - Emit an aggregate copy.
  1495. ///
  1496. /// \param isVolatile - True iff either the source or the destination is
  1497. /// volatile.
  1498. /// \param isAssignment - If false, allow padding to be copied. This often
  1499. /// yields more efficient.
  1500. void EmitAggregateCopy(Address DestPtr, Address SrcPtr,
  1501. QualType EltTy, bool isVolatile=false,
  1502. bool isAssignment = false);
  1503. /// GetAddrOfLocalVar - Return the address of a local variable.
  1504. Address GetAddrOfLocalVar(const VarDecl *VD) {
  1505. auto it = LocalDeclMap.find(VD);
  1506. assert(it != LocalDeclMap.end() &&
  1507. "Invalid argument to GetAddrOfLocalVar(), no decl!");
  1508. return it->second;
  1509. }
  1510. /// getOpaqueLValueMapping - Given an opaque value expression (which
  1511. /// must be mapped to an l-value), return its mapping.
  1512. const LValue &getOpaqueLValueMapping(const OpaqueValueExpr *e) {
  1513. assert(OpaqueValueMapping::shouldBindAsLValue(e));
  1514. llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
  1515. it = OpaqueLValues.find(e);
  1516. assert(it != OpaqueLValues.end() && "no mapping for opaque value!");
  1517. return it->second;
  1518. }
  1519. /// getOpaqueRValueMapping - Given an opaque value expression (which
  1520. /// must be mapped to an r-value), return its mapping.
  1521. const RValue &getOpaqueRValueMapping(const OpaqueValueExpr *e) {
  1522. assert(!OpaqueValueMapping::shouldBindAsLValue(e));
  1523. llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
  1524. it = OpaqueRValues.find(e);
  1525. assert(it != OpaqueRValues.end() && "no mapping for opaque value!");
  1526. return it->second;
  1527. }
  1528. /// getAccessedFieldNo - Given an encoded value and a result number, return
  1529. /// the input field number being accessed.
  1530. static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
  1531. llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L);
  1532. llvm::BasicBlock *GetIndirectGotoBlock();
  1533. /// EmitNullInitialization - Generate code to set a value of the given type to
  1534. /// null, If the type contains data member pointers, they will be initialized
  1535. /// to -1 in accordance with the Itanium C++ ABI.
  1536. void EmitNullInitialization(Address DestPtr, QualType Ty);
  1537. /// Emits a call to an LLVM variable-argument intrinsic, either
  1538. /// \c llvm.va_start or \c llvm.va_end.
  1539. /// \param ArgValue A reference to the \c va_list as emitted by either
  1540. /// \c EmitVAListRef or \c EmitMSVAListRef.
  1541. /// \param IsStart If \c true, emits a call to \c llvm.va_start; otherwise,
  1542. /// calls \c llvm.va_end.
  1543. llvm::Value *EmitVAStartEnd(llvm::Value *ArgValue, bool IsStart);
  1544. /// Generate code to get an argument from the passed in pointer
  1545. /// and update it accordingly.
  1546. /// \param VE The \c VAArgExpr for which to generate code.
  1547. /// \param VAListAddr Receives a reference to the \c va_list as emitted by
  1548. /// either \c EmitVAListRef or \c EmitMSVAListRef.
  1549. /// \returns A pointer to the argument.
  1550. // FIXME: We should be able to get rid of this method and use the va_arg
  1551. // instruction in LLVM instead once it works well enough.
  1552. Address EmitVAArg(VAArgExpr *VE, Address &VAListAddr);
  1553. /// emitArrayLength - Compute the length of an array, even if it's a
  1554. /// VLA, and drill down to the base element type.
  1555. llvm::Value *emitArrayLength(const ArrayType *arrayType,
  1556. QualType &baseType,
  1557. Address &addr);
  1558. /// EmitVLASize - Capture all the sizes for the VLA expressions in
  1559. /// the given variably-modified type and store them in the VLASizeMap.
  1560. ///
  1561. /// This function can be called with a null (unreachable) insert point.
  1562. void EmitVariablyModifiedType(QualType Ty);
  1563. /// getVLASize - Returns an LLVM value that corresponds to the size,
  1564. /// in non-variably-sized elements, of a variable length array type,
  1565. /// plus that largest non-variably-sized element type. Assumes that
  1566. /// the type has already been emitted with EmitVariablyModifiedType.
  1567. std::pair<llvm::Value*,QualType> getVLASize(const VariableArrayType *vla);
  1568. std::pair<llvm::Value*,QualType> getVLASize(QualType vla);
  1569. /// LoadCXXThis - Load the value of 'this'. This function is only valid while
  1570. /// generating code for an C++ member function.
  1571. llvm::Value *LoadCXXThis() {
  1572. assert(CXXThisValue && "no 'this' value for this function");
  1573. return CXXThisValue;
  1574. }
  1575. Address LoadCXXThisAddress();
  1576. /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
  1577. /// virtual bases.
  1578. // FIXME: Every place that calls LoadCXXVTT is something
  1579. // that needs to be abstracted properly.
  1580. llvm::Value *LoadCXXVTT() {
  1581. assert(CXXStructorImplicitParamValue && "no VTT value for this function");
  1582. return CXXStructorImplicitParamValue;
  1583. }
  1584. /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
  1585. /// complete class to the given direct base.
  1586. Address
  1587. GetAddressOfDirectBaseInCompleteClass(Address Value,
  1588. const CXXRecordDecl *Derived,
  1589. const CXXRecordDecl *Base,
  1590. bool BaseIsVirtual);
  1591. static bool ShouldNullCheckClassCastValue(const CastExpr *Cast);
  1592. /// GetAddressOfBaseClass - This function will add the necessary delta to the
  1593. /// load of 'this' and returns address of the base class.
  1594. Address GetAddressOfBaseClass(Address Value,
  1595. const CXXRecordDecl *Derived,
  1596. CastExpr::path_const_iterator PathBegin,
  1597. CastExpr::path_const_iterator PathEnd,
  1598. bool NullCheckValue, SourceLocation Loc);
  1599. Address GetAddressOfDerivedClass(Address Value,
  1600. const CXXRecordDecl *Derived,
  1601. CastExpr::path_const_iterator PathBegin,
  1602. CastExpr::path_const_iterator PathEnd,
  1603. bool NullCheckValue);
  1604. /// GetVTTParameter - Return the VTT parameter that should be passed to a
  1605. /// base constructor/destructor with virtual bases.
  1606. /// FIXME: VTTs are Itanium ABI-specific, so the definition should move
  1607. /// to ItaniumCXXABI.cpp together with all the references to VTT.
  1608. llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase,
  1609. bool Delegating);
  1610. void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
  1611. CXXCtorType CtorType,
  1612. const FunctionArgList &Args,
  1613. SourceLocation Loc);
  1614. // It's important not to confuse this and the previous function. Delegating
  1615. // constructors are the C++0x feature. The constructor delegate optimization
  1616. // is used to reduce duplication in the base and complete consturctors where
  1617. // they are substantially the same.
  1618. void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
  1619. const FunctionArgList &Args);
  1620. /// Emit a call to an inheriting constructor (that is, one that invokes a
  1621. /// constructor inherited from a base class) by inlining its definition. This
  1622. /// is necessary if the ABI does not support forwarding the arguments to the
  1623. /// base class constructor (because they're variadic or similar).
  1624. void EmitInlinedInheritingCXXConstructorCall(const CXXConstructorDecl *Ctor,
  1625. CXXCtorType CtorType,
  1626. bool ForVirtualBase,
  1627. bool Delegating,
  1628. CallArgList &Args);
  1629. /// Emit a call to a constructor inherited from a base class, passing the
  1630. /// current constructor's arguments along unmodified (without even making
  1631. /// a copy).
  1632. void EmitInheritedCXXConstructorCall(const CXXConstructorDecl *D,
  1633. bool ForVirtualBase, Address This,
  1634. bool InheritedFromVBase,
  1635. const CXXInheritedCtorInitExpr *E);
  1636. void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
  1637. bool ForVirtualBase, bool Delegating,
  1638. Address This, const CXXConstructExpr *E);
  1639. void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
  1640. bool ForVirtualBase, bool Delegating,
  1641. Address This, CallArgList &Args);
  1642. /// Emit assumption load for all bases. Requires to be be called only on
  1643. /// most-derived class and not under construction of the object.
  1644. void EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl, Address This);
  1645. /// Emit assumption that vptr load == global vtable.
  1646. void EmitVTableAssumptionLoad(const VPtr &vptr, Address This);
  1647. void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
  1648. Address This, Address Src,
  1649. const CXXConstructExpr *E);
  1650. void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
  1651. const ArrayType *ArrayTy,
  1652. Address ArrayPtr,
  1653. const CXXConstructExpr *E,
  1654. bool ZeroInitialization = false);
  1655. void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
  1656. llvm::Value *NumElements,
  1657. Address ArrayPtr,
  1658. const CXXConstructExpr *E,
  1659. bool ZeroInitialization = false);
  1660. static Destroyer destroyCXXObject;
  1661. void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
  1662. bool ForVirtualBase, bool Delegating,
  1663. Address This);
  1664. void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType,
  1665. llvm::Type *ElementTy, Address NewPtr,
  1666. llvm::Value *NumElements,
  1667. llvm::Value *AllocSizeWithoutCookie);
  1668. void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType,
  1669. Address Ptr);
  1670. llvm::Value *EmitLifetimeStart(uint64_t Size, llvm::Value *Addr);
  1671. void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr);
  1672. llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
  1673. void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
  1674. void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
  1675. QualType DeleteTy);
  1676. RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
  1677. const Expr *Arg, bool IsDelete);
  1678. llvm::Value *EmitCXXTypeidExpr(const CXXTypeidExpr *E);
  1679. llvm::Value *EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE);
  1680. Address EmitCXXUuidofExpr(const CXXUuidofExpr *E);
  1681. /// \brief Situations in which we might emit a check for the suitability of a
  1682. /// pointer or glvalue.
  1683. enum TypeCheckKind {
  1684. /// Checking the operand of a load. Must be suitably sized and aligned.
  1685. TCK_Load,
  1686. /// Checking the destination of a store. Must be suitably sized and aligned.
  1687. TCK_Store,
  1688. /// Checking the bound value in a reference binding. Must be suitably sized
  1689. /// and aligned, but is not required to refer to an object (until the
  1690. /// reference is used), per core issue 453.
  1691. TCK_ReferenceBinding,
  1692. /// Checking the object expression in a non-static data member access. Must
  1693. /// be an object within its lifetime.
  1694. TCK_MemberAccess,
  1695. /// Checking the 'this' pointer for a call to a non-static member function.
  1696. /// Must be an object within its lifetime.
  1697. TCK_MemberCall,
  1698. /// Checking the 'this' pointer for a constructor call.
  1699. TCK_ConstructorCall,
  1700. /// Checking the operand of a static_cast to a derived pointer type. Must be
  1701. /// null or an object within its lifetime.
  1702. TCK_DowncastPointer,
  1703. /// Checking the operand of a static_cast to a derived reference type. Must
  1704. /// be an object within its lifetime.
  1705. TCK_DowncastReference,
  1706. /// Checking the operand of a cast to a base object. Must be suitably sized
  1707. /// and aligned.
  1708. TCK_Upcast,
  1709. /// Checking the operand of a cast to a virtual base object. Must be an
  1710. /// object within its lifetime.
  1711. TCK_UpcastToVirtualBase
  1712. };
  1713. /// \brief Whether any type-checking sanitizers are enabled. If \c false,
  1714. /// calls to EmitTypeCheck can be skipped.
  1715. bool sanitizePerformTypeCheck() const;
  1716. /// \brief Emit a check that \p V is the address of storage of the
  1717. /// appropriate size and alignment for an object of type \p Type.
  1718. void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V,
  1719. QualType Type, CharUnits Alignment = CharUnits::Zero(),
  1720. bool SkipNullCheck = false);
  1721. /// \brief Emit a check that \p Base points into an array object, which
  1722. /// we can access at index \p Index. \p Accessed should be \c false if we
  1723. /// this expression is used as an lvalue, for instance in "&Arr[Idx]".
  1724. void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index,
  1725. QualType IndexType, bool Accessed);
  1726. llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
  1727. bool isInc, bool isPre);
  1728. ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
  1729. bool isInc, bool isPre);
  1730. void EmitAlignmentAssumption(llvm::Value *PtrValue, unsigned Alignment,
  1731. llvm::Value *OffsetValue = nullptr) {
  1732. Builder.CreateAlignmentAssumption(CGM.getDataLayout(), PtrValue, Alignment,
  1733. OffsetValue);
  1734. }
  1735. //===--------------------------------------------------------------------===//
  1736. // Declaration Emission
  1737. //===--------------------------------------------------------------------===//
  1738. /// EmitDecl - Emit a declaration.
  1739. ///
  1740. /// This function can be called with a null (unreachable) insert point.
  1741. void EmitDecl(const Decl &D);
  1742. /// EmitVarDecl - Emit a local variable declaration.
  1743. ///
  1744. /// This function can be called with a null (unreachable) insert point.
  1745. void EmitVarDecl(const VarDecl &D);
  1746. void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue,
  1747. bool capturedByInit);
  1748. void EmitScalarInit(llvm::Value *init, LValue lvalue);
  1749. typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
  1750. llvm::Value *Address);
  1751. /// \brief Determine whether the given initializer is trivial in the sense
  1752. /// that it requires no code to be generated.
  1753. bool isTrivialInitializer(const Expr *Init);
  1754. /// EmitAutoVarDecl - Emit an auto variable declaration.
  1755. ///
  1756. /// This function can be called with a null (unreachable) insert point.
  1757. void EmitAutoVarDecl(const VarDecl &D);
  1758. class AutoVarEmission {
  1759. friend class CodeGenFunction;
  1760. const VarDecl *Variable;
  1761. /// The address of the alloca. Invalid if the variable was emitted
  1762. /// as a global constant.
  1763. Address Addr;
  1764. llvm::Value *NRVOFlag;
  1765. /// True if the variable is a __block variable.
  1766. bool IsByRef;
  1767. /// True if the variable is of aggregate type and has a constant
  1768. /// initializer.
  1769. bool IsConstantAggregate;
  1770. /// Non-null if we should use lifetime annotations.
  1771. llvm::Value *SizeForLifetimeMarkers;
  1772. struct Invalid {};
  1773. AutoVarEmission(Invalid) : Variable(nullptr), Addr(Address::invalid()) {}
  1774. AutoVarEmission(const VarDecl &variable)
  1775. : Variable(&variable), Addr(Address::invalid()), NRVOFlag(nullptr),
  1776. IsByRef(false), IsConstantAggregate(false),
  1777. SizeForLifetimeMarkers(nullptr) {}
  1778. bool wasEmittedAsGlobal() const { return !Addr.isValid(); }
  1779. public:
  1780. static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); }
  1781. bool useLifetimeMarkers() const {
  1782. return SizeForLifetimeMarkers != nullptr;
  1783. }
  1784. llvm::Value *getSizeForLifetimeMarkers() const {
  1785. assert(useLifetimeMarkers());
  1786. return SizeForLifetimeMarkers;
  1787. }
  1788. /// Returns the raw, allocated address, which is not necessarily
  1789. /// the address of the object itself.
  1790. Address getAllocatedAddress() const {
  1791. return Addr;
  1792. }
  1793. /// Returns the address of the object within this declaration.
  1794. /// Note that this does not chase the forwarding pointer for
  1795. /// __block decls.
  1796. Address getObjectAddress(CodeGenFunction &CGF) const {
  1797. if (!IsByRef) return Addr;
  1798. return CGF.emitBlockByrefAddress(Addr, Variable, /*forward*/ false);
  1799. }
  1800. };
  1801. AutoVarEmission EmitAutoVarAlloca(const VarDecl &var);
  1802. void EmitAutoVarInit(const AutoVarEmission &emission);
  1803. void EmitAutoVarCleanups(const AutoVarEmission &emission);
  1804. void emitAutoVarTypeCleanup(const AutoVarEmission &emission,
  1805. QualType::DestructionKind dtorKind);
  1806. void EmitStaticVarDecl(const VarDecl &D,
  1807. llvm::GlobalValue::LinkageTypes Linkage);
  1808. class ParamValue {
  1809. llvm::Value *Value;
  1810. unsigned Alignment;
  1811. ParamValue(llvm::Value *V, unsigned A) : Value(V), Alignment(A) {}
  1812. public:
  1813. static ParamValue forDirect(llvm::Value *value) {
  1814. return ParamValue(value, 0);
  1815. }
  1816. static ParamValue forIndirect(Address addr) {
  1817. assert(!addr.getAlignment().isZero());
  1818. return ParamValue(addr.getPointer(), addr.getAlignment().getQuantity());
  1819. }
  1820. bool isIndirect() const { return Alignment != 0; }
  1821. llvm::Value *getAnyValue() const { return Value; }
  1822. llvm::Value *getDirectValue() const {
  1823. assert(!isIndirect());
  1824. return Value;
  1825. }
  1826. Address getIndirectAddress() const {
  1827. assert(isIndirect());
  1828. return Address(Value, CharUnits::fromQuantity(Alignment));
  1829. }
  1830. };
  1831. /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
  1832. void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo);
  1833. /// protectFromPeepholes - Protect a value that we're intending to
  1834. /// store to the side, but which will probably be used later, from
  1835. /// aggressive peepholing optimizations that might delete it.
  1836. ///
  1837. /// Pass the result to unprotectFromPeepholes to declare that
  1838. /// protection is no longer required.
  1839. ///
  1840. /// There's no particular reason why this shouldn't apply to
  1841. /// l-values, it's just that no existing peepholes work on pointers.
  1842. PeepholeProtection protectFromPeepholes(RValue rvalue);
  1843. void unprotectFromPeepholes(PeepholeProtection protection);
  1844. //===--------------------------------------------------------------------===//
  1845. // Statement Emission
  1846. //===--------------------------------------------------------------------===//
  1847. /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
  1848. void EmitStopPoint(const Stmt *S);
  1849. /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
  1850. /// this function even if there is no current insertion point.
  1851. ///
  1852. /// This function may clear the current insertion point; callers should use
  1853. /// EnsureInsertPoint if they wish to subsequently generate code without first
  1854. /// calling EmitBlock, EmitBranch, or EmitStmt.
  1855. void EmitStmt(const Stmt *S);
  1856. /// EmitSimpleStmt - Try to emit a "simple" statement which does not
  1857. /// necessarily require an insertion point or debug information; typically
  1858. /// because the statement amounts to a jump or a container of other
  1859. /// statements.
  1860. ///
  1861. /// \return True if the statement was handled.
  1862. bool EmitSimpleStmt(const Stmt *S);
  1863. Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
  1864. AggValueSlot AVS = AggValueSlot::ignored());
  1865. Address EmitCompoundStmtWithoutScope(const CompoundStmt &S,
  1866. bool GetLast = false,
  1867. AggValueSlot AVS =
  1868. AggValueSlot::ignored());
  1869. /// EmitLabel - Emit the block for the given label. It is legal to call this
  1870. /// function even if there is no current insertion point.
  1871. void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt.
  1872. void EmitLabelStmt(const LabelStmt &S);
  1873. void EmitAttributedStmt(const AttributedStmt &S);
  1874. void EmitGotoStmt(const GotoStmt &S);
  1875. void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
  1876. void EmitIfStmt(const IfStmt &S);
  1877. void EmitWhileStmt(const WhileStmt &S,
  1878. ArrayRef<const Attr *> Attrs = None);
  1879. void EmitDoStmt(const DoStmt &S, ArrayRef<const Attr *> Attrs = None);
  1880. void EmitForStmt(const ForStmt &S,
  1881. ArrayRef<const Attr *> Attrs = None);
  1882. void EmitReturnStmt(const ReturnStmt &S);
  1883. void EmitDeclStmt(const DeclStmt &S);
  1884. void EmitBreakStmt(const BreakStmt &S);
  1885. void EmitContinueStmt(const ContinueStmt &S);
  1886. void EmitSwitchStmt(const SwitchStmt &S);
  1887. void EmitDefaultStmt(const DefaultStmt &S);
  1888. void EmitCaseStmt(const CaseStmt &S);
  1889. void EmitCaseStmtRange(const CaseStmt &S);
  1890. void EmitAsmStmt(const AsmStmt &S);
  1891. void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
  1892. void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
  1893. void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
  1894. void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
  1895. void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S);
  1896. void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
  1897. void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
  1898. void EmitCXXTryStmt(const CXXTryStmt &S);
  1899. void EmitSEHTryStmt(const SEHTryStmt &S);
  1900. void EmitSEHLeaveStmt(const SEHLeaveStmt &S);
  1901. void EnterSEHTryStmt(const SEHTryStmt &S);
  1902. void ExitSEHTryStmt(const SEHTryStmt &S);
  1903. void startOutlinedSEHHelper(CodeGenFunction &ParentCGF, bool IsFilter,
  1904. const Stmt *OutlinedStmt);
  1905. llvm::Function *GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
  1906. const SEHExceptStmt &Except);
  1907. llvm::Function *GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
  1908. const SEHFinallyStmt &Finally);
  1909. void EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
  1910. llvm::Value *ParentFP,
  1911. llvm::Value *EntryEBP);
  1912. llvm::Value *EmitSEHExceptionCode();
  1913. llvm::Value *EmitSEHExceptionInfo();
  1914. llvm::Value *EmitSEHAbnormalTermination();
  1915. /// Scan the outlined statement for captures from the parent function. For
  1916. /// each capture, mark the capture as escaped and emit a call to
  1917. /// llvm.localrecover. Insert the localrecover result into the LocalDeclMap.
  1918. void EmitCapturedLocals(CodeGenFunction &ParentCGF, const Stmt *OutlinedStmt,
  1919. bool IsFilter);
  1920. /// Recovers the address of a local in a parent function. ParentVar is the
  1921. /// address of the variable used in the immediate parent function. It can
  1922. /// either be an alloca or a call to llvm.localrecover if there are nested
  1923. /// outlined functions. ParentFP is the frame pointer of the outermost parent
  1924. /// frame.
  1925. Address recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
  1926. Address ParentVar,
  1927. llvm::Value *ParentFP);
  1928. void EmitCXXForRangeStmt(const CXXForRangeStmt &S,
  1929. ArrayRef<const Attr *> Attrs = None);
  1930. /// Returns calculated size of the specified type.
  1931. llvm::Value *getTypeSize(QualType Ty);
  1932. LValue InitCapturedStruct(const CapturedStmt &S);
  1933. llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K);
  1934. llvm::Function *GenerateCapturedStmtFunction(const CapturedStmt &S);
  1935. Address GenerateCapturedStmtArgument(const CapturedStmt &S);
  1936. llvm::Function *GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S);
  1937. void GenerateOpenMPCapturedVars(const CapturedStmt &S,
  1938. SmallVectorImpl<llvm::Value *> &CapturedVars);
  1939. void emitOMPSimpleStore(LValue LVal, RValue RVal, QualType RValTy,
  1940. SourceLocation Loc);
  1941. /// \brief Perform element by element copying of arrays with type \a
  1942. /// OriginalType from \a SrcAddr to \a DestAddr using copying procedure
  1943. /// generated by \a CopyGen.
  1944. ///
  1945. /// \param DestAddr Address of the destination array.
  1946. /// \param SrcAddr Address of the source array.
  1947. /// \param OriginalType Type of destination and source arrays.
  1948. /// \param CopyGen Copying procedure that copies value of single array element
  1949. /// to another single array element.
  1950. void EmitOMPAggregateAssign(
  1951. Address DestAddr, Address SrcAddr, QualType OriginalType,
  1952. const llvm::function_ref<void(Address, Address)> &CopyGen);
  1953. /// \brief Emit proper copying of data from one variable to another.
  1954. ///
  1955. /// \param OriginalType Original type of the copied variables.
  1956. /// \param DestAddr Destination address.
  1957. /// \param SrcAddr Source address.
  1958. /// \param DestVD Destination variable used in \a CopyExpr (for arrays, has
  1959. /// type of the base array element).
  1960. /// \param SrcVD Source variable used in \a CopyExpr (for arrays, has type of
  1961. /// the base array element).
  1962. /// \param Copy Actual copygin expression for copying data from \a SrcVD to \a
  1963. /// DestVD.
  1964. void EmitOMPCopy(QualType OriginalType,
  1965. Address DestAddr, Address SrcAddr,
  1966. const VarDecl *DestVD, const VarDecl *SrcVD,
  1967. const Expr *Copy);
  1968. /// \brief Emit atomic update code for constructs: \a X = \a X \a BO \a E or
  1969. /// \a X = \a E \a BO \a E.
  1970. ///
  1971. /// \param X Value to be updated.
  1972. /// \param E Update value.
  1973. /// \param BO Binary operation for update operation.
  1974. /// \param IsXLHSInRHSPart true if \a X is LHS in RHS part of the update
  1975. /// expression, false otherwise.
  1976. /// \param AO Atomic ordering of the generated atomic instructions.
  1977. /// \param CommonGen Code generator for complex expressions that cannot be
  1978. /// expressed through atomicrmw instruction.
  1979. /// \returns <true, OldAtomicValue> if simple 'atomicrmw' instruction was
  1980. /// generated, <false, RValue::get(nullptr)> otherwise.
  1981. std::pair<bool, RValue> EmitOMPAtomicSimpleUpdateExpr(
  1982. LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
  1983. llvm::AtomicOrdering AO, SourceLocation Loc,
  1984. const llvm::function_ref<RValue(RValue)> &CommonGen);
  1985. bool EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
  1986. OMPPrivateScope &PrivateScope);
  1987. void EmitOMPPrivateClause(const OMPExecutableDirective &D,
  1988. OMPPrivateScope &PrivateScope);
  1989. void EmitOMPUseDevicePtrClause(
  1990. const OMPClause &C, OMPPrivateScope &PrivateScope,
  1991. const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap);
  1992. /// \brief Emit code for copyin clause in \a D directive. The next code is
  1993. /// generated at the start of outlined functions for directives:
  1994. /// \code
  1995. /// threadprivate_var1 = master_threadprivate_var1;
  1996. /// operator=(threadprivate_var2, master_threadprivate_var2);
  1997. /// ...
  1998. /// __kmpc_barrier(&loc, global_tid);
  1999. /// \endcode
  2000. ///
  2001. /// \param D OpenMP directive possibly with 'copyin' clause(s).
  2002. /// \returns true if at least one copyin variable is found, false otherwise.
  2003. bool EmitOMPCopyinClause(const OMPExecutableDirective &D);
  2004. /// \brief Emit initial code for lastprivate variables. If some variable is
  2005. /// not also firstprivate, then the default initialization is used. Otherwise
  2006. /// initialization of this variable is performed by EmitOMPFirstprivateClause
  2007. /// method.
  2008. ///
  2009. /// \param D Directive that may have 'lastprivate' directives.
  2010. /// \param PrivateScope Private scope for capturing lastprivate variables for
  2011. /// proper codegen in internal captured statement.
  2012. ///
  2013. /// \returns true if there is at least one lastprivate variable, false
  2014. /// otherwise.
  2015. bool EmitOMPLastprivateClauseInit(const OMPExecutableDirective &D,
  2016. OMPPrivateScope &PrivateScope);
  2017. /// \brief Emit final copying of lastprivate values to original variables at
  2018. /// the end of the worksharing or simd directive.
  2019. ///
  2020. /// \param D Directive that has at least one 'lastprivate' directives.
  2021. /// \param IsLastIterCond Boolean condition that must be set to 'i1 true' if
  2022. /// it is the last iteration of the loop code in associated directive, or to
  2023. /// 'i1 false' otherwise. If this item is nullptr, no final check is required.
  2024. void EmitOMPLastprivateClauseFinal(const OMPExecutableDirective &D,
  2025. bool NoFinals,
  2026. llvm::Value *IsLastIterCond = nullptr);
  2027. /// Emit initial code for linear clauses.
  2028. void EmitOMPLinearClause(const OMPLoopDirective &D,
  2029. CodeGenFunction::OMPPrivateScope &PrivateScope);
  2030. /// Emit final code for linear clauses.
  2031. /// \param CondGen Optional conditional code for final part of codegen for
  2032. /// linear clause.
  2033. void EmitOMPLinearClauseFinal(
  2034. const OMPLoopDirective &D,
  2035. const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen);
  2036. /// \brief Emit initial code for reduction variables. Creates reduction copies
  2037. /// and initializes them with the values according to OpenMP standard.
  2038. ///
  2039. /// \param D Directive (possibly) with the 'reduction' clause.
  2040. /// \param PrivateScope Private scope for capturing reduction variables for
  2041. /// proper codegen in internal captured statement.
  2042. ///
  2043. void EmitOMPReductionClauseInit(const OMPExecutableDirective &D,
  2044. OMPPrivateScope &PrivateScope);
  2045. /// \brief Emit final update of reduction values to original variables at
  2046. /// the end of the directive.
  2047. ///
  2048. /// \param D Directive that has at least one 'reduction' directives.
  2049. void EmitOMPReductionClauseFinal(const OMPExecutableDirective &D);
  2050. /// \brief Emit initial code for linear variables. Creates private copies
  2051. /// and initializes them with the values according to OpenMP standard.
  2052. ///
  2053. /// \param D Directive (possibly) with the 'linear' clause.
  2054. void EmitOMPLinearClauseInit(const OMPLoopDirective &D);
  2055. typedef const llvm::function_ref<void(CodeGenFunction & /*CGF*/,
  2056. llvm::Value * /*OutlinedFn*/,
  2057. const OMPTaskDataTy & /*Data*/)>
  2058. TaskGenTy;
  2059. void EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
  2060. const RegionCodeGenTy &BodyGen,
  2061. const TaskGenTy &TaskGen, OMPTaskDataTy &Data);
  2062. void EmitOMPParallelDirective(const OMPParallelDirective &S);
  2063. void EmitOMPSimdDirective(const OMPSimdDirective &S);
  2064. void EmitOMPForDirective(const OMPForDirective &S);
  2065. void EmitOMPForSimdDirective(const OMPForSimdDirective &S);
  2066. void EmitOMPSectionsDirective(const OMPSectionsDirective &S);
  2067. void EmitOMPSectionDirective(const OMPSectionDirective &S);
  2068. void EmitOMPSingleDirective(const OMPSingleDirective &S);
  2069. void EmitOMPMasterDirective(const OMPMasterDirective &S);
  2070. void EmitOMPCriticalDirective(const OMPCriticalDirective &S);
  2071. void EmitOMPParallelForDirective(const OMPParallelForDirective &S);
  2072. void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S);
  2073. void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S);
  2074. void EmitOMPTaskDirective(const OMPTaskDirective &S);
  2075. void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S);
  2076. void EmitOMPBarrierDirective(const OMPBarrierDirective &S);
  2077. void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S);
  2078. void EmitOMPTaskgroupDirective(const OMPTaskgroupDirective &S);
  2079. void EmitOMPFlushDirective(const OMPFlushDirective &S);
  2080. void EmitOMPOrderedDirective(const OMPOrderedDirective &S);
  2081. void EmitOMPAtomicDirective(const OMPAtomicDirective &S);
  2082. void EmitOMPTargetDirective(const OMPTargetDirective &S);
  2083. void EmitOMPTargetDataDirective(const OMPTargetDataDirective &S);
  2084. void EmitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective &S);
  2085. void EmitOMPTargetExitDataDirective(const OMPTargetExitDataDirective &S);
  2086. void EmitOMPTargetUpdateDirective(const OMPTargetUpdateDirective &S);
  2087. void EmitOMPTargetParallelDirective(const OMPTargetParallelDirective &S);
  2088. void
  2089. EmitOMPTargetParallelForDirective(const OMPTargetParallelForDirective &S);
  2090. void EmitOMPTeamsDirective(const OMPTeamsDirective &S);
  2091. void
  2092. EmitOMPCancellationPointDirective(const OMPCancellationPointDirective &S);
  2093. void EmitOMPCancelDirective(const OMPCancelDirective &S);
  2094. void EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S);
  2095. void EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S);
  2096. void EmitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective &S);
  2097. void EmitOMPDistributeDirective(const OMPDistributeDirective &S);
  2098. void EmitOMPDistributeLoop(const OMPDistributeDirective &S);
  2099. void EmitOMPDistributeParallelForDirective(
  2100. const OMPDistributeParallelForDirective &S);
  2101. void EmitOMPDistributeParallelForSimdDirective(
  2102. const OMPDistributeParallelForSimdDirective &S);
  2103. void EmitOMPDistributeSimdDirective(const OMPDistributeSimdDirective &S);
  2104. void EmitOMPTargetParallelForSimdDirective(
  2105. const OMPTargetParallelForSimdDirective &S);
  2106. void EmitOMPTargetSimdDirective(const OMPTargetSimdDirective &S);
  2107. void EmitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective &S);
  2108. /// Emit outlined function for the target directive.
  2109. static std::pair<llvm::Function * /*OutlinedFn*/,
  2110. llvm::Constant * /*OutlinedFnID*/>
  2111. EmitOMPTargetDirectiveOutlinedFunction(CodeGenModule &CGM,
  2112. const OMPTargetDirective &S,
  2113. StringRef ParentName,
  2114. bool IsOffloadEntry);
  2115. /// \brief Emit inner loop of the worksharing/simd construct.
  2116. ///
  2117. /// \param S Directive, for which the inner loop must be emitted.
  2118. /// \param RequiresCleanup true, if directive has some associated private
  2119. /// variables.
  2120. /// \param LoopCond Bollean condition for loop continuation.
  2121. /// \param IncExpr Increment expression for loop control variable.
  2122. /// \param BodyGen Generator for the inner body of the inner loop.
  2123. /// \param PostIncGen Genrator for post-increment code (required for ordered
  2124. /// loop directvies).
  2125. void EmitOMPInnerLoop(
  2126. const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
  2127. const Expr *IncExpr,
  2128. const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
  2129. const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen);
  2130. JumpDest getOMPCancelDestination(OpenMPDirectiveKind Kind);
  2131. /// Emit initial code for loop counters of loop-based directives.
  2132. void EmitOMPPrivateLoopCounters(const OMPLoopDirective &S,
  2133. OMPPrivateScope &LoopScope);
  2134. private:
  2135. /// Helpers for the OpenMP loop directives.
  2136. void EmitOMPLoopBody(const OMPLoopDirective &D, JumpDest LoopExit);
  2137. void EmitOMPSimdInit(const OMPLoopDirective &D, bool IsMonotonic = false);
  2138. void EmitOMPSimdFinal(
  2139. const OMPLoopDirective &D,
  2140. const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen);
  2141. /// \brief Emit code for the worksharing loop-based directive.
  2142. /// \return true, if this construct has any lastprivate clause, false -
  2143. /// otherwise.
  2144. bool EmitOMPWorksharingLoop(const OMPLoopDirective &S);
  2145. void EmitOMPOuterLoop(bool IsMonotonic, bool DynamicOrOrdered,
  2146. const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
  2147. Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk);
  2148. void EmitOMPForOuterLoop(const OpenMPScheduleTy &ScheduleKind,
  2149. bool IsMonotonic, const OMPLoopDirective &S,
  2150. OMPPrivateScope &LoopScope, bool Ordered, Address LB,
  2151. Address UB, Address ST, Address IL,
  2152. llvm::Value *Chunk);
  2153. void EmitOMPDistributeOuterLoop(
  2154. OpenMPDistScheduleClauseKind ScheduleKind,
  2155. const OMPDistributeDirective &S, OMPPrivateScope &LoopScope,
  2156. Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk);
  2157. /// \brief Emit code for sections directive.
  2158. void EmitSections(const OMPExecutableDirective &S);
  2159. public:
  2160. //===--------------------------------------------------------------------===//
  2161. // LValue Expression Emission
  2162. //===--------------------------------------------------------------------===//
  2163. /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
  2164. RValue GetUndefRValue(QualType Ty);
  2165. /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
  2166. /// and issue an ErrorUnsupported style diagnostic (using the
  2167. /// provided Name).
  2168. RValue EmitUnsupportedRValue(const Expr *E,
  2169. const char *Name);
  2170. /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
  2171. /// an ErrorUnsupported style diagnostic (using the provided Name).
  2172. LValue EmitUnsupportedLValue(const Expr *E,
  2173. const char *Name);
  2174. /// EmitLValue - Emit code to compute a designator that specifies the location
  2175. /// of the expression.
  2176. ///
  2177. /// This can return one of two things: a simple address or a bitfield
  2178. /// reference. In either case, the LLVM Value* in the LValue structure is
  2179. /// guaranteed to be an LLVM pointer type.
  2180. ///
  2181. /// If this returns a bitfield reference, nothing about the pointee type of
  2182. /// the LLVM value is known: For example, it may not be a pointer to an
  2183. /// integer.
  2184. ///
  2185. /// If this returns a normal address, and if the lvalue's C type is fixed
  2186. /// size, this method guarantees that the returned pointer type will point to
  2187. /// an LLVM type of the same size of the lvalue's type. If the lvalue has a
  2188. /// variable length type, this is not possible.
  2189. ///
  2190. LValue EmitLValue(const Expr *E);
  2191. /// \brief Same as EmitLValue but additionally we generate checking code to
  2192. /// guard against undefined behavior. This is only suitable when we know
  2193. /// that the address will be used to access the object.
  2194. LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK);
  2195. RValue convertTempToRValue(Address addr, QualType type,
  2196. SourceLocation Loc);
  2197. void EmitAtomicInit(Expr *E, LValue lvalue);
  2198. bool LValueIsSuitableForInlineAtomic(LValue Src);
  2199. RValue EmitAtomicLoad(LValue LV, SourceLocation SL,
  2200. AggValueSlot Slot = AggValueSlot::ignored());
  2201. RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc,
  2202. llvm::AtomicOrdering AO, bool IsVolatile = false,
  2203. AggValueSlot slot = AggValueSlot::ignored());
  2204. void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit);
  2205. void EmitAtomicStore(RValue rvalue, LValue lvalue, llvm::AtomicOrdering AO,
  2206. bool IsVolatile, bool isInit);
  2207. std::pair<RValue, llvm::Value *> EmitAtomicCompareExchange(
  2208. LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
  2209. llvm::AtomicOrdering Success =
  2210. llvm::AtomicOrdering::SequentiallyConsistent,
  2211. llvm::AtomicOrdering Failure =
  2212. llvm::AtomicOrdering::SequentiallyConsistent,
  2213. bool IsWeak = false, AggValueSlot Slot = AggValueSlot::ignored());
  2214. void EmitAtomicUpdate(LValue LVal, llvm::AtomicOrdering AO,
  2215. const llvm::function_ref<RValue(RValue)> &UpdateOp,
  2216. bool IsVolatile);
  2217. /// EmitToMemory - Change a scalar value from its value
  2218. /// representation to its in-memory representation.
  2219. llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty);
  2220. /// EmitFromMemory - Change a scalar value from its memory
  2221. /// representation to its value representation.
  2222. llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty);
  2223. /// EmitLoadOfScalar - Load a scalar value from an address, taking
  2224. /// care to appropriately convert from the memory representation to
  2225. /// the LLVM value representation.
  2226. llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty,
  2227. SourceLocation Loc,
  2228. AlignmentSource AlignSource =
  2229. AlignmentSource::Type,
  2230. llvm::MDNode *TBAAInfo = nullptr,
  2231. QualType TBAABaseTy = QualType(),
  2232. uint64_t TBAAOffset = 0,
  2233. bool isNontemporal = false);
  2234. /// EmitLoadOfScalar - Load a scalar value from an address, taking
  2235. /// care to appropriately convert from the memory representation to
  2236. /// the LLVM value representation. The l-value must be a simple
  2237. /// l-value.
  2238. llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc);
  2239. /// EmitStoreOfScalar - Store a scalar value to an address, taking
  2240. /// care to appropriately convert from the memory representation to
  2241. /// the LLVM value representation.
  2242. void EmitStoreOfScalar(llvm::Value *Value, Address Addr,
  2243. bool Volatile, QualType Ty,
  2244. AlignmentSource AlignSource = AlignmentSource::Type,
  2245. llvm::MDNode *TBAAInfo = nullptr, bool isInit = false,
  2246. QualType TBAABaseTy = QualType(),
  2247. uint64_t TBAAOffset = 0, bool isNontemporal = false);
  2248. /// EmitStoreOfScalar - Store a scalar value to an address, taking
  2249. /// care to appropriately convert from the memory representation to
  2250. /// the LLVM value representation. The l-value must be a simple
  2251. /// l-value. The isInit flag indicates whether this is an initialization.
  2252. /// If so, atomic qualifiers are ignored and the store is always non-atomic.
  2253. void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false);
  2254. /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
  2255. /// this method emits the address of the lvalue, then loads the result as an
  2256. /// rvalue, returning the rvalue.
  2257. RValue EmitLoadOfLValue(LValue V, SourceLocation Loc);
  2258. RValue EmitLoadOfExtVectorElementLValue(LValue V);
  2259. RValue EmitLoadOfBitfieldLValue(LValue LV);
  2260. RValue EmitLoadOfGlobalRegLValue(LValue LV);
  2261. /// EmitStoreThroughLValue - Store the specified rvalue into the specified
  2262. /// lvalue, where both are guaranteed to the have the same type, and that type
  2263. /// is 'Ty'.
  2264. void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit = false);
  2265. void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst);
  2266. void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst);
  2267. /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints
  2268. /// as EmitStoreThroughLValue.
  2269. ///
  2270. /// \param Result [out] - If non-null, this will be set to a Value* for the
  2271. /// bit-field contents after the store, appropriate for use as the result of
  2272. /// an assignment to the bit-field.
  2273. void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
  2274. llvm::Value **Result=nullptr);
  2275. /// Emit an l-value for an assignment (simple or compound) of complex type.
  2276. LValue EmitComplexAssignmentLValue(const BinaryOperator *E);
  2277. LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E);
  2278. LValue EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E,
  2279. llvm::Value *&Result);
  2280. // Note: only available for agg return types
  2281. LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
  2282. LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E);
  2283. // Note: only available for agg return types
  2284. LValue EmitCallExprLValue(const CallExpr *E);
  2285. // Note: only available for agg return types
  2286. LValue EmitVAArgExprLValue(const VAArgExpr *E);
  2287. LValue EmitDeclRefLValue(const DeclRefExpr *E);
  2288. LValue EmitStringLiteralLValue(const StringLiteral *E);
  2289. LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
  2290. LValue EmitPredefinedLValue(const PredefinedExpr *E);
  2291. LValue EmitUnaryOpLValue(const UnaryOperator *E);
  2292. LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
  2293. bool Accessed = false);
  2294. LValue EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
  2295. bool IsLowerBound = true);
  2296. LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
  2297. LValue EmitMemberExpr(const MemberExpr *E);
  2298. LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
  2299. LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
  2300. LValue EmitInitListLValue(const InitListExpr *E);
  2301. LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E);
  2302. LValue EmitCastLValue(const CastExpr *E);
  2303. LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
  2304. LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e);
  2305. Address EmitExtVectorElementLValue(LValue V);
  2306. RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc);
  2307. Address EmitArrayToPointerDecay(const Expr *Array,
  2308. AlignmentSource *AlignSource = nullptr);
  2309. class ConstantEmission {
  2310. llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference;
  2311. ConstantEmission(llvm::Constant *C, bool isReference)
  2312. : ValueAndIsReference(C, isReference) {}
  2313. public:
  2314. ConstantEmission() {}
  2315. static ConstantEmission forReference(llvm::Constant *C) {
  2316. return ConstantEmission(C, true);
  2317. }
  2318. static ConstantEmission forValue(llvm::Constant *C) {
  2319. return ConstantEmission(C, false);
  2320. }
  2321. explicit operator bool() const {
  2322. return ValueAndIsReference.getOpaqueValue() != nullptr;
  2323. }
  2324. bool isReference() const { return ValueAndIsReference.getInt(); }
  2325. LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const {
  2326. assert(isReference());
  2327. return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(),
  2328. refExpr->getType());
  2329. }
  2330. llvm::Constant *getValue() const {
  2331. assert(!isReference());
  2332. return ValueAndIsReference.getPointer();
  2333. }
  2334. };
  2335. ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr);
  2336. RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e,
  2337. AggValueSlot slot = AggValueSlot::ignored());
  2338. LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e);
  2339. llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
  2340. const ObjCIvarDecl *Ivar);
  2341. LValue EmitLValueForField(LValue Base, const FieldDecl* Field);
  2342. LValue EmitLValueForLambdaField(const FieldDecl *Field);
  2343. /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
  2344. /// if the Field is a reference, this will return the address of the reference
  2345. /// and not the address of the value stored in the reference.
  2346. LValue EmitLValueForFieldInitialization(LValue Base,
  2347. const FieldDecl* Field);
  2348. LValue EmitLValueForIvar(QualType ObjectTy,
  2349. llvm::Value* Base, const ObjCIvarDecl *Ivar,
  2350. unsigned CVRQualifiers);
  2351. LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
  2352. LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
  2353. LValue EmitLambdaLValue(const LambdaExpr *E);
  2354. LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
  2355. LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E);
  2356. LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
  2357. LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
  2358. LValue EmitStmtExprLValue(const StmtExpr *E);
  2359. LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
  2360. LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
  2361. void EmitDeclRefExprDbgValue(const DeclRefExpr *E, llvm::Constant *Init);
  2362. //===--------------------------------------------------------------------===//
  2363. // Scalar Expression Emission
  2364. //===--------------------------------------------------------------------===//
  2365. /// EmitCall - Generate a call of the given function, expecting the given
  2366. /// result type, and using the given argument list which specifies both the
  2367. /// LLVM arguments and the types they were derived from.
  2368. RValue EmitCall(const CGFunctionInfo &FnInfo, llvm::Value *Callee,
  2369. ReturnValueSlot ReturnValue, const CallArgList &Args,
  2370. CGCalleeInfo CalleeInfo = CGCalleeInfo(),
  2371. llvm::Instruction **callOrInvoke = nullptr);
  2372. RValue EmitCall(QualType FnType, llvm::Value *Callee, const CallExpr *E,
  2373. ReturnValueSlot ReturnValue,
  2374. CGCalleeInfo CalleeInfo = CGCalleeInfo(),
  2375. llvm::Value *Chain = nullptr);
  2376. RValue EmitCallExpr(const CallExpr *E,
  2377. ReturnValueSlot ReturnValue = ReturnValueSlot());
  2378. void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl);
  2379. llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
  2380. const Twine &name = "");
  2381. llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
  2382. ArrayRef<llvm::Value*> args,
  2383. const Twine &name = "");
  2384. llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
  2385. const Twine &name = "");
  2386. llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
  2387. ArrayRef<llvm::Value*> args,
  2388. const Twine &name = "");
  2389. llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
  2390. ArrayRef<llvm::Value *> Args,
  2391. const Twine &Name = "");
  2392. llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
  2393. ArrayRef<llvm::Value*> args,
  2394. const Twine &name = "");
  2395. llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
  2396. const Twine &name = "");
  2397. void EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
  2398. ArrayRef<llvm::Value*> args);
  2399. llvm::Value *BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
  2400. NestedNameSpecifier *Qual,
  2401. llvm::Type *Ty);
  2402. llvm::Value *BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD,
  2403. CXXDtorType Type,
  2404. const CXXRecordDecl *RD);
  2405. RValue
  2406. EmitCXXMemberOrOperatorCall(const CXXMethodDecl *MD, llvm::Value *Callee,
  2407. ReturnValueSlot ReturnValue, llvm::Value *This,
  2408. llvm::Value *ImplicitParam,
  2409. QualType ImplicitParamTy, const CallExpr *E);
  2410. RValue EmitCXXDestructorCall(const CXXDestructorDecl *DD, llvm::Value *Callee,
  2411. llvm::Value *This, llvm::Value *ImplicitParam,
  2412. QualType ImplicitParamTy, const CallExpr *E,
  2413. StructorType Type);
  2414. RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
  2415. ReturnValueSlot ReturnValue);
  2416. RValue EmitCXXMemberOrOperatorMemberCallExpr(const CallExpr *CE,
  2417. const CXXMethodDecl *MD,
  2418. ReturnValueSlot ReturnValue,
  2419. bool HasQualifier,
  2420. NestedNameSpecifier *Qualifier,
  2421. bool IsArrow, const Expr *Base);
  2422. // Compute the object pointer.
  2423. Address EmitCXXMemberDataPointerAddress(const Expr *E, Address base,
  2424. llvm::Value *memberPtr,
  2425. const MemberPointerType *memberPtrType,
  2426. AlignmentSource *AlignSource = nullptr);
  2427. RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
  2428. ReturnValueSlot ReturnValue);
  2429. RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
  2430. const CXXMethodDecl *MD,
  2431. ReturnValueSlot ReturnValue);
  2432. RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
  2433. ReturnValueSlot ReturnValue);
  2434. RValue EmitCUDADevicePrintfCallExpr(const CallExpr *E,
  2435. ReturnValueSlot ReturnValue);
  2436. RValue EmitBuiltinExpr(const FunctionDecl *FD,
  2437. unsigned BuiltinID, const CallExpr *E,
  2438. ReturnValueSlot ReturnValue);
  2439. RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
  2440. /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
  2441. /// is unhandled by the current target.
  2442. llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2443. llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty,
  2444. const llvm::CmpInst::Predicate Fp,
  2445. const llvm::CmpInst::Predicate Ip,
  2446. const llvm::Twine &Name = "");
  2447. llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2448. llvm::Value *EmitCommonNeonBuiltinExpr(unsigned BuiltinID,
  2449. unsigned LLVMIntrinsic,
  2450. unsigned AltLLVMIntrinsic,
  2451. const char *NameHint,
  2452. unsigned Modifier,
  2453. const CallExpr *E,
  2454. SmallVectorImpl<llvm::Value *> &Ops,
  2455. Address PtrOp0, Address PtrOp1);
  2456. llvm::Function *LookupNeonLLVMIntrinsic(unsigned IntrinsicID,
  2457. unsigned Modifier, llvm::Type *ArgTy,
  2458. const CallExpr *E);
  2459. llvm::Value *EmitNeonCall(llvm::Function *F,
  2460. SmallVectorImpl<llvm::Value*> &O,
  2461. const char *name,
  2462. unsigned shift = 0, bool rightshift = false);
  2463. llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx);
  2464. llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty,
  2465. bool negateForRightShift);
  2466. llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt,
  2467. llvm::Type *Ty, bool usgn, const char *name);
  2468. llvm::Value *vectorWrapScalar16(llvm::Value *Op);
  2469. llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2470. llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops);
  2471. llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2472. llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2473. llvm::Value *EmitAMDGPUBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2474. llvm::Value *EmitSystemZBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2475. llvm::Value *EmitNVPTXBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2476. llvm::Value *EmitWebAssemblyBuiltinExpr(unsigned BuiltinID,
  2477. const CallExpr *E);
  2478. llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
  2479. llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
  2480. llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E);
  2481. llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E);
  2482. llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E);
  2483. llvm::Value *EmitObjCCollectionLiteral(const Expr *E,
  2484. const ObjCMethodDecl *MethodWithObjects);
  2485. llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
  2486. RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
  2487. ReturnValueSlot Return = ReturnValueSlot());
  2488. /// Retrieves the default cleanup kind for an ARC cleanup.
  2489. /// Except under -fobjc-arc-eh, ARC cleanups are normal-only.
  2490. CleanupKind getARCCleanupKind() {
  2491. return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions
  2492. ? NormalAndEHCleanup : NormalCleanup;
  2493. }
  2494. // ARC primitives.
  2495. void EmitARCInitWeak(Address addr, llvm::Value *value);
  2496. void EmitARCDestroyWeak(Address addr);
  2497. llvm::Value *EmitARCLoadWeak(Address addr);
  2498. llvm::Value *EmitARCLoadWeakRetained(Address addr);
  2499. llvm::Value *EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored);
  2500. void EmitARCCopyWeak(Address dst, Address src);
  2501. void EmitARCMoveWeak(Address dst, Address src);
  2502. llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value);
  2503. llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value);
  2504. llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value,
  2505. bool resultIgnored);
  2506. llvm::Value *EmitARCStoreStrongCall(Address addr, llvm::Value *value,
  2507. bool resultIgnored);
  2508. llvm::Value *EmitARCRetain(QualType type, llvm::Value *value);
  2509. llvm::Value *EmitARCRetainNonBlock(llvm::Value *value);
  2510. llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory);
  2511. void EmitARCDestroyStrong(Address addr, ARCPreciseLifetime_t precise);
  2512. void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise);
  2513. llvm::Value *EmitARCAutorelease(llvm::Value *value);
  2514. llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value);
  2515. llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value);
  2516. llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value);
  2517. llvm::Value *EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value);
  2518. std::pair<LValue,llvm::Value*>
  2519. EmitARCStoreAutoreleasing(const BinaryOperator *e);
  2520. std::pair<LValue,llvm::Value*>
  2521. EmitARCStoreStrong(const BinaryOperator *e, bool ignored);
  2522. std::pair<LValue,llvm::Value*>
  2523. EmitARCStoreUnsafeUnretained(const BinaryOperator *e, bool ignored);
  2524. llvm::Value *EmitObjCThrowOperand(const Expr *expr);
  2525. llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr);
  2526. llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr);
  2527. llvm::Value *EmitARCExtendBlockObject(const Expr *expr);
  2528. llvm::Value *EmitARCReclaimReturnedObject(const Expr *e,
  2529. bool allowUnsafeClaim);
  2530. llvm::Value *EmitARCRetainScalarExpr(const Expr *expr);
  2531. llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr);
  2532. llvm::Value *EmitARCUnsafeUnretainedScalarExpr(const Expr *expr);
  2533. void EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values);
  2534. static Destroyer destroyARCStrongImprecise;
  2535. static Destroyer destroyARCStrongPrecise;
  2536. static Destroyer destroyARCWeak;
  2537. void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr);
  2538. llvm::Value *EmitObjCAutoreleasePoolPush();
  2539. llvm::Value *EmitObjCMRRAutoreleasePoolPush();
  2540. void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr);
  2541. void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr);
  2542. /// \brief Emits a reference binding to the passed in expression.
  2543. RValue EmitReferenceBindingToExpr(const Expr *E);
  2544. //===--------------------------------------------------------------------===//
  2545. // Expression Emission
  2546. //===--------------------------------------------------------------------===//
  2547. // Expressions are broken into three classes: scalar, complex, aggregate.
  2548. /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
  2549. /// scalar type, returning the result.
  2550. llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
  2551. /// Emit a conversion from the specified type to the specified destination
  2552. /// type, both of which are LLVM scalar types.
  2553. llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
  2554. QualType DstTy, SourceLocation Loc);
  2555. /// Emit a conversion from the specified complex type to the specified
  2556. /// destination type, where the destination type is an LLVM scalar type.
  2557. llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
  2558. QualType DstTy,
  2559. SourceLocation Loc);
  2560. /// EmitAggExpr - Emit the computation of the specified expression
  2561. /// of aggregate type. The result is computed into the given slot,
  2562. /// which may be null to indicate that the value is not needed.
  2563. void EmitAggExpr(const Expr *E, AggValueSlot AS);
  2564. /// EmitAggExprToLValue - Emit the computation of the specified expression of
  2565. /// aggregate type into a temporary LValue.
  2566. LValue EmitAggExprToLValue(const Expr *E);
  2567. /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
  2568. /// make sure it survives garbage collection until this point.
  2569. void EmitExtendGCLifetime(llvm::Value *object);
  2570. /// EmitComplexExpr - Emit the computation of the specified expression of
  2571. /// complex type, returning the result.
  2572. ComplexPairTy EmitComplexExpr(const Expr *E,
  2573. bool IgnoreReal = false,
  2574. bool IgnoreImag = false);
  2575. /// EmitComplexExprIntoLValue - Emit the given expression of complex
  2576. /// type and place its result into the specified l-value.
  2577. void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit);
  2578. /// EmitStoreOfComplex - Store a complex number into the specified l-value.
  2579. void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit);
  2580. /// EmitLoadOfComplex - Load a complex number from the specified l-value.
  2581. ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc);
  2582. Address emitAddrOfRealComponent(Address complex, QualType complexType);
  2583. Address emitAddrOfImagComponent(Address complex, QualType complexType);
  2584. /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
  2585. /// global variable that has already been created for it. If the initializer
  2586. /// has a different type than GV does, this may free GV and return a different
  2587. /// one. Otherwise it just returns GV.
  2588. llvm::GlobalVariable *
  2589. AddInitializerToStaticVarDecl(const VarDecl &D,
  2590. llvm::GlobalVariable *GV);
  2591. /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
  2592. /// variable with global storage.
  2593. void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr,
  2594. bool PerformInit);
  2595. llvm::Constant *createAtExitStub(const VarDecl &VD, llvm::Constant *Dtor,
  2596. llvm::Constant *Addr);
  2597. /// Call atexit() with a function that passes the given argument to
  2598. /// the given function.
  2599. void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::Constant *fn,
  2600. llvm::Constant *addr);
  2601. /// Emit code in this function to perform a guarded variable
  2602. /// initialization. Guarded initializations are used when it's not
  2603. /// possible to prove that an initialization will be done exactly
  2604. /// once, e.g. with a static local variable or a static data member
  2605. /// of a class template.
  2606. void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr,
  2607. bool PerformInit);
  2608. /// GenerateCXXGlobalInitFunc - Generates code for initializing global
  2609. /// variables.
  2610. void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
  2611. ArrayRef<llvm::Function *> CXXThreadLocals,
  2612. Address Guard = Address::invalid());
  2613. /// GenerateCXXGlobalDtorsFunc - Generates code for destroying global
  2614. /// variables.
  2615. void GenerateCXXGlobalDtorsFunc(llvm::Function *Fn,
  2616. const std::vector<std::pair<llvm::WeakVH,
  2617. llvm::Constant*> > &DtorsAndObjects);
  2618. void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
  2619. const VarDecl *D,
  2620. llvm::GlobalVariable *Addr,
  2621. bool PerformInit);
  2622. void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
  2623. void EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, const Expr *Exp);
  2624. void enterFullExpression(const ExprWithCleanups *E) {
  2625. if (E->getNumObjects() == 0) return;
  2626. enterNonTrivialFullExpression(E);
  2627. }
  2628. void enterNonTrivialFullExpression(const ExprWithCleanups *E);
  2629. void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true);
  2630. void EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Dest);
  2631. RValue EmitAtomicExpr(AtomicExpr *E);
  2632. //===--------------------------------------------------------------------===//
  2633. // Annotations Emission
  2634. //===--------------------------------------------------------------------===//
  2635. /// Emit an annotation call (intrinsic or builtin).
  2636. llvm::Value *EmitAnnotationCall(llvm::Value *AnnotationFn,
  2637. llvm::Value *AnnotatedVal,
  2638. StringRef AnnotationStr,
  2639. SourceLocation Location);
  2640. /// Emit local annotations for the local variable V, declared by D.
  2641. void EmitVarAnnotations(const VarDecl *D, llvm::Value *V);
  2642. /// Emit field annotations for the given field & value. Returns the
  2643. /// annotation result.
  2644. Address EmitFieldAnnotations(const FieldDecl *D, Address V);
  2645. //===--------------------------------------------------------------------===//
  2646. // Internal Helpers
  2647. //===--------------------------------------------------------------------===//
  2648. /// ContainsLabel - Return true if the statement contains a label in it. If
  2649. /// this statement is not executed normally, it not containing a label means
  2650. /// that we can just remove the code.
  2651. static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
  2652. /// containsBreak - Return true if the statement contains a break out of it.
  2653. /// If the statement (recursively) contains a switch or loop with a break
  2654. /// inside of it, this is fine.
  2655. static bool containsBreak(const Stmt *S);
  2656. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  2657. /// to a constant, or if it does but contains a label, return false. If it
  2658. /// constant folds return true and set the boolean result in Result.
  2659. bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result,
  2660. bool AllowLabels = false);
  2661. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  2662. /// to a constant, or if it does but contains a label, return false. If it
  2663. /// constant folds return true and set the folded value.
  2664. bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result,
  2665. bool AllowLabels = false);
  2666. /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
  2667. /// if statement) to the specified blocks. Based on the condition, this might
  2668. /// try to simplify the codegen of the conditional based on the branch.
  2669. /// TrueCount should be the number of times we expect the condition to
  2670. /// evaluate to true based on PGO data.
  2671. void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
  2672. llvm::BasicBlock *FalseBlock, uint64_t TrueCount);
  2673. /// \brief Emit a description of a type in a format suitable for passing to
  2674. /// a runtime sanitizer handler.
  2675. llvm::Constant *EmitCheckTypeDescriptor(QualType T);
  2676. /// \brief Convert a value into a format suitable for passing to a runtime
  2677. /// sanitizer handler.
  2678. llvm::Value *EmitCheckValue(llvm::Value *V);
  2679. /// \brief Emit a description of a source location in a format suitable for
  2680. /// passing to a runtime sanitizer handler.
  2681. llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc);
  2682. /// \brief Create a basic block that will call a handler function in a
  2683. /// sanitizer runtime with the provided arguments, and create a conditional
  2684. /// branch to it.
  2685. void EmitCheck(ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
  2686. StringRef CheckName, ArrayRef<llvm::Constant *> StaticArgs,
  2687. ArrayRef<llvm::Value *> DynamicArgs);
  2688. /// \brief Emit a slow path cross-DSO CFI check which calls __cfi_slowpath
  2689. /// if Cond if false.
  2690. void EmitCfiSlowPathCheck(SanitizerMask Kind, llvm::Value *Cond,
  2691. llvm::ConstantInt *TypeId, llvm::Value *Ptr,
  2692. ArrayRef<llvm::Constant *> StaticArgs);
  2693. /// \brief Create a basic block that will call the trap intrinsic, and emit a
  2694. /// conditional branch to it, for the -ftrapv checks.
  2695. void EmitTrapCheck(llvm::Value *Checked);
  2696. /// \brief Emit a call to trap or debugtrap and attach function attribute
  2697. /// "trap-func-name" if specified.
  2698. llvm::CallInst *EmitTrapCall(llvm::Intrinsic::ID IntrID);
  2699. /// \brief Emit a cross-DSO CFI failure handling function.
  2700. void EmitCfiCheckFail();
  2701. /// \brief Create a check for a function parameter that may potentially be
  2702. /// declared as non-null.
  2703. void EmitNonNullArgCheck(RValue RV, QualType ArgType, SourceLocation ArgLoc,
  2704. const FunctionDecl *FD, unsigned ParmNum);
  2705. /// EmitCallArg - Emit a single call argument.
  2706. void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType);
  2707. /// EmitDelegateCallArg - We are performing a delegate call; that
  2708. /// is, the current function is delegating to another one. Produce
  2709. /// a r-value suitable for passing the given parameter.
  2710. void EmitDelegateCallArg(CallArgList &args, const VarDecl *param,
  2711. SourceLocation loc);
  2712. /// SetFPAccuracy - Set the minimum required accuracy of the given floating
  2713. /// point operation, expressed as the maximum relative error in ulp.
  2714. void SetFPAccuracy(llvm::Value *Val, float Accuracy);
  2715. private:
  2716. llvm::MDNode *getRangeForLoadFromType(QualType Ty);
  2717. void EmitReturnOfRValue(RValue RV, QualType Ty);
  2718. void deferPlaceholderReplacement(llvm::Instruction *Old, llvm::Value *New);
  2719. llvm::SmallVector<std::pair<llvm::Instruction *, llvm::Value *>, 4>
  2720. DeferredReplacements;
  2721. /// Set the address of a local variable.
  2722. void setAddrOfLocalVar(const VarDecl *VD, Address Addr) {
  2723. assert(!LocalDeclMap.count(VD) && "Decl already exists in LocalDeclMap!");
  2724. LocalDeclMap.insert({VD, Addr});
  2725. }
  2726. /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
  2727. /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
  2728. ///
  2729. /// \param AI - The first function argument of the expansion.
  2730. void ExpandTypeFromArgs(QualType Ty, LValue Dst,
  2731. SmallVectorImpl<llvm::Value *>::iterator &AI);
  2732. /// ExpandTypeToArgs - Expand an RValue \arg RV, with the LLVM type for \arg
  2733. /// Ty, into individual arguments on the provided vector \arg IRCallArgs,
  2734. /// starting at index \arg IRCallArgPos. See ABIArgInfo::Expand.
  2735. void ExpandTypeToArgs(QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
  2736. SmallVectorImpl<llvm::Value *> &IRCallArgs,
  2737. unsigned &IRCallArgPos);
  2738. llvm::Value* EmitAsmInput(const TargetInfo::ConstraintInfo &Info,
  2739. const Expr *InputExpr, std::string &ConstraintStr);
  2740. llvm::Value* EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
  2741. LValue InputValue, QualType InputType,
  2742. std::string &ConstraintStr,
  2743. SourceLocation Loc);
  2744. /// \brief Attempts to statically evaluate the object size of E. If that
  2745. /// fails, emits code to figure the size of E out for us. This is
  2746. /// pass_object_size aware.
  2747. llvm::Value *evaluateOrEmitBuiltinObjectSize(const Expr *E, unsigned Type,
  2748. llvm::IntegerType *ResType);
  2749. /// \brief Emits the size of E, as required by __builtin_object_size. This
  2750. /// function is aware of pass_object_size parameters, and will act accordingly
  2751. /// if E is a parameter with the pass_object_size attribute.
  2752. llvm::Value *emitBuiltinObjectSize(const Expr *E, unsigned Type,
  2753. llvm::IntegerType *ResType);
  2754. public:
  2755. #ifndef NDEBUG
  2756. // Determine whether the given argument is an Objective-C method
  2757. // that may have type parameters in its signature.
  2758. static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) {
  2759. const DeclContext *dc = method->getDeclContext();
  2760. if (const ObjCInterfaceDecl *classDecl= dyn_cast<ObjCInterfaceDecl>(dc)) {
  2761. return classDecl->getTypeParamListAsWritten();
  2762. }
  2763. if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) {
  2764. return catDecl->getTypeParamList();
  2765. }
  2766. return false;
  2767. }
  2768. template<typename T>
  2769. static bool isObjCMethodWithTypeParams(const T *) { return false; }
  2770. #endif
  2771. /// EmitCallArgs - Emit call arguments for a function.
  2772. template <typename T>
  2773. void EmitCallArgs(CallArgList &Args, const T *CallArgTypeInfo,
  2774. llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
  2775. const FunctionDecl *CalleeDecl = nullptr,
  2776. unsigned ParamsToSkip = 0) {
  2777. SmallVector<QualType, 16> ArgTypes;
  2778. CallExpr::const_arg_iterator Arg = ArgRange.begin();
  2779. assert((ParamsToSkip == 0 || CallArgTypeInfo) &&
  2780. "Can't skip parameters if type info is not provided");
  2781. if (CallArgTypeInfo) {
  2782. #ifndef NDEBUG
  2783. bool isGenericMethod = isObjCMethodWithTypeParams(CallArgTypeInfo);
  2784. #endif
  2785. // First, use the argument types that the type info knows about
  2786. for (auto I = CallArgTypeInfo->param_type_begin() + ParamsToSkip,
  2787. E = CallArgTypeInfo->param_type_end();
  2788. I != E; ++I, ++Arg) {
  2789. assert(Arg != ArgRange.end() && "Running over edge of argument list!");
  2790. assert((isGenericMethod ||
  2791. ((*I)->isVariablyModifiedType() ||
  2792. (*I).getNonReferenceType()->isObjCRetainableType() ||
  2793. getContext()
  2794. .getCanonicalType((*I).getNonReferenceType())
  2795. .getTypePtr() ==
  2796. getContext()
  2797. .getCanonicalType((*Arg)->getType())
  2798. .getTypePtr())) &&
  2799. "type mismatch in call argument!");
  2800. ArgTypes.push_back(*I);
  2801. }
  2802. }
  2803. // Either we've emitted all the call args, or we have a call to variadic
  2804. // function.
  2805. assert((Arg == ArgRange.end() || !CallArgTypeInfo ||
  2806. CallArgTypeInfo->isVariadic()) &&
  2807. "Extra arguments in non-variadic function!");
  2808. // If we still have any arguments, emit them using the type of the argument.
  2809. for (auto *A : llvm::make_range(Arg, ArgRange.end()))
  2810. ArgTypes.push_back(getVarArgType(A));
  2811. EmitCallArgs(Args, ArgTypes, ArgRange, CalleeDecl, ParamsToSkip);
  2812. }
  2813. void EmitCallArgs(CallArgList &Args, ArrayRef<QualType> ArgTypes,
  2814. llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
  2815. const FunctionDecl *CalleeDecl = nullptr,
  2816. unsigned ParamsToSkip = 0);
  2817. /// EmitPointerWithAlignment - Given an expression with a pointer
  2818. /// type, emit the value and compute our best estimate of the
  2819. /// alignment of the pointee.
  2820. ///
  2821. /// Note that this function will conservatively fall back on the type
  2822. /// when it doesn't
  2823. ///
  2824. /// \param Source - If non-null, this will be initialized with
  2825. /// information about the source of the alignment. Note that this
  2826. /// function will conservatively fall back on the type when it
  2827. /// doesn't recognize the expression, which means that sometimes
  2828. ///
  2829. /// a worst-case One
  2830. /// reasonable way to use this information is when there's a
  2831. /// language guarantee that the pointer must be aligned to some
  2832. /// stricter value, and we're simply trying to ensure that
  2833. /// sufficiently obvious uses of under-aligned objects don't get
  2834. /// miscompiled; for example, a placement new into the address of
  2835. /// a local variable. In such a case, it's quite reasonable to
  2836. /// just ignore the returned alignment when it isn't from an
  2837. /// explicit source.
  2838. Address EmitPointerWithAlignment(const Expr *Addr,
  2839. AlignmentSource *Source = nullptr);
  2840. void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK);
  2841. private:
  2842. QualType getVarArgType(const Expr *Arg);
  2843. const TargetCodeGenInfo &getTargetHooks() const {
  2844. return CGM.getTargetCodeGenInfo();
  2845. }
  2846. void EmitDeclMetadata();
  2847. BlockByrefHelpers *buildByrefHelpers(llvm::StructType &byrefType,
  2848. const AutoVarEmission &emission);
  2849. void AddObjCARCExceptionMetadata(llvm::Instruction *Inst);
  2850. llvm::Value *GetValueForARMHint(unsigned BuiltinID);
  2851. };
  2852. /// Helper class with most of the code for saving a value for a
  2853. /// conditional expression cleanup.
  2854. struct DominatingLLVMValue {
  2855. typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type;
  2856. /// Answer whether the given value needs extra work to be saved.
  2857. static bool needsSaving(llvm::Value *value) {
  2858. // If it's not an instruction, we don't need to save.
  2859. if (!isa<llvm::Instruction>(value)) return false;
  2860. // If it's an instruction in the entry block, we don't need to save.
  2861. llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent();
  2862. return (block != &block->getParent()->getEntryBlock());
  2863. }
  2864. /// Try to save the given value.
  2865. static saved_type save(CodeGenFunction &CGF, llvm::Value *value) {
  2866. if (!needsSaving(value)) return saved_type(value, false);
  2867. // Otherwise, we need an alloca.
  2868. auto align = CharUnits::fromQuantity(
  2869. CGF.CGM.getDataLayout().getPrefTypeAlignment(value->getType()));
  2870. Address alloca =
  2871. CGF.CreateTempAlloca(value->getType(), align, "cond-cleanup.save");
  2872. CGF.Builder.CreateStore(value, alloca);
  2873. return saved_type(alloca.getPointer(), true);
  2874. }
  2875. static llvm::Value *restore(CodeGenFunction &CGF, saved_type value) {
  2876. // If the value says it wasn't saved, trust that it's still dominating.
  2877. if (!value.getInt()) return value.getPointer();
  2878. // Otherwise, it should be an alloca instruction, as set up in save().
  2879. auto alloca = cast<llvm::AllocaInst>(value.getPointer());
  2880. return CGF.Builder.CreateAlignedLoad(alloca, alloca->getAlignment());
  2881. }
  2882. };
  2883. /// A partial specialization of DominatingValue for llvm::Values that
  2884. /// might be llvm::Instructions.
  2885. template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue {
  2886. typedef T *type;
  2887. static type restore(CodeGenFunction &CGF, saved_type value) {
  2888. return static_cast<T*>(DominatingLLVMValue::restore(CGF, value));
  2889. }
  2890. };
  2891. /// A specialization of DominatingValue for Address.
  2892. template <> struct DominatingValue<Address> {
  2893. typedef Address type;
  2894. struct saved_type {
  2895. DominatingLLVMValue::saved_type SavedValue;
  2896. CharUnits Alignment;
  2897. };
  2898. static bool needsSaving(type value) {
  2899. return DominatingLLVMValue::needsSaving(value.getPointer());
  2900. }
  2901. static saved_type save(CodeGenFunction &CGF, type value) {
  2902. return { DominatingLLVMValue::save(CGF, value.getPointer()),
  2903. value.getAlignment() };
  2904. }
  2905. static type restore(CodeGenFunction &CGF, saved_type value) {
  2906. return Address(DominatingLLVMValue::restore(CGF, value.SavedValue),
  2907. value.Alignment);
  2908. }
  2909. };
  2910. /// A specialization of DominatingValue for RValue.
  2911. template <> struct DominatingValue<RValue> {
  2912. typedef RValue type;
  2913. class saved_type {
  2914. enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral,
  2915. AggregateAddress, ComplexAddress };
  2916. llvm::Value *Value;
  2917. unsigned K : 3;
  2918. unsigned Align : 29;
  2919. saved_type(llvm::Value *v, Kind k, unsigned a = 0)
  2920. : Value(v), K(k), Align(a) {}
  2921. public:
  2922. static bool needsSaving(RValue value);
  2923. static saved_type save(CodeGenFunction &CGF, RValue value);
  2924. RValue restore(CodeGenFunction &CGF);
  2925. // implementations in CGCleanup.cpp
  2926. };
  2927. static bool needsSaving(type value) {
  2928. return saved_type::needsSaving(value);
  2929. }
  2930. static saved_type save(CodeGenFunction &CGF, type value) {
  2931. return saved_type::save(CGF, value);
  2932. }
  2933. static type restore(CodeGenFunction &CGF, saved_type value) {
  2934. return value.restore(CGF);
  2935. }
  2936. };
  2937. } // end namespace CodeGen
  2938. } // end namespace clang
  2939. #endif