CodeGenFunction.h 184 KB

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