CodeGenFunction.h 187 KB

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