CodeGenFunction.h 149 KB

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