CodeGenFunction.h 171 KB

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