CodeGenFunction.h 176 KB

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