CodeGenFunction.h 138 KB

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