CodeGenFunction.h 149 KB

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