CodeGenFunction.h 132 KB

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