CodeGenFunction.h 179 KB

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