CGDecl.cpp 105 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719
  1. //===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
  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 contains code to emit Decl nodes as LLVM code.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CGBlocks.h"
  13. #include "CGCXXABI.h"
  14. #include "CGCleanup.h"
  15. #include "CGDebugInfo.h"
  16. #include "CGOpenCLRuntime.h"
  17. #include "CGOpenMPRuntime.h"
  18. #include "CodeGenFunction.h"
  19. #include "CodeGenModule.h"
  20. #include "ConstantEmitter.h"
  21. #include "PatternInit.h"
  22. #include "TargetInfo.h"
  23. #include "clang/AST/ASTContext.h"
  24. #include "clang/AST/Attr.h"
  25. #include "clang/AST/CharUnits.h"
  26. #include "clang/AST/Decl.h"
  27. #include "clang/AST/DeclObjC.h"
  28. #include "clang/AST/DeclOpenMP.h"
  29. #include "clang/Basic/CodeGenOptions.h"
  30. #include "clang/Basic/SourceManager.h"
  31. #include "clang/Basic/TargetInfo.h"
  32. #include "clang/CodeGen/CGFunctionInfo.h"
  33. #include "clang/Sema/Sema.h"
  34. #include "llvm/Analysis/ValueTracking.h"
  35. #include "llvm/IR/DataLayout.h"
  36. #include "llvm/IR/GlobalVariable.h"
  37. #include "llvm/IR/Intrinsics.h"
  38. #include "llvm/IR/Type.h"
  39. #include <optional>
  40. using namespace clang;
  41. using namespace CodeGen;
  42. static_assert(clang::Sema::MaximumAlignment <= llvm::Value::MaximumAlignment,
  43. "Clang max alignment greater than what LLVM supports?");
  44. void CodeGenFunction::EmitDecl(const Decl &D) {
  45. switch (D.getKind()) {
  46. case Decl::BuiltinTemplate:
  47. case Decl::TranslationUnit:
  48. case Decl::ExternCContext:
  49. case Decl::Namespace:
  50. case Decl::UnresolvedUsingTypename:
  51. case Decl::ClassTemplateSpecialization:
  52. case Decl::ClassTemplatePartialSpecialization:
  53. case Decl::VarTemplateSpecialization:
  54. case Decl::VarTemplatePartialSpecialization:
  55. case Decl::TemplateTypeParm:
  56. case Decl::UnresolvedUsingValue:
  57. case Decl::NonTypeTemplateParm:
  58. case Decl::CXXDeductionGuide:
  59. case Decl::CXXMethod:
  60. case Decl::CXXConstructor:
  61. case Decl::CXXDestructor:
  62. case Decl::CXXConversion:
  63. case Decl::Field:
  64. case Decl::MSProperty:
  65. case Decl::IndirectField:
  66. case Decl::ObjCIvar:
  67. case Decl::ObjCAtDefsField:
  68. case Decl::ParmVar:
  69. case Decl::ImplicitParam:
  70. case Decl::ClassTemplate:
  71. case Decl::VarTemplate:
  72. case Decl::FunctionTemplate:
  73. case Decl::TypeAliasTemplate:
  74. case Decl::TemplateTemplateParm:
  75. case Decl::ObjCMethod:
  76. case Decl::ObjCCategory:
  77. case Decl::ObjCProtocol:
  78. case Decl::ObjCInterface:
  79. case Decl::ObjCCategoryImpl:
  80. case Decl::ObjCImplementation:
  81. case Decl::ObjCProperty:
  82. case Decl::ObjCCompatibleAlias:
  83. case Decl::PragmaComment:
  84. case Decl::PragmaDetectMismatch:
  85. case Decl::AccessSpec:
  86. case Decl::LinkageSpec:
  87. case Decl::Export:
  88. case Decl::ObjCPropertyImpl:
  89. case Decl::FileScopeAsm:
  90. case Decl::TopLevelStmt:
  91. case Decl::Friend:
  92. case Decl::FriendTemplate:
  93. case Decl::Block:
  94. case Decl::Captured:
  95. case Decl::ClassScopeFunctionSpecialization:
  96. case Decl::UsingShadow:
  97. case Decl::ConstructorUsingShadow:
  98. case Decl::ObjCTypeParam:
  99. case Decl::Binding:
  100. case Decl::UnresolvedUsingIfExists:
  101. case Decl::HLSLBuffer:
  102. llvm_unreachable("Declaration should not be in declstmts!");
  103. case Decl::Record: // struct/union/class X;
  104. case Decl::CXXRecord: // struct/union/class X; [C++]
  105. if (CGDebugInfo *DI = getDebugInfo())
  106. if (cast<RecordDecl>(D).getDefinition())
  107. DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(&D)));
  108. return;
  109. case Decl::Enum: // enum X;
  110. if (CGDebugInfo *DI = getDebugInfo())
  111. if (cast<EnumDecl>(D).getDefinition())
  112. DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(&D)));
  113. return;
  114. case Decl::Function: // void X();
  115. case Decl::EnumConstant: // enum ? { X = ? }
  116. case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
  117. case Decl::Label: // __label__ x;
  118. case Decl::Import:
  119. case Decl::MSGuid: // __declspec(uuid("..."))
  120. case Decl::UnnamedGlobalConstant:
  121. case Decl::TemplateParamObject:
  122. case Decl::OMPThreadPrivate:
  123. case Decl::OMPAllocate:
  124. case Decl::OMPCapturedExpr:
  125. case Decl::OMPRequires:
  126. case Decl::Empty:
  127. case Decl::Concept:
  128. case Decl::ImplicitConceptSpecialization:
  129. case Decl::LifetimeExtendedTemporary:
  130. case Decl::RequiresExprBody:
  131. // None of these decls require codegen support.
  132. return;
  133. case Decl::NamespaceAlias:
  134. if (CGDebugInfo *DI = getDebugInfo())
  135. DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
  136. return;
  137. case Decl::Using: // using X; [C++]
  138. if (CGDebugInfo *DI = getDebugInfo())
  139. DI->EmitUsingDecl(cast<UsingDecl>(D));
  140. return;
  141. case Decl::UsingEnum: // using enum X; [C++]
  142. if (CGDebugInfo *DI = getDebugInfo())
  143. DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(D));
  144. return;
  145. case Decl::UsingPack:
  146. for (auto *Using : cast<UsingPackDecl>(D).expansions())
  147. EmitDecl(*Using);
  148. return;
  149. case Decl::UsingDirective: // using namespace X; [C++]
  150. if (CGDebugInfo *DI = getDebugInfo())
  151. DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
  152. return;
  153. case Decl::Var:
  154. case Decl::Decomposition: {
  155. const VarDecl &VD = cast<VarDecl>(D);
  156. assert(VD.isLocalVarDecl() &&
  157. "Should not see file-scope variables inside a function!");
  158. EmitVarDecl(VD);
  159. if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
  160. for (auto *B : DD->bindings())
  161. if (auto *HD = B->getHoldingVar())
  162. EmitVarDecl(*HD);
  163. return;
  164. }
  165. case Decl::OMPDeclareReduction:
  166. return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
  167. case Decl::OMPDeclareMapper:
  168. return CGM.EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(&D), this);
  169. case Decl::Typedef: // typedef int X;
  170. case Decl::TypeAlias: { // using X = int; [C++0x]
  171. QualType Ty = cast<TypedefNameDecl>(D).getUnderlyingType();
  172. if (CGDebugInfo *DI = getDebugInfo())
  173. DI->EmitAndRetainType(Ty);
  174. if (Ty->isVariablyModifiedType())
  175. EmitVariablyModifiedType(Ty);
  176. return;
  177. }
  178. }
  179. }
  180. /// EmitVarDecl - This method handles emission of any variable declaration
  181. /// inside a function, including static vars etc.
  182. void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
  183. if (D.hasExternalStorage())
  184. // Don't emit it now, allow it to be emitted lazily on its first use.
  185. return;
  186. // Some function-scope variable does not have static storage but still
  187. // needs to be emitted like a static variable, e.g. a function-scope
  188. // variable in constant address space in OpenCL.
  189. if (D.getStorageDuration() != SD_Automatic) {
  190. // Static sampler variables translated to function calls.
  191. if (D.getType()->isSamplerT())
  192. return;
  193. llvm::GlobalValue::LinkageTypes Linkage =
  194. CGM.getLLVMLinkageVarDefinition(&D, /*IsConstant=*/false);
  195. // FIXME: We need to force the emission/use of a guard variable for
  196. // some variables even if we can constant-evaluate them because
  197. // we can't guarantee every translation unit will constant-evaluate them.
  198. return EmitStaticVarDecl(D, Linkage);
  199. }
  200. if (D.getType().getAddressSpace() == LangAS::opencl_local)
  201. return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
  202. assert(D.hasLocalStorage());
  203. return EmitAutoVarDecl(D);
  204. }
  205. static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
  206. if (CGM.getLangOpts().CPlusPlus)
  207. return CGM.getMangledName(&D).str();
  208. // If this isn't C++, we don't need a mangled name, just a pretty one.
  209. assert(!D.isExternallyVisible() && "name shouldn't matter");
  210. std::string ContextName;
  211. const DeclContext *DC = D.getDeclContext();
  212. if (auto *CD = dyn_cast<CapturedDecl>(DC))
  213. DC = cast<DeclContext>(CD->getNonClosureContext());
  214. if (const auto *FD = dyn_cast<FunctionDecl>(DC))
  215. ContextName = std::string(CGM.getMangledName(FD));
  216. else if (const auto *BD = dyn_cast<BlockDecl>(DC))
  217. ContextName = std::string(CGM.getBlockMangledName(GlobalDecl(), BD));
  218. else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
  219. ContextName = OMD->getSelector().getAsString();
  220. else
  221. llvm_unreachable("Unknown context for static var decl");
  222. ContextName += "." + D.getNameAsString();
  223. return ContextName;
  224. }
  225. llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
  226. const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
  227. // In general, we don't always emit static var decls once before we reference
  228. // them. It is possible to reference them before emitting the function that
  229. // contains them, and it is possible to emit the containing function multiple
  230. // times.
  231. if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
  232. return ExistingGV;
  233. QualType Ty = D.getType();
  234. assert(Ty->isConstantSizeType() && "VLAs can't be static");
  235. // Use the label if the variable is renamed with the asm-label extension.
  236. std::string Name;
  237. if (D.hasAttr<AsmLabelAttr>())
  238. Name = std::string(getMangledName(&D));
  239. else
  240. Name = getStaticDeclName(*this, D);
  241. llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
  242. LangAS AS = GetGlobalVarAddressSpace(&D);
  243. unsigned TargetAS = getContext().getTargetAddressSpace(AS);
  244. // OpenCL variables in local address space and CUDA shared
  245. // variables cannot have an initializer.
  246. llvm::Constant *Init = nullptr;
  247. if (Ty.getAddressSpace() == LangAS::opencl_local ||
  248. D.hasAttr<CUDASharedAttr>() || D.hasAttr<LoaderUninitializedAttr>())
  249. Init = llvm::UndefValue::get(LTy);
  250. else
  251. Init = EmitNullConstant(Ty);
  252. llvm::GlobalVariable *GV = new llvm::GlobalVariable(
  253. getModule(), LTy, Ty.isConstant(getContext()), Linkage, Init, Name,
  254. nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
  255. GV->setAlignment(getContext().getDeclAlign(&D).getAsAlign());
  256. if (supportsCOMDAT() && GV->isWeakForLinker())
  257. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  258. if (D.getTLSKind())
  259. setTLSMode(GV, D);
  260. setGVProperties(GV, &D);
  261. // Make sure the result is of the correct type.
  262. LangAS ExpectedAS = Ty.getAddressSpace();
  263. llvm::Constant *Addr = GV;
  264. if (AS != ExpectedAS) {
  265. Addr = getTargetCodeGenInfo().performAddrSpaceCast(
  266. *this, GV, AS, ExpectedAS,
  267. LTy->getPointerTo(getContext().getTargetAddressSpace(ExpectedAS)));
  268. }
  269. setStaticLocalDeclAddress(&D, Addr);
  270. // Ensure that the static local gets initialized by making sure the parent
  271. // function gets emitted eventually.
  272. const Decl *DC = cast<Decl>(D.getDeclContext());
  273. // We can't name blocks or captured statements directly, so try to emit their
  274. // parents.
  275. if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
  276. DC = DC->getNonClosureContext();
  277. // FIXME: Ensure that global blocks get emitted.
  278. if (!DC)
  279. return Addr;
  280. }
  281. GlobalDecl GD;
  282. if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
  283. GD = GlobalDecl(CD, Ctor_Base);
  284. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
  285. GD = GlobalDecl(DD, Dtor_Base);
  286. else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
  287. GD = GlobalDecl(FD);
  288. else {
  289. // Don't do anything for Obj-C method decls or global closures. We should
  290. // never defer them.
  291. assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
  292. }
  293. if (GD.getDecl()) {
  294. // Disable emission of the parent function for the OpenMP device codegen.
  295. CGOpenMPRuntime::DisableAutoDeclareTargetRAII NoDeclTarget(*this);
  296. (void)GetAddrOfGlobal(GD);
  297. }
  298. return Addr;
  299. }
  300. /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
  301. /// global variable that has already been created for it. If the initializer
  302. /// has a different type than GV does, this may free GV and return a different
  303. /// one. Otherwise it just returns GV.
  304. llvm::GlobalVariable *
  305. CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
  306. llvm::GlobalVariable *GV) {
  307. ConstantEmitter emitter(*this);
  308. llvm::Constant *Init = emitter.tryEmitForInitializer(D);
  309. // If constant emission failed, then this should be a C++ static
  310. // initializer.
  311. if (!Init) {
  312. if (!getLangOpts().CPlusPlus)
  313. CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
  314. else if (D.hasFlexibleArrayInit(getContext()))
  315. CGM.ErrorUnsupported(D.getInit(), "flexible array initializer");
  316. else if (HaveInsertPoint()) {
  317. // Since we have a static initializer, this global variable can't
  318. // be constant.
  319. GV->setConstant(false);
  320. EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
  321. }
  322. return GV;
  323. }
  324. #ifndef NDEBUG
  325. CharUnits VarSize = CGM.getContext().getTypeSizeInChars(D.getType()) +
  326. D.getFlexibleArrayInitChars(getContext());
  327. CharUnits CstSize = CharUnits::fromQuantity(
  328. CGM.getDataLayout().getTypeAllocSize(Init->getType()));
  329. assert(VarSize == CstSize && "Emitted constant has unexpected size");
  330. #endif
  331. // The initializer may differ in type from the global. Rewrite
  332. // the global to match the initializer. (We have to do this
  333. // because some types, like unions, can't be completely represented
  334. // in the LLVM type system.)
  335. if (GV->getValueType() != Init->getType()) {
  336. llvm::GlobalVariable *OldGV = GV;
  337. GV = new llvm::GlobalVariable(
  338. CGM.getModule(), Init->getType(), OldGV->isConstant(),
  339. OldGV->getLinkage(), Init, "",
  340. /*InsertBefore*/ OldGV, OldGV->getThreadLocalMode(),
  341. OldGV->getType()->getPointerAddressSpace());
  342. GV->setVisibility(OldGV->getVisibility());
  343. GV->setDSOLocal(OldGV->isDSOLocal());
  344. GV->setComdat(OldGV->getComdat());
  345. // Steal the name of the old global
  346. GV->takeName(OldGV);
  347. // Replace all uses of the old global with the new global
  348. llvm::Constant *NewPtrForOldDecl =
  349. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  350. OldGV->replaceAllUsesWith(NewPtrForOldDecl);
  351. // Erase the old global, since it is no longer used.
  352. OldGV->eraseFromParent();
  353. }
  354. GV->setConstant(CGM.isTypeConstant(D.getType(), true));
  355. GV->setInitializer(Init);
  356. emitter.finalize(GV);
  357. if (D.needsDestruction(getContext()) == QualType::DK_cxx_destructor &&
  358. HaveInsertPoint()) {
  359. // We have a constant initializer, but a nontrivial destructor. We still
  360. // need to perform a guarded "initialization" in order to register the
  361. // destructor.
  362. EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
  363. }
  364. return GV;
  365. }
  366. void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
  367. llvm::GlobalValue::LinkageTypes Linkage) {
  368. // Check to see if we already have a global variable for this
  369. // declaration. This can happen when double-emitting function
  370. // bodies, e.g. with complete and base constructors.
  371. llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
  372. CharUnits alignment = getContext().getDeclAlign(&D);
  373. // Store into LocalDeclMap before generating initializer to handle
  374. // circular references.
  375. llvm::Type *elemTy = ConvertTypeForMem(D.getType());
  376. setAddrOfLocalVar(&D, Address(addr, elemTy, alignment));
  377. // We can't have a VLA here, but we can have a pointer to a VLA,
  378. // even though that doesn't really make any sense.
  379. // Make sure to evaluate VLA bounds now so that we have them for later.
  380. if (D.getType()->isVariablyModifiedType())
  381. EmitVariablyModifiedType(D.getType());
  382. // Save the type in case adding the initializer forces a type change.
  383. llvm::Type *expectedType = addr->getType();
  384. llvm::GlobalVariable *var =
  385. cast<llvm::GlobalVariable>(addr->stripPointerCasts());
  386. // CUDA's local and local static __shared__ variables should not
  387. // have any non-empty initializers. This is ensured by Sema.
  388. // Whatever initializer such variable may have when it gets here is
  389. // a no-op and should not be emitted.
  390. bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
  391. D.hasAttr<CUDASharedAttr>();
  392. // If this value has an initializer, emit it.
  393. if (D.getInit() && !isCudaSharedVar)
  394. var = AddInitializerToStaticVarDecl(D, var);
  395. var->setAlignment(alignment.getAsAlign());
  396. if (D.hasAttr<AnnotateAttr>())
  397. CGM.AddGlobalAnnotations(&D, var);
  398. if (auto *SA = D.getAttr<PragmaClangBSSSectionAttr>())
  399. var->addAttribute("bss-section", SA->getName());
  400. if (auto *SA = D.getAttr<PragmaClangDataSectionAttr>())
  401. var->addAttribute("data-section", SA->getName());
  402. if (auto *SA = D.getAttr<PragmaClangRodataSectionAttr>())
  403. var->addAttribute("rodata-section", SA->getName());
  404. if (auto *SA = D.getAttr<PragmaClangRelroSectionAttr>())
  405. var->addAttribute("relro-section", SA->getName());
  406. if (const SectionAttr *SA = D.getAttr<SectionAttr>())
  407. var->setSection(SA->getName());
  408. if (D.hasAttr<RetainAttr>())
  409. CGM.addUsedGlobal(var);
  410. else if (D.hasAttr<UsedAttr>())
  411. CGM.addUsedOrCompilerUsedGlobal(var);
  412. // We may have to cast the constant because of the initializer
  413. // mismatch above.
  414. //
  415. // FIXME: It is really dangerous to store this in the map; if anyone
  416. // RAUW's the GV uses of this constant will be invalid.
  417. llvm::Constant *castedAddr =
  418. llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
  419. LocalDeclMap.find(&D)->second = Address(castedAddr, elemTy, alignment);
  420. CGM.setStaticLocalDeclAddress(&D, castedAddr);
  421. CGM.getSanitizerMetadata()->reportGlobal(var, D);
  422. // Emit global variable debug descriptor for static vars.
  423. CGDebugInfo *DI = getDebugInfo();
  424. if (DI && CGM.getCodeGenOpts().hasReducedDebugInfo()) {
  425. DI->setLocation(D.getLocation());
  426. DI->EmitGlobalVariable(var, &D);
  427. }
  428. }
  429. namespace {
  430. struct DestroyObject final : EHScopeStack::Cleanup {
  431. DestroyObject(Address addr, QualType type,
  432. CodeGenFunction::Destroyer *destroyer,
  433. bool useEHCleanupForArray)
  434. : addr(addr), type(type), destroyer(destroyer),
  435. useEHCleanupForArray(useEHCleanupForArray) {}
  436. Address addr;
  437. QualType type;
  438. CodeGenFunction::Destroyer *destroyer;
  439. bool useEHCleanupForArray;
  440. void Emit(CodeGenFunction &CGF, Flags flags) override {
  441. // Don't use an EH cleanup recursively from an EH cleanup.
  442. bool useEHCleanupForArray =
  443. flags.isForNormalCleanup() && this->useEHCleanupForArray;
  444. CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
  445. }
  446. };
  447. template <class Derived>
  448. struct DestroyNRVOVariable : EHScopeStack::Cleanup {
  449. DestroyNRVOVariable(Address addr, QualType type, llvm::Value *NRVOFlag)
  450. : NRVOFlag(NRVOFlag), Loc(addr), Ty(type) {}
  451. llvm::Value *NRVOFlag;
  452. Address Loc;
  453. QualType Ty;
  454. void Emit(CodeGenFunction &CGF, Flags flags) override {
  455. // Along the exceptions path we always execute the dtor.
  456. bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
  457. llvm::BasicBlock *SkipDtorBB = nullptr;
  458. if (NRVO) {
  459. // If we exited via NRVO, we skip the destructor call.
  460. llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
  461. SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
  462. llvm::Value *DidNRVO =
  463. CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
  464. CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
  465. CGF.EmitBlock(RunDtorBB);
  466. }
  467. static_cast<Derived *>(this)->emitDestructorCall(CGF);
  468. if (NRVO) CGF.EmitBlock(SkipDtorBB);
  469. }
  470. virtual ~DestroyNRVOVariable() = default;
  471. };
  472. struct DestroyNRVOVariableCXX final
  473. : DestroyNRVOVariable<DestroyNRVOVariableCXX> {
  474. DestroyNRVOVariableCXX(Address addr, QualType type,
  475. const CXXDestructorDecl *Dtor, llvm::Value *NRVOFlag)
  476. : DestroyNRVOVariable<DestroyNRVOVariableCXX>(addr, type, NRVOFlag),
  477. Dtor(Dtor) {}
  478. const CXXDestructorDecl *Dtor;
  479. void emitDestructorCall(CodeGenFunction &CGF) {
  480. CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
  481. /*ForVirtualBase=*/false,
  482. /*Delegating=*/false, Loc, Ty);
  483. }
  484. };
  485. struct DestroyNRVOVariableC final
  486. : DestroyNRVOVariable<DestroyNRVOVariableC> {
  487. DestroyNRVOVariableC(Address addr, llvm::Value *NRVOFlag, QualType Ty)
  488. : DestroyNRVOVariable<DestroyNRVOVariableC>(addr, Ty, NRVOFlag) {}
  489. void emitDestructorCall(CodeGenFunction &CGF) {
  490. CGF.destroyNonTrivialCStruct(CGF, Loc, Ty);
  491. }
  492. };
  493. struct CallStackRestore final : EHScopeStack::Cleanup {
  494. Address Stack;
  495. CallStackRestore(Address Stack) : Stack(Stack) {}
  496. bool isRedundantBeforeReturn() override { return true; }
  497. void Emit(CodeGenFunction &CGF, Flags flags) override {
  498. llvm::Value *V = CGF.Builder.CreateLoad(Stack);
  499. llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
  500. CGF.Builder.CreateCall(F, V);
  501. }
  502. };
  503. struct ExtendGCLifetime final : EHScopeStack::Cleanup {
  504. const VarDecl &Var;
  505. ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
  506. void Emit(CodeGenFunction &CGF, Flags flags) override {
  507. // Compute the address of the local variable, in case it's a
  508. // byref or something.
  509. DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
  510. Var.getType(), VK_LValue, SourceLocation());
  511. llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
  512. SourceLocation());
  513. CGF.EmitExtendGCLifetime(value);
  514. }
  515. };
  516. struct CallCleanupFunction final : EHScopeStack::Cleanup {
  517. llvm::Constant *CleanupFn;
  518. const CGFunctionInfo &FnInfo;
  519. const VarDecl &Var;
  520. CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
  521. const VarDecl *Var)
  522. : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
  523. void Emit(CodeGenFunction &CGF, Flags flags) override {
  524. DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
  525. Var.getType(), VK_LValue, SourceLocation());
  526. // Compute the address of the local variable, in case it's a byref
  527. // or something.
  528. llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer(CGF);
  529. // In some cases, the type of the function argument will be different from
  530. // the type of the pointer. An example of this is
  531. // void f(void* arg);
  532. // __attribute__((cleanup(f))) void *g;
  533. //
  534. // To fix this we insert a bitcast here.
  535. QualType ArgTy = FnInfo.arg_begin()->type;
  536. llvm::Value *Arg =
  537. CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
  538. CallArgList Args;
  539. Args.add(RValue::get(Arg),
  540. CGF.getContext().getPointerType(Var.getType()));
  541. auto Callee = CGCallee::forDirect(CleanupFn);
  542. CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
  543. }
  544. };
  545. } // end anonymous namespace
  546. /// EmitAutoVarWithLifetime - Does the setup required for an automatic
  547. /// variable with lifetime.
  548. static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
  549. Address addr,
  550. Qualifiers::ObjCLifetime lifetime) {
  551. switch (lifetime) {
  552. case Qualifiers::OCL_None:
  553. llvm_unreachable("present but none");
  554. case Qualifiers::OCL_ExplicitNone:
  555. // nothing to do
  556. break;
  557. case Qualifiers::OCL_Strong: {
  558. CodeGenFunction::Destroyer *destroyer =
  559. (var.hasAttr<ObjCPreciseLifetimeAttr>()
  560. ? CodeGenFunction::destroyARCStrongPrecise
  561. : CodeGenFunction::destroyARCStrongImprecise);
  562. CleanupKind cleanupKind = CGF.getARCCleanupKind();
  563. CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
  564. cleanupKind & EHCleanup);
  565. break;
  566. }
  567. case Qualifiers::OCL_Autoreleasing:
  568. // nothing to do
  569. break;
  570. case Qualifiers::OCL_Weak:
  571. // __weak objects always get EH cleanups; otherwise, exceptions
  572. // could cause really nasty crashes instead of mere leaks.
  573. CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
  574. CodeGenFunction::destroyARCWeak,
  575. /*useEHCleanup*/ true);
  576. break;
  577. }
  578. }
  579. static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
  580. if (const Expr *e = dyn_cast<Expr>(s)) {
  581. // Skip the most common kinds of expressions that make
  582. // hierarchy-walking expensive.
  583. s = e = e->IgnoreParenCasts();
  584. if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
  585. return (ref->getDecl() == &var);
  586. if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
  587. const BlockDecl *block = be->getBlockDecl();
  588. for (const auto &I : block->captures()) {
  589. if (I.getVariable() == &var)
  590. return true;
  591. }
  592. }
  593. }
  594. for (const Stmt *SubStmt : s->children())
  595. // SubStmt might be null; as in missing decl or conditional of an if-stmt.
  596. if (SubStmt && isAccessedBy(var, SubStmt))
  597. return true;
  598. return false;
  599. }
  600. static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
  601. if (!decl) return false;
  602. if (!isa<VarDecl>(decl)) return false;
  603. const VarDecl *var = cast<VarDecl>(decl);
  604. return isAccessedBy(*var, e);
  605. }
  606. static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
  607. const LValue &destLV, const Expr *init) {
  608. bool needsCast = false;
  609. while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
  610. switch (castExpr->getCastKind()) {
  611. // Look through casts that don't require representation changes.
  612. case CK_NoOp:
  613. case CK_BitCast:
  614. case CK_BlockPointerToObjCPointerCast:
  615. needsCast = true;
  616. break;
  617. // If we find an l-value to r-value cast from a __weak variable,
  618. // emit this operation as a copy or move.
  619. case CK_LValueToRValue: {
  620. const Expr *srcExpr = castExpr->getSubExpr();
  621. if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
  622. return false;
  623. // Emit the source l-value.
  624. LValue srcLV = CGF.EmitLValue(srcExpr);
  625. // Handle a formal type change to avoid asserting.
  626. auto srcAddr = srcLV.getAddress(CGF);
  627. if (needsCast) {
  628. srcAddr = CGF.Builder.CreateElementBitCast(
  629. srcAddr, destLV.getAddress(CGF).getElementType());
  630. }
  631. // If it was an l-value, use objc_copyWeak.
  632. if (srcExpr->isLValue()) {
  633. CGF.EmitARCCopyWeak(destLV.getAddress(CGF), srcAddr);
  634. } else {
  635. assert(srcExpr->isXValue());
  636. CGF.EmitARCMoveWeak(destLV.getAddress(CGF), srcAddr);
  637. }
  638. return true;
  639. }
  640. // Stop at anything else.
  641. default:
  642. return false;
  643. }
  644. init = castExpr->getSubExpr();
  645. }
  646. return false;
  647. }
  648. static void drillIntoBlockVariable(CodeGenFunction &CGF,
  649. LValue &lvalue,
  650. const VarDecl *var) {
  651. lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(CGF), var));
  652. }
  653. void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS,
  654. SourceLocation Loc) {
  655. if (!SanOpts.has(SanitizerKind::NullabilityAssign))
  656. return;
  657. auto Nullability = LHS.getType()->getNullability();
  658. if (!Nullability || *Nullability != NullabilityKind::NonNull)
  659. return;
  660. // Check if the right hand side of the assignment is nonnull, if the left
  661. // hand side must be nonnull.
  662. SanitizerScope SanScope(this);
  663. llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS);
  664. llvm::Constant *StaticData[] = {
  665. EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(LHS.getType()),
  666. llvm::ConstantInt::get(Int8Ty, 0), // The LogAlignment info is unused.
  667. llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)};
  668. EmitCheck({{IsNotNull, SanitizerKind::NullabilityAssign}},
  669. SanitizerHandler::TypeMismatch, StaticData, RHS);
  670. }
  671. void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
  672. LValue lvalue, bool capturedByInit) {
  673. Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
  674. if (!lifetime) {
  675. llvm::Value *value = EmitScalarExpr(init);
  676. if (capturedByInit)
  677. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  678. EmitNullabilityCheck(lvalue, value, init->getExprLoc());
  679. EmitStoreThroughLValue(RValue::get(value), lvalue, true);
  680. return;
  681. }
  682. if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
  683. init = DIE->getExpr();
  684. // If we're emitting a value with lifetime, we have to do the
  685. // initialization *before* we leave the cleanup scopes.
  686. if (auto *EWC = dyn_cast<ExprWithCleanups>(init)) {
  687. CodeGenFunction::RunCleanupsScope Scope(*this);
  688. return EmitScalarInit(EWC->getSubExpr(), D, lvalue, capturedByInit);
  689. }
  690. // We have to maintain the illusion that the variable is
  691. // zero-initialized. If the variable might be accessed in its
  692. // initializer, zero-initialize before running the initializer, then
  693. // actually perform the initialization with an assign.
  694. bool accessedByInit = false;
  695. if (lifetime != Qualifiers::OCL_ExplicitNone)
  696. accessedByInit = (capturedByInit || isAccessedBy(D, init));
  697. if (accessedByInit) {
  698. LValue tempLV = lvalue;
  699. // Drill down to the __block object if necessary.
  700. if (capturedByInit) {
  701. // We can use a simple GEP for this because it can't have been
  702. // moved yet.
  703. tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(*this),
  704. cast<VarDecl>(D),
  705. /*follow*/ false));
  706. }
  707. auto ty =
  708. cast<llvm::PointerType>(tempLV.getAddress(*this).getElementType());
  709. llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());
  710. // If __weak, we want to use a barrier under certain conditions.
  711. if (lifetime == Qualifiers::OCL_Weak)
  712. EmitARCInitWeak(tempLV.getAddress(*this), zero);
  713. // Otherwise just do a simple store.
  714. else
  715. EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
  716. }
  717. // Emit the initializer.
  718. llvm::Value *value = nullptr;
  719. switch (lifetime) {
  720. case Qualifiers::OCL_None:
  721. llvm_unreachable("present but none");
  722. case Qualifiers::OCL_Strong: {
  723. if (!D || !isa<VarDecl>(D) || !cast<VarDecl>(D)->isARCPseudoStrong()) {
  724. value = EmitARCRetainScalarExpr(init);
  725. break;
  726. }
  727. // If D is pseudo-strong, treat it like __unsafe_unretained here. This means
  728. // that we omit the retain, and causes non-autoreleased return values to be
  729. // immediately released.
  730. [[fallthrough]];
  731. }
  732. case Qualifiers::OCL_ExplicitNone:
  733. value = EmitARCUnsafeUnretainedScalarExpr(init);
  734. break;
  735. case Qualifiers::OCL_Weak: {
  736. // If it's not accessed by the initializer, try to emit the
  737. // initialization with a copy or move.
  738. if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
  739. return;
  740. }
  741. // No way to optimize a producing initializer into this. It's not
  742. // worth optimizing for, because the value will immediately
  743. // disappear in the common case.
  744. value = EmitScalarExpr(init);
  745. if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  746. if (accessedByInit)
  747. EmitARCStoreWeak(lvalue.getAddress(*this), value, /*ignored*/ true);
  748. else
  749. EmitARCInitWeak(lvalue.getAddress(*this), value);
  750. return;
  751. }
  752. case Qualifiers::OCL_Autoreleasing:
  753. value = EmitARCRetainAutoreleaseScalarExpr(init);
  754. break;
  755. }
  756. if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  757. EmitNullabilityCheck(lvalue, value, init->getExprLoc());
  758. // If the variable might have been accessed by its initializer, we
  759. // might have to initialize with a barrier. We have to do this for
  760. // both __weak and __strong, but __weak got filtered out above.
  761. if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
  762. llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
  763. EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
  764. EmitARCRelease(oldValue, ARCImpreciseLifetime);
  765. return;
  766. }
  767. EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
  768. }
  769. /// Decide whether we can emit the non-zero parts of the specified initializer
  770. /// with equal or fewer than NumStores scalar stores.
  771. static bool canEmitInitWithFewStoresAfterBZero(llvm::Constant *Init,
  772. unsigned &NumStores) {
  773. // Zero and Undef never requires any extra stores.
  774. if (isa<llvm::ConstantAggregateZero>(Init) ||
  775. isa<llvm::ConstantPointerNull>(Init) ||
  776. isa<llvm::UndefValue>(Init))
  777. return true;
  778. if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
  779. isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
  780. isa<llvm::ConstantExpr>(Init))
  781. return Init->isNullValue() || NumStores--;
  782. // See if we can emit each element.
  783. if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
  784. for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
  785. llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
  786. if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
  787. return false;
  788. }
  789. return true;
  790. }
  791. if (llvm::ConstantDataSequential *CDS =
  792. dyn_cast<llvm::ConstantDataSequential>(Init)) {
  793. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  794. llvm::Constant *Elt = CDS->getElementAsConstant(i);
  795. if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
  796. return false;
  797. }
  798. return true;
  799. }
  800. // Anything else is hard and scary.
  801. return false;
  802. }
  803. /// For inits that canEmitInitWithFewStoresAfterBZero returned true for, emit
  804. /// the scalar stores that would be required.
  805. static void emitStoresForInitAfterBZero(CodeGenModule &CGM,
  806. llvm::Constant *Init, Address Loc,
  807. bool isVolatile, CGBuilderTy &Builder,
  808. bool IsAutoInit) {
  809. assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
  810. "called emitStoresForInitAfterBZero for zero or undef value.");
  811. if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
  812. isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
  813. isa<llvm::ConstantExpr>(Init)) {
  814. auto *I = Builder.CreateStore(Init, Loc, isVolatile);
  815. if (IsAutoInit)
  816. I->addAnnotationMetadata("auto-init");
  817. return;
  818. }
  819. if (llvm::ConstantDataSequential *CDS =
  820. dyn_cast<llvm::ConstantDataSequential>(Init)) {
  821. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  822. llvm::Constant *Elt = CDS->getElementAsConstant(i);
  823. // If necessary, get a pointer to the element and emit it.
  824. if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
  825. emitStoresForInitAfterBZero(
  826. CGM, Elt, Builder.CreateConstInBoundsGEP2_32(Loc, 0, i), isVolatile,
  827. Builder, IsAutoInit);
  828. }
  829. return;
  830. }
  831. assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
  832. "Unknown value type!");
  833. for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
  834. llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
  835. // If necessary, get a pointer to the element and emit it.
  836. if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
  837. emitStoresForInitAfterBZero(CGM, Elt,
  838. Builder.CreateConstInBoundsGEP2_32(Loc, 0, i),
  839. isVolatile, Builder, IsAutoInit);
  840. }
  841. }
  842. /// Decide whether we should use bzero plus some stores to initialize a local
  843. /// variable instead of using a memcpy from a constant global. It is beneficial
  844. /// to use bzero if the global is all zeros, or mostly zeros and large.
  845. static bool shouldUseBZeroPlusStoresToInitialize(llvm::Constant *Init,
  846. uint64_t GlobalSize) {
  847. // If a global is all zeros, always use a bzero.
  848. if (isa<llvm::ConstantAggregateZero>(Init)) return true;
  849. // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
  850. // do it if it will require 6 or fewer scalar stores.
  851. // TODO: Should budget depends on the size? Avoiding a large global warrants
  852. // plopping in more stores.
  853. unsigned StoreBudget = 6;
  854. uint64_t SizeLimit = 32;
  855. return GlobalSize > SizeLimit &&
  856. canEmitInitWithFewStoresAfterBZero(Init, StoreBudget);
  857. }
  858. /// Decide whether we should use memset to initialize a local variable instead
  859. /// of using a memcpy from a constant global. Assumes we've already decided to
  860. /// not user bzero.
  861. /// FIXME We could be more clever, as we are for bzero above, and generate
  862. /// memset followed by stores. It's unclear that's worth the effort.
  863. static llvm::Value *shouldUseMemSetToInitialize(llvm::Constant *Init,
  864. uint64_t GlobalSize,
  865. const llvm::DataLayout &DL) {
  866. uint64_t SizeLimit = 32;
  867. if (GlobalSize <= SizeLimit)
  868. return nullptr;
  869. return llvm::isBytewiseValue(Init, DL);
  870. }
  871. /// Decide whether we want to split a constant structure or array store into a
  872. /// sequence of its fields' stores. This may cost us code size and compilation
  873. /// speed, but plays better with store optimizations.
  874. static bool shouldSplitConstantStore(CodeGenModule &CGM,
  875. uint64_t GlobalByteSize) {
  876. // Don't break things that occupy more than one cacheline.
  877. uint64_t ByteSizeLimit = 64;
  878. if (CGM.getCodeGenOpts().OptimizationLevel == 0)
  879. return false;
  880. if (GlobalByteSize <= ByteSizeLimit)
  881. return true;
  882. return false;
  883. }
  884. enum class IsPattern { No, Yes };
  885. /// Generate a constant filled with either a pattern or zeroes.
  886. static llvm::Constant *patternOrZeroFor(CodeGenModule &CGM, IsPattern isPattern,
  887. llvm::Type *Ty) {
  888. if (isPattern == IsPattern::Yes)
  889. return initializationPatternFor(CGM, Ty);
  890. else
  891. return llvm::Constant::getNullValue(Ty);
  892. }
  893. static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
  894. llvm::Constant *constant);
  895. /// Helper function for constWithPadding() to deal with padding in structures.
  896. static llvm::Constant *constStructWithPadding(CodeGenModule &CGM,
  897. IsPattern isPattern,
  898. llvm::StructType *STy,
  899. llvm::Constant *constant) {
  900. const llvm::DataLayout &DL = CGM.getDataLayout();
  901. const llvm::StructLayout *Layout = DL.getStructLayout(STy);
  902. llvm::Type *Int8Ty = llvm::IntegerType::getInt8Ty(CGM.getLLVMContext());
  903. unsigned SizeSoFar = 0;
  904. SmallVector<llvm::Constant *, 8> Values;
  905. bool NestedIntact = true;
  906. for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
  907. unsigned CurOff = Layout->getElementOffset(i);
  908. if (SizeSoFar < CurOff) {
  909. assert(!STy->isPacked());
  910. auto *PadTy = llvm::ArrayType::get(Int8Ty, CurOff - SizeSoFar);
  911. Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy));
  912. }
  913. llvm::Constant *CurOp;
  914. if (constant->isZeroValue())
  915. CurOp = llvm::Constant::getNullValue(STy->getElementType(i));
  916. else
  917. CurOp = cast<llvm::Constant>(constant->getAggregateElement(i));
  918. auto *NewOp = constWithPadding(CGM, isPattern, CurOp);
  919. if (CurOp != NewOp)
  920. NestedIntact = false;
  921. Values.push_back(NewOp);
  922. SizeSoFar = CurOff + DL.getTypeAllocSize(CurOp->getType());
  923. }
  924. unsigned TotalSize = Layout->getSizeInBytes();
  925. if (SizeSoFar < TotalSize) {
  926. auto *PadTy = llvm::ArrayType::get(Int8Ty, TotalSize - SizeSoFar);
  927. Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy));
  928. }
  929. if (NestedIntact && Values.size() == STy->getNumElements())
  930. return constant;
  931. return llvm::ConstantStruct::getAnon(Values, STy->isPacked());
  932. }
  933. /// Replace all padding bytes in a given constant with either a pattern byte or
  934. /// 0x00.
  935. static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
  936. llvm::Constant *constant) {
  937. llvm::Type *OrigTy = constant->getType();
  938. if (const auto STy = dyn_cast<llvm::StructType>(OrigTy))
  939. return constStructWithPadding(CGM, isPattern, STy, constant);
  940. if (auto *ArrayTy = dyn_cast<llvm::ArrayType>(OrigTy)) {
  941. llvm::SmallVector<llvm::Constant *, 8> Values;
  942. uint64_t Size = ArrayTy->getNumElements();
  943. if (!Size)
  944. return constant;
  945. llvm::Type *ElemTy = ArrayTy->getElementType();
  946. bool ZeroInitializer = constant->isNullValue();
  947. llvm::Constant *OpValue, *PaddedOp;
  948. if (ZeroInitializer) {
  949. OpValue = llvm::Constant::getNullValue(ElemTy);
  950. PaddedOp = constWithPadding(CGM, isPattern, OpValue);
  951. }
  952. for (unsigned Op = 0; Op != Size; ++Op) {
  953. if (!ZeroInitializer) {
  954. OpValue = constant->getAggregateElement(Op);
  955. PaddedOp = constWithPadding(CGM, isPattern, OpValue);
  956. }
  957. Values.push_back(PaddedOp);
  958. }
  959. auto *NewElemTy = Values[0]->getType();
  960. if (NewElemTy == ElemTy)
  961. return constant;
  962. auto *NewArrayTy = llvm::ArrayType::get(NewElemTy, Size);
  963. return llvm::ConstantArray::get(NewArrayTy, Values);
  964. }
  965. // FIXME: Add handling for tail padding in vectors. Vectors don't
  966. // have padding between or inside elements, but the total amount of
  967. // data can be less than the allocated size.
  968. return constant;
  969. }
  970. Address CodeGenModule::createUnnamedGlobalFrom(const VarDecl &D,
  971. llvm::Constant *Constant,
  972. CharUnits Align) {
  973. auto FunctionName = [&](const DeclContext *DC) -> std::string {
  974. if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
  975. if (const auto *CC = dyn_cast<CXXConstructorDecl>(FD))
  976. return CC->getNameAsString();
  977. if (const auto *CD = dyn_cast<CXXDestructorDecl>(FD))
  978. return CD->getNameAsString();
  979. return std::string(getMangledName(FD));
  980. } else if (const auto *OM = dyn_cast<ObjCMethodDecl>(DC)) {
  981. return OM->getNameAsString();
  982. } else if (isa<BlockDecl>(DC)) {
  983. return "<block>";
  984. } else if (isa<CapturedDecl>(DC)) {
  985. return "<captured>";
  986. } else {
  987. llvm_unreachable("expected a function or method");
  988. }
  989. };
  990. // Form a simple per-variable cache of these values in case we find we
  991. // want to reuse them.
  992. llvm::GlobalVariable *&CacheEntry = InitializerConstants[&D];
  993. if (!CacheEntry || CacheEntry->getInitializer() != Constant) {
  994. auto *Ty = Constant->getType();
  995. bool isConstant = true;
  996. llvm::GlobalVariable *InsertBefore = nullptr;
  997. unsigned AS =
  998. getContext().getTargetAddressSpace(GetGlobalConstantAddressSpace());
  999. std::string Name;
  1000. if (D.hasGlobalStorage())
  1001. Name = getMangledName(&D).str() + ".const";
  1002. else if (const DeclContext *DC = D.getParentFunctionOrMethod())
  1003. Name = ("__const." + FunctionName(DC) + "." + D.getName()).str();
  1004. else
  1005. llvm_unreachable("local variable has no parent function or method");
  1006. llvm::GlobalVariable *GV = new llvm::GlobalVariable(
  1007. getModule(), Ty, isConstant, llvm::GlobalValue::PrivateLinkage,
  1008. Constant, Name, InsertBefore, llvm::GlobalValue::NotThreadLocal, AS);
  1009. GV->setAlignment(Align.getAsAlign());
  1010. GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1011. CacheEntry = GV;
  1012. } else if (CacheEntry->getAlignment() < uint64_t(Align.getQuantity())) {
  1013. CacheEntry->setAlignment(Align.getAsAlign());
  1014. }
  1015. return Address(CacheEntry, CacheEntry->getValueType(), Align);
  1016. }
  1017. static Address createUnnamedGlobalForMemcpyFrom(CodeGenModule &CGM,
  1018. const VarDecl &D,
  1019. CGBuilderTy &Builder,
  1020. llvm::Constant *Constant,
  1021. CharUnits Align) {
  1022. Address SrcPtr = CGM.createUnnamedGlobalFrom(D, Constant, Align);
  1023. return Builder.CreateElementBitCast(SrcPtr, CGM.Int8Ty);
  1024. }
  1025. static void emitStoresForConstant(CodeGenModule &CGM, const VarDecl &D,
  1026. Address Loc, bool isVolatile,
  1027. CGBuilderTy &Builder,
  1028. llvm::Constant *constant, bool IsAutoInit) {
  1029. auto *Ty = constant->getType();
  1030. uint64_t ConstantSize = CGM.getDataLayout().getTypeAllocSize(Ty);
  1031. if (!ConstantSize)
  1032. return;
  1033. bool canDoSingleStore = Ty->isIntOrIntVectorTy() ||
  1034. Ty->isPtrOrPtrVectorTy() || Ty->isFPOrFPVectorTy();
  1035. if (canDoSingleStore) {
  1036. auto *I = Builder.CreateStore(constant, Loc, isVolatile);
  1037. if (IsAutoInit)
  1038. I->addAnnotationMetadata("auto-init");
  1039. return;
  1040. }
  1041. auto *SizeVal = llvm::ConstantInt::get(CGM.IntPtrTy, ConstantSize);
  1042. // If the initializer is all or mostly the same, codegen with bzero / memset
  1043. // then do a few stores afterward.
  1044. if (shouldUseBZeroPlusStoresToInitialize(constant, ConstantSize)) {
  1045. auto *I = Builder.CreateMemSet(Loc, llvm::ConstantInt::get(CGM.Int8Ty, 0),
  1046. SizeVal, isVolatile);
  1047. if (IsAutoInit)
  1048. I->addAnnotationMetadata("auto-init");
  1049. bool valueAlreadyCorrect =
  1050. constant->isNullValue() || isa<llvm::UndefValue>(constant);
  1051. if (!valueAlreadyCorrect) {
  1052. Loc = Builder.CreateElementBitCast(Loc, Ty);
  1053. emitStoresForInitAfterBZero(CGM, constant, Loc, isVolatile, Builder,
  1054. IsAutoInit);
  1055. }
  1056. return;
  1057. }
  1058. // If the initializer is a repeated byte pattern, use memset.
  1059. llvm::Value *Pattern =
  1060. shouldUseMemSetToInitialize(constant, ConstantSize, CGM.getDataLayout());
  1061. if (Pattern) {
  1062. uint64_t Value = 0x00;
  1063. if (!isa<llvm::UndefValue>(Pattern)) {
  1064. const llvm::APInt &AP = cast<llvm::ConstantInt>(Pattern)->getValue();
  1065. assert(AP.getBitWidth() <= 8);
  1066. Value = AP.getLimitedValue();
  1067. }
  1068. auto *I = Builder.CreateMemSet(
  1069. Loc, llvm::ConstantInt::get(CGM.Int8Ty, Value), SizeVal, isVolatile);
  1070. if (IsAutoInit)
  1071. I->addAnnotationMetadata("auto-init");
  1072. return;
  1073. }
  1074. // If the initializer is small, use a handful of stores.
  1075. if (shouldSplitConstantStore(CGM, ConstantSize)) {
  1076. if (auto *STy = dyn_cast<llvm::StructType>(Ty)) {
  1077. // FIXME: handle the case when STy != Loc.getElementType().
  1078. if (STy == Loc.getElementType()) {
  1079. for (unsigned i = 0; i != constant->getNumOperands(); i++) {
  1080. Address EltPtr = Builder.CreateStructGEP(Loc, i);
  1081. emitStoresForConstant(
  1082. CGM, D, EltPtr, isVolatile, Builder,
  1083. cast<llvm::Constant>(Builder.CreateExtractValue(constant, i)),
  1084. IsAutoInit);
  1085. }
  1086. return;
  1087. }
  1088. } else if (auto *ATy = dyn_cast<llvm::ArrayType>(Ty)) {
  1089. // FIXME: handle the case when ATy != Loc.getElementType().
  1090. if (ATy == Loc.getElementType()) {
  1091. for (unsigned i = 0; i != ATy->getNumElements(); i++) {
  1092. Address EltPtr = Builder.CreateConstArrayGEP(Loc, i);
  1093. emitStoresForConstant(
  1094. CGM, D, EltPtr, isVolatile, Builder,
  1095. cast<llvm::Constant>(Builder.CreateExtractValue(constant, i)),
  1096. IsAutoInit);
  1097. }
  1098. return;
  1099. }
  1100. }
  1101. }
  1102. // Copy from a global.
  1103. auto *I =
  1104. Builder.CreateMemCpy(Loc,
  1105. createUnnamedGlobalForMemcpyFrom(
  1106. CGM, D, Builder, constant, Loc.getAlignment()),
  1107. SizeVal, isVolatile);
  1108. if (IsAutoInit)
  1109. I->addAnnotationMetadata("auto-init");
  1110. }
  1111. static void emitStoresForZeroInit(CodeGenModule &CGM, const VarDecl &D,
  1112. Address Loc, bool isVolatile,
  1113. CGBuilderTy &Builder) {
  1114. llvm::Type *ElTy = Loc.getElementType();
  1115. llvm::Constant *constant =
  1116. constWithPadding(CGM, IsPattern::No, llvm::Constant::getNullValue(ElTy));
  1117. emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant,
  1118. /*IsAutoInit=*/true);
  1119. }
  1120. static void emitStoresForPatternInit(CodeGenModule &CGM, const VarDecl &D,
  1121. Address Loc, bool isVolatile,
  1122. CGBuilderTy &Builder) {
  1123. llvm::Type *ElTy = Loc.getElementType();
  1124. llvm::Constant *constant = constWithPadding(
  1125. CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));
  1126. assert(!isa<llvm::UndefValue>(constant));
  1127. emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant,
  1128. /*IsAutoInit=*/true);
  1129. }
  1130. static bool containsUndef(llvm::Constant *constant) {
  1131. auto *Ty = constant->getType();
  1132. if (isa<llvm::UndefValue>(constant))
  1133. return true;
  1134. if (Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy())
  1135. for (llvm::Use &Op : constant->operands())
  1136. if (containsUndef(cast<llvm::Constant>(Op)))
  1137. return true;
  1138. return false;
  1139. }
  1140. static llvm::Constant *replaceUndef(CodeGenModule &CGM, IsPattern isPattern,
  1141. llvm::Constant *constant) {
  1142. auto *Ty = constant->getType();
  1143. if (isa<llvm::UndefValue>(constant))
  1144. return patternOrZeroFor(CGM, isPattern, Ty);
  1145. if (!(Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()))
  1146. return constant;
  1147. if (!containsUndef(constant))
  1148. return constant;
  1149. llvm::SmallVector<llvm::Constant *, 8> Values(constant->getNumOperands());
  1150. for (unsigned Op = 0, NumOp = constant->getNumOperands(); Op != NumOp; ++Op) {
  1151. auto *OpValue = cast<llvm::Constant>(constant->getOperand(Op));
  1152. Values[Op] = replaceUndef(CGM, isPattern, OpValue);
  1153. }
  1154. if (Ty->isStructTy())
  1155. return llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Values);
  1156. if (Ty->isArrayTy())
  1157. return llvm::ConstantArray::get(cast<llvm::ArrayType>(Ty), Values);
  1158. assert(Ty->isVectorTy());
  1159. return llvm::ConstantVector::get(Values);
  1160. }
  1161. /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
  1162. /// variable declaration with auto, register, or no storage class specifier.
  1163. /// These turn into simple stack objects, or GlobalValues depending on target.
  1164. void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
  1165. AutoVarEmission emission = EmitAutoVarAlloca(D);
  1166. EmitAutoVarInit(emission);
  1167. EmitAutoVarCleanups(emission);
  1168. }
  1169. /// Emit a lifetime.begin marker if some criteria are satisfied.
  1170. /// \return a pointer to the temporary size Value if a marker was emitted, null
  1171. /// otherwise
  1172. llvm::Value *CodeGenFunction::EmitLifetimeStart(llvm::TypeSize Size,
  1173. llvm::Value *Addr) {
  1174. if (!ShouldEmitLifetimeMarkers)
  1175. return nullptr;
  1176. assert(Addr->getType()->getPointerAddressSpace() ==
  1177. CGM.getDataLayout().getAllocaAddrSpace() &&
  1178. "Pointer should be in alloca address space");
  1179. llvm::Value *SizeV = llvm::ConstantInt::get(
  1180. Int64Ty, Size.isScalable() ? -1 : Size.getFixedValue());
  1181. Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
  1182. llvm::CallInst *C =
  1183. Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
  1184. C->setDoesNotThrow();
  1185. return SizeV;
  1186. }
  1187. void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
  1188. assert(Addr->getType()->getPointerAddressSpace() ==
  1189. CGM.getDataLayout().getAllocaAddrSpace() &&
  1190. "Pointer should be in alloca address space");
  1191. Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
  1192. llvm::CallInst *C =
  1193. Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
  1194. C->setDoesNotThrow();
  1195. }
  1196. void CodeGenFunction::EmitAndRegisterVariableArrayDimensions(
  1197. CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo) {
  1198. // For each dimension stores its QualType and corresponding
  1199. // size-expression Value.
  1200. SmallVector<CodeGenFunction::VlaSizePair, 4> Dimensions;
  1201. SmallVector<IdentifierInfo *, 4> VLAExprNames;
  1202. // Break down the array into individual dimensions.
  1203. QualType Type1D = D.getType();
  1204. while (getContext().getAsVariableArrayType(Type1D)) {
  1205. auto VlaSize = getVLAElements1D(Type1D);
  1206. if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
  1207. Dimensions.emplace_back(C, Type1D.getUnqualifiedType());
  1208. else {
  1209. // Generate a locally unique name for the size expression.
  1210. Twine Name = Twine("__vla_expr") + Twine(VLAExprCounter++);
  1211. SmallString<12> Buffer;
  1212. StringRef NameRef = Name.toStringRef(Buffer);
  1213. auto &Ident = getContext().Idents.getOwn(NameRef);
  1214. VLAExprNames.push_back(&Ident);
  1215. auto SizeExprAddr =
  1216. CreateDefaultAlignTempAlloca(VlaSize.NumElts->getType(), NameRef);
  1217. Builder.CreateStore(VlaSize.NumElts, SizeExprAddr);
  1218. Dimensions.emplace_back(SizeExprAddr.getPointer(),
  1219. Type1D.getUnqualifiedType());
  1220. }
  1221. Type1D = VlaSize.Type;
  1222. }
  1223. if (!EmitDebugInfo)
  1224. return;
  1225. // Register each dimension's size-expression with a DILocalVariable,
  1226. // so that it can be used by CGDebugInfo when instantiating a DISubrange
  1227. // to describe this array.
  1228. unsigned NameIdx = 0;
  1229. for (auto &VlaSize : Dimensions) {
  1230. llvm::Metadata *MD;
  1231. if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
  1232. MD = llvm::ConstantAsMetadata::get(C);
  1233. else {
  1234. // Create an artificial VarDecl to generate debug info for.
  1235. IdentifierInfo *NameIdent = VLAExprNames[NameIdx++];
  1236. assert(cast<llvm::PointerType>(VlaSize.NumElts->getType())
  1237. ->isOpaqueOrPointeeTypeMatches(SizeTy) &&
  1238. "Number of VLA elements must be SizeTy");
  1239. auto QT = getContext().getIntTypeForBitwidth(
  1240. SizeTy->getScalarSizeInBits(), false);
  1241. auto *ArtificialDecl = VarDecl::Create(
  1242. getContext(), const_cast<DeclContext *>(D.getDeclContext()),
  1243. D.getLocation(), D.getLocation(), NameIdent, QT,
  1244. getContext().CreateTypeSourceInfo(QT), SC_Auto);
  1245. ArtificialDecl->setImplicit();
  1246. MD = DI->EmitDeclareOfAutoVariable(ArtificialDecl, VlaSize.NumElts,
  1247. Builder);
  1248. }
  1249. assert(MD && "No Size expression debug node created");
  1250. DI->registerVLASizeExpression(VlaSize.Type, MD);
  1251. }
  1252. }
  1253. /// EmitAutoVarAlloca - Emit the alloca and debug information for a
  1254. /// local variable. Does not emit initialization or destruction.
  1255. CodeGenFunction::AutoVarEmission
  1256. CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
  1257. QualType Ty = D.getType();
  1258. assert(
  1259. Ty.getAddressSpace() == LangAS::Default ||
  1260. (Ty.getAddressSpace() == LangAS::opencl_private && getLangOpts().OpenCL));
  1261. AutoVarEmission emission(D);
  1262. bool isEscapingByRef = D.isEscapingByref();
  1263. emission.IsEscapingByRef = isEscapingByRef;
  1264. CharUnits alignment = getContext().getDeclAlign(&D);
  1265. // If the type is variably-modified, emit all the VLA sizes for it.
  1266. if (Ty->isVariablyModifiedType())
  1267. EmitVariablyModifiedType(Ty);
  1268. auto *DI = getDebugInfo();
  1269. bool EmitDebugInfo = DI && CGM.getCodeGenOpts().hasReducedDebugInfo();
  1270. Address address = Address::invalid();
  1271. Address AllocaAddr = Address::invalid();
  1272. Address OpenMPLocalAddr = Address::invalid();
  1273. if (CGM.getLangOpts().OpenMPIRBuilder)
  1274. OpenMPLocalAddr = OMPBuilderCBHelpers::getAddressOfLocalVariable(*this, &D);
  1275. else
  1276. OpenMPLocalAddr =
  1277. getLangOpts().OpenMP
  1278. ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
  1279. : Address::invalid();
  1280. bool NRVO = getLangOpts().ElideConstructors && D.isNRVOVariable();
  1281. if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
  1282. address = OpenMPLocalAddr;
  1283. AllocaAddr = OpenMPLocalAddr;
  1284. } else if (Ty->isConstantSizeType()) {
  1285. // If this value is an array or struct with a statically determinable
  1286. // constant initializer, there are optimizations we can do.
  1287. //
  1288. // TODO: We should constant-evaluate the initializer of any variable,
  1289. // as long as it is initialized by a constant expression. Currently,
  1290. // isConstantInitializer produces wrong answers for structs with
  1291. // reference or bitfield members, and a few other cases, and checking
  1292. // for POD-ness protects us from some of these.
  1293. if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
  1294. (D.isConstexpr() ||
  1295. ((Ty.isPODType(getContext()) ||
  1296. getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
  1297. D.getInit()->isConstantInitializer(getContext(), false)))) {
  1298. // If the variable's a const type, and it's neither an NRVO
  1299. // candidate nor a __block variable and has no mutable members,
  1300. // emit it as a global instead.
  1301. // Exception is if a variable is located in non-constant address space
  1302. // in OpenCL.
  1303. if ((!getLangOpts().OpenCL ||
  1304. Ty.getAddressSpace() == LangAS::opencl_constant) &&
  1305. (CGM.getCodeGenOpts().MergeAllConstants && !NRVO &&
  1306. !isEscapingByRef && CGM.isTypeConstant(Ty, true))) {
  1307. EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
  1308. // Signal this condition to later callbacks.
  1309. emission.Addr = Address::invalid();
  1310. assert(emission.wasEmittedAsGlobal());
  1311. return emission;
  1312. }
  1313. // Otherwise, tell the initialization code that we're in this case.
  1314. emission.IsConstantAggregate = true;
  1315. }
  1316. // A normal fixed sized variable becomes an alloca in the entry block,
  1317. // unless:
  1318. // - it's an NRVO variable.
  1319. // - we are compiling OpenMP and it's an OpenMP local variable.
  1320. if (NRVO) {
  1321. // The named return value optimization: allocate this variable in the
  1322. // return slot, so that we can elide the copy when returning this
  1323. // variable (C++0x [class.copy]p34).
  1324. address = ReturnValue;
  1325. AllocaAddr = ReturnValue;
  1326. if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
  1327. const auto *RD = RecordTy->getDecl();
  1328. const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
  1329. if ((CXXRD && !CXXRD->hasTrivialDestructor()) ||
  1330. RD->isNonTrivialToPrimitiveDestroy()) {
  1331. // Create a flag that is used to indicate when the NRVO was applied
  1332. // to this variable. Set it to zero to indicate that NRVO was not
  1333. // applied.
  1334. llvm::Value *Zero = Builder.getFalse();
  1335. Address NRVOFlag =
  1336. CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo",
  1337. /*ArraySize=*/nullptr, &AllocaAddr);
  1338. EnsureInsertPoint();
  1339. Builder.CreateStore(Zero, NRVOFlag);
  1340. // Record the NRVO flag for this variable.
  1341. NRVOFlags[&D] = NRVOFlag.getPointer();
  1342. emission.NRVOFlag = NRVOFlag.getPointer();
  1343. }
  1344. }
  1345. } else {
  1346. CharUnits allocaAlignment;
  1347. llvm::Type *allocaTy;
  1348. if (isEscapingByRef) {
  1349. auto &byrefInfo = getBlockByrefInfo(&D);
  1350. allocaTy = byrefInfo.Type;
  1351. allocaAlignment = byrefInfo.ByrefAlignment;
  1352. } else {
  1353. allocaTy = ConvertTypeForMem(Ty);
  1354. allocaAlignment = alignment;
  1355. }
  1356. // Create the alloca. Note that we set the name separately from
  1357. // building the instruction so that it's there even in no-asserts
  1358. // builds.
  1359. address = CreateTempAlloca(allocaTy, allocaAlignment, D.getName(),
  1360. /*ArraySize=*/nullptr, &AllocaAddr);
  1361. // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
  1362. // the catch parameter starts in the catchpad instruction, and we can't
  1363. // insert code in those basic blocks.
  1364. bool IsMSCatchParam =
  1365. D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
  1366. // Emit a lifetime intrinsic if meaningful. There's no point in doing this
  1367. // if we don't have a valid insertion point (?).
  1368. if (HaveInsertPoint() && !IsMSCatchParam) {
  1369. // If there's a jump into the lifetime of this variable, its lifetime
  1370. // gets broken up into several regions in IR, which requires more work
  1371. // to handle correctly. For now, just omit the intrinsics; this is a
  1372. // rare case, and it's better to just be conservatively correct.
  1373. // PR28267.
  1374. //
  1375. // We have to do this in all language modes if there's a jump past the
  1376. // declaration. We also have to do it in C if there's a jump to an
  1377. // earlier point in the current block because non-VLA lifetimes begin as
  1378. // soon as the containing block is entered, not when its variables
  1379. // actually come into scope; suppressing the lifetime annotations
  1380. // completely in this case is unnecessarily pessimistic, but again, this
  1381. // is rare.
  1382. if (!Bypasses.IsBypassed(&D) &&
  1383. !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
  1384. llvm::TypeSize Size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
  1385. emission.SizeForLifetimeMarkers =
  1386. EmitLifetimeStart(Size, AllocaAddr.getPointer());
  1387. }
  1388. } else {
  1389. assert(!emission.useLifetimeMarkers());
  1390. }
  1391. }
  1392. } else {
  1393. EnsureInsertPoint();
  1394. if (!DidCallStackSave) {
  1395. // Save the stack.
  1396. Address Stack =
  1397. CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
  1398. llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
  1399. llvm::Value *V = Builder.CreateCall(F);
  1400. Builder.CreateStore(V, Stack);
  1401. DidCallStackSave = true;
  1402. // Push a cleanup block and restore the stack there.
  1403. // FIXME: in general circumstances, this should be an EH cleanup.
  1404. pushStackRestore(NormalCleanup, Stack);
  1405. }
  1406. auto VlaSize = getVLASize(Ty);
  1407. llvm::Type *llvmTy = ConvertTypeForMem(VlaSize.Type);
  1408. // Allocate memory for the array.
  1409. address = CreateTempAlloca(llvmTy, alignment, "vla", VlaSize.NumElts,
  1410. &AllocaAddr);
  1411. // If we have debug info enabled, properly describe the VLA dimensions for
  1412. // this type by registering the vla size expression for each of the
  1413. // dimensions.
  1414. EmitAndRegisterVariableArrayDimensions(DI, D, EmitDebugInfo);
  1415. }
  1416. setAddrOfLocalVar(&D, address);
  1417. emission.Addr = address;
  1418. emission.AllocaAddr = AllocaAddr;
  1419. // Emit debug info for local var declaration.
  1420. if (EmitDebugInfo && HaveInsertPoint()) {
  1421. Address DebugAddr = address;
  1422. bool UsePointerValue = NRVO && ReturnValuePointer.isValid();
  1423. DI->setLocation(D.getLocation());
  1424. // If NRVO, use a pointer to the return address.
  1425. if (UsePointerValue) {
  1426. DebugAddr = ReturnValuePointer;
  1427. AllocaAddr = ReturnValuePointer;
  1428. }
  1429. (void)DI->EmitDeclareOfAutoVariable(&D, AllocaAddr.getPointer(), Builder,
  1430. UsePointerValue);
  1431. }
  1432. if (D.hasAttr<AnnotateAttr>() && HaveInsertPoint())
  1433. EmitVarAnnotations(&D, address.getPointer());
  1434. // Make sure we call @llvm.lifetime.end.
  1435. if (emission.useLifetimeMarkers())
  1436. EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
  1437. emission.getOriginalAllocatedAddress(),
  1438. emission.getSizeForLifetimeMarkers());
  1439. return emission;
  1440. }
  1441. static bool isCapturedBy(const VarDecl &, const Expr *);
  1442. /// Determines whether the given __block variable is potentially
  1443. /// captured by the given statement.
  1444. static bool isCapturedBy(const VarDecl &Var, const Stmt *S) {
  1445. if (const Expr *E = dyn_cast<Expr>(S))
  1446. return isCapturedBy(Var, E);
  1447. for (const Stmt *SubStmt : S->children())
  1448. if (isCapturedBy(Var, SubStmt))
  1449. return true;
  1450. return false;
  1451. }
  1452. /// Determines whether the given __block variable is potentially
  1453. /// captured by the given expression.
  1454. static bool isCapturedBy(const VarDecl &Var, const Expr *E) {
  1455. // Skip the most common kinds of expressions that make
  1456. // hierarchy-walking expensive.
  1457. E = E->IgnoreParenCasts();
  1458. if (const BlockExpr *BE = dyn_cast<BlockExpr>(E)) {
  1459. const BlockDecl *Block = BE->getBlockDecl();
  1460. for (const auto &I : Block->captures()) {
  1461. if (I.getVariable() == &Var)
  1462. return true;
  1463. }
  1464. // No need to walk into the subexpressions.
  1465. return false;
  1466. }
  1467. if (const StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
  1468. const CompoundStmt *CS = SE->getSubStmt();
  1469. for (const auto *BI : CS->body())
  1470. if (const auto *BIE = dyn_cast<Expr>(BI)) {
  1471. if (isCapturedBy(Var, BIE))
  1472. return true;
  1473. }
  1474. else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
  1475. // special case declarations
  1476. for (const auto *I : DS->decls()) {
  1477. if (const auto *VD = dyn_cast<VarDecl>((I))) {
  1478. const Expr *Init = VD->getInit();
  1479. if (Init && isCapturedBy(Var, Init))
  1480. return true;
  1481. }
  1482. }
  1483. }
  1484. else
  1485. // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
  1486. // Later, provide code to poke into statements for capture analysis.
  1487. return true;
  1488. return false;
  1489. }
  1490. for (const Stmt *SubStmt : E->children())
  1491. if (isCapturedBy(Var, SubStmt))
  1492. return true;
  1493. return false;
  1494. }
  1495. /// Determine whether the given initializer is trivial in the sense
  1496. /// that it requires no code to be generated.
  1497. bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
  1498. if (!Init)
  1499. return true;
  1500. if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
  1501. if (CXXConstructorDecl *Constructor = Construct->getConstructor())
  1502. if (Constructor->isTrivial() &&
  1503. Constructor->isDefaultConstructor() &&
  1504. !Construct->requiresZeroInitialization())
  1505. return true;
  1506. return false;
  1507. }
  1508. void CodeGenFunction::emitZeroOrPatternForAutoVarInit(QualType type,
  1509. const VarDecl &D,
  1510. Address Loc) {
  1511. auto trivialAutoVarInit = getContext().getLangOpts().getTrivialAutoVarInit();
  1512. CharUnits Size = getContext().getTypeSizeInChars(type);
  1513. bool isVolatile = type.isVolatileQualified();
  1514. if (!Size.isZero()) {
  1515. switch (trivialAutoVarInit) {
  1516. case LangOptions::TrivialAutoVarInitKind::Uninitialized:
  1517. llvm_unreachable("Uninitialized handled by caller");
  1518. case LangOptions::TrivialAutoVarInitKind::Zero:
  1519. if (CGM.stopAutoInit())
  1520. return;
  1521. emitStoresForZeroInit(CGM, D, Loc, isVolatile, Builder);
  1522. break;
  1523. case LangOptions::TrivialAutoVarInitKind::Pattern:
  1524. if (CGM.stopAutoInit())
  1525. return;
  1526. emitStoresForPatternInit(CGM, D, Loc, isVolatile, Builder);
  1527. break;
  1528. }
  1529. return;
  1530. }
  1531. // VLAs look zero-sized to getTypeInfo. We can't emit constant stores to
  1532. // them, so emit a memcpy with the VLA size to initialize each element.
  1533. // Technically zero-sized or negative-sized VLAs are undefined, and UBSan
  1534. // will catch that code, but there exists code which generates zero-sized
  1535. // VLAs. Be nice and initialize whatever they requested.
  1536. const auto *VlaType = getContext().getAsVariableArrayType(type);
  1537. if (!VlaType)
  1538. return;
  1539. auto VlaSize = getVLASize(VlaType);
  1540. auto SizeVal = VlaSize.NumElts;
  1541. CharUnits EltSize = getContext().getTypeSizeInChars(VlaSize.Type);
  1542. switch (trivialAutoVarInit) {
  1543. case LangOptions::TrivialAutoVarInitKind::Uninitialized:
  1544. llvm_unreachable("Uninitialized handled by caller");
  1545. case LangOptions::TrivialAutoVarInitKind::Zero: {
  1546. if (CGM.stopAutoInit())
  1547. return;
  1548. if (!EltSize.isOne())
  1549. SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
  1550. auto *I = Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0),
  1551. SizeVal, isVolatile);
  1552. I->addAnnotationMetadata("auto-init");
  1553. break;
  1554. }
  1555. case LangOptions::TrivialAutoVarInitKind::Pattern: {
  1556. if (CGM.stopAutoInit())
  1557. return;
  1558. llvm::Type *ElTy = Loc.getElementType();
  1559. llvm::Constant *Constant = constWithPadding(
  1560. CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));
  1561. CharUnits ConstantAlign = getContext().getTypeAlignInChars(VlaSize.Type);
  1562. llvm::BasicBlock *SetupBB = createBasicBlock("vla-setup.loop");
  1563. llvm::BasicBlock *LoopBB = createBasicBlock("vla-init.loop");
  1564. llvm::BasicBlock *ContBB = createBasicBlock("vla-init.cont");
  1565. llvm::Value *IsZeroSizedVLA = Builder.CreateICmpEQ(
  1566. SizeVal, llvm::ConstantInt::get(SizeVal->getType(), 0),
  1567. "vla.iszerosized");
  1568. Builder.CreateCondBr(IsZeroSizedVLA, ContBB, SetupBB);
  1569. EmitBlock(SetupBB);
  1570. if (!EltSize.isOne())
  1571. SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
  1572. llvm::Value *BaseSizeInChars =
  1573. llvm::ConstantInt::get(IntPtrTy, EltSize.getQuantity());
  1574. Address Begin = Builder.CreateElementBitCast(Loc, Int8Ty, "vla.begin");
  1575. llvm::Value *End = Builder.CreateInBoundsGEP(
  1576. Begin.getElementType(), Begin.getPointer(), SizeVal, "vla.end");
  1577. llvm::BasicBlock *OriginBB = Builder.GetInsertBlock();
  1578. EmitBlock(LoopBB);
  1579. llvm::PHINode *Cur = Builder.CreatePHI(Begin.getType(), 2, "vla.cur");
  1580. Cur->addIncoming(Begin.getPointer(), OriginBB);
  1581. CharUnits CurAlign = Loc.getAlignment().alignmentOfArrayElement(EltSize);
  1582. auto *I =
  1583. Builder.CreateMemCpy(Address(Cur, Int8Ty, CurAlign),
  1584. createUnnamedGlobalForMemcpyFrom(
  1585. CGM, D, Builder, Constant, ConstantAlign),
  1586. BaseSizeInChars, isVolatile);
  1587. I->addAnnotationMetadata("auto-init");
  1588. llvm::Value *Next =
  1589. Builder.CreateInBoundsGEP(Int8Ty, Cur, BaseSizeInChars, "vla.next");
  1590. llvm::Value *Done = Builder.CreateICmpEQ(Next, End, "vla-init.isdone");
  1591. Builder.CreateCondBr(Done, ContBB, LoopBB);
  1592. Cur->addIncoming(Next, LoopBB);
  1593. EmitBlock(ContBB);
  1594. } break;
  1595. }
  1596. }
  1597. void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
  1598. assert(emission.Variable && "emission was not valid!");
  1599. // If this was emitted as a global constant, we're done.
  1600. if (emission.wasEmittedAsGlobal()) return;
  1601. const VarDecl &D = *emission.Variable;
  1602. auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
  1603. QualType type = D.getType();
  1604. // If this local has an initializer, emit it now.
  1605. const Expr *Init = D.getInit();
  1606. // If we are at an unreachable point, we don't need to emit the initializer
  1607. // unless it contains a label.
  1608. if (!HaveInsertPoint()) {
  1609. if (!Init || !ContainsLabel(Init)) return;
  1610. EnsureInsertPoint();
  1611. }
  1612. // Initialize the structure of a __block variable.
  1613. if (emission.IsEscapingByRef)
  1614. emitByrefStructureInit(emission);
  1615. // Initialize the variable here if it doesn't have a initializer and it is a
  1616. // C struct that is non-trivial to initialize or an array containing such a
  1617. // struct.
  1618. if (!Init &&
  1619. type.isNonTrivialToPrimitiveDefaultInitialize() ==
  1620. QualType::PDIK_Struct) {
  1621. LValue Dst = MakeAddrLValue(emission.getAllocatedAddress(), type);
  1622. if (emission.IsEscapingByRef)
  1623. drillIntoBlockVariable(*this, Dst, &D);
  1624. defaultInitNonTrivialCStructVar(Dst);
  1625. return;
  1626. }
  1627. // Check whether this is a byref variable that's potentially
  1628. // captured and moved by its own initializer. If so, we'll need to
  1629. // emit the initializer first, then copy into the variable.
  1630. bool capturedByInit =
  1631. Init && emission.IsEscapingByRef && isCapturedBy(D, Init);
  1632. bool locIsByrefHeader = !capturedByInit;
  1633. const Address Loc =
  1634. locIsByrefHeader ? emission.getObjectAddress(*this) : emission.Addr;
  1635. // Note: constexpr already initializes everything correctly.
  1636. LangOptions::TrivialAutoVarInitKind trivialAutoVarInit =
  1637. (D.isConstexpr()
  1638. ? LangOptions::TrivialAutoVarInitKind::Uninitialized
  1639. : (D.getAttr<UninitializedAttr>()
  1640. ? LangOptions::TrivialAutoVarInitKind::Uninitialized
  1641. : getContext().getLangOpts().getTrivialAutoVarInit()));
  1642. auto initializeWhatIsTechnicallyUninitialized = [&](Address Loc) {
  1643. if (trivialAutoVarInit ==
  1644. LangOptions::TrivialAutoVarInitKind::Uninitialized)
  1645. return;
  1646. // Only initialize a __block's storage: we always initialize the header.
  1647. if (emission.IsEscapingByRef && !locIsByrefHeader)
  1648. Loc = emitBlockByrefAddress(Loc, &D, /*follow=*/false);
  1649. return emitZeroOrPatternForAutoVarInit(type, D, Loc);
  1650. };
  1651. if (isTrivialInitializer(Init))
  1652. return initializeWhatIsTechnicallyUninitialized(Loc);
  1653. llvm::Constant *constant = nullptr;
  1654. if (emission.IsConstantAggregate ||
  1655. D.mightBeUsableInConstantExpressions(getContext())) {
  1656. assert(!capturedByInit && "constant init contains a capturing block?");
  1657. constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(D);
  1658. if (constant && !constant->isZeroValue() &&
  1659. (trivialAutoVarInit !=
  1660. LangOptions::TrivialAutoVarInitKind::Uninitialized)) {
  1661. IsPattern isPattern =
  1662. (trivialAutoVarInit == LangOptions::TrivialAutoVarInitKind::Pattern)
  1663. ? IsPattern::Yes
  1664. : IsPattern::No;
  1665. // C guarantees that brace-init with fewer initializers than members in
  1666. // the aggregate will initialize the rest of the aggregate as-if it were
  1667. // static initialization. In turn static initialization guarantees that
  1668. // padding is initialized to zero bits. We could instead pattern-init if D
  1669. // has any ImplicitValueInitExpr, but that seems to be unintuitive
  1670. // behavior.
  1671. constant = constWithPadding(CGM, IsPattern::No,
  1672. replaceUndef(CGM, isPattern, constant));
  1673. }
  1674. }
  1675. if (!constant) {
  1676. initializeWhatIsTechnicallyUninitialized(Loc);
  1677. LValue lv = MakeAddrLValue(Loc, type);
  1678. lv.setNonGC(true);
  1679. return EmitExprAsInit(Init, &D, lv, capturedByInit);
  1680. }
  1681. if (!emission.IsConstantAggregate) {
  1682. // For simple scalar/complex initialization, store the value directly.
  1683. LValue lv = MakeAddrLValue(Loc, type);
  1684. lv.setNonGC(true);
  1685. return EmitStoreThroughLValue(RValue::get(constant), lv, true);
  1686. }
  1687. emitStoresForConstant(CGM, D, Builder.CreateElementBitCast(Loc, CGM.Int8Ty),
  1688. type.isVolatileQualified(), Builder, constant,
  1689. /*IsAutoInit=*/false);
  1690. }
  1691. /// Emit an expression as an initializer for an object (variable, field, etc.)
  1692. /// at the given location. The expression is not necessarily the normal
  1693. /// initializer for the object, and the address is not necessarily
  1694. /// its normal location.
  1695. ///
  1696. /// \param init the initializing expression
  1697. /// \param D the object to act as if we're initializing
  1698. /// \param lvalue the lvalue to initialize
  1699. /// \param capturedByInit true if \p D is a __block variable
  1700. /// whose address is potentially changed by the initializer
  1701. void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
  1702. LValue lvalue, bool capturedByInit) {
  1703. QualType type = D->getType();
  1704. if (type->isReferenceType()) {
  1705. RValue rvalue = EmitReferenceBindingToExpr(init);
  1706. if (capturedByInit)
  1707. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  1708. EmitStoreThroughLValue(rvalue, lvalue, true);
  1709. return;
  1710. }
  1711. switch (getEvaluationKind(type)) {
  1712. case TEK_Scalar:
  1713. EmitScalarInit(init, D, lvalue, capturedByInit);
  1714. return;
  1715. case TEK_Complex: {
  1716. ComplexPairTy complex = EmitComplexExpr(init);
  1717. if (capturedByInit)
  1718. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  1719. EmitStoreOfComplex(complex, lvalue, /*init*/ true);
  1720. return;
  1721. }
  1722. case TEK_Aggregate:
  1723. if (type->isAtomicType()) {
  1724. EmitAtomicInit(const_cast<Expr*>(init), lvalue);
  1725. } else {
  1726. AggValueSlot::Overlap_t Overlap = AggValueSlot::MayOverlap;
  1727. if (isa<VarDecl>(D))
  1728. Overlap = AggValueSlot::DoesNotOverlap;
  1729. else if (auto *FD = dyn_cast<FieldDecl>(D))
  1730. Overlap = getOverlapForFieldInit(FD);
  1731. // TODO: how can we delay here if D is captured by its initializer?
  1732. EmitAggExpr(init, AggValueSlot::forLValue(
  1733. lvalue, *this, AggValueSlot::IsDestructed,
  1734. AggValueSlot::DoesNotNeedGCBarriers,
  1735. AggValueSlot::IsNotAliased, Overlap));
  1736. }
  1737. return;
  1738. }
  1739. llvm_unreachable("bad evaluation kind");
  1740. }
  1741. /// Enter a destroy cleanup for the given local variable.
  1742. void CodeGenFunction::emitAutoVarTypeCleanup(
  1743. const CodeGenFunction::AutoVarEmission &emission,
  1744. QualType::DestructionKind dtorKind) {
  1745. assert(dtorKind != QualType::DK_none);
  1746. // Note that for __block variables, we want to destroy the
  1747. // original stack object, not the possibly forwarded object.
  1748. Address addr = emission.getObjectAddress(*this);
  1749. const VarDecl *var = emission.Variable;
  1750. QualType type = var->getType();
  1751. CleanupKind cleanupKind = NormalAndEHCleanup;
  1752. CodeGenFunction::Destroyer *destroyer = nullptr;
  1753. switch (dtorKind) {
  1754. case QualType::DK_none:
  1755. llvm_unreachable("no cleanup for trivially-destructible variable");
  1756. case QualType::DK_cxx_destructor:
  1757. // If there's an NRVO flag on the emission, we need a different
  1758. // cleanup.
  1759. if (emission.NRVOFlag) {
  1760. assert(!type->isArrayType());
  1761. CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
  1762. EHStack.pushCleanup<DestroyNRVOVariableCXX>(cleanupKind, addr, type, dtor,
  1763. emission.NRVOFlag);
  1764. return;
  1765. }
  1766. break;
  1767. case QualType::DK_objc_strong_lifetime:
  1768. // Suppress cleanups for pseudo-strong variables.
  1769. if (var->isARCPseudoStrong()) return;
  1770. // Otherwise, consider whether to use an EH cleanup or not.
  1771. cleanupKind = getARCCleanupKind();
  1772. // Use the imprecise destroyer by default.
  1773. if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
  1774. destroyer = CodeGenFunction::destroyARCStrongImprecise;
  1775. break;
  1776. case QualType::DK_objc_weak_lifetime:
  1777. break;
  1778. case QualType::DK_nontrivial_c_struct:
  1779. destroyer = CodeGenFunction::destroyNonTrivialCStruct;
  1780. if (emission.NRVOFlag) {
  1781. assert(!type->isArrayType());
  1782. EHStack.pushCleanup<DestroyNRVOVariableC>(cleanupKind, addr,
  1783. emission.NRVOFlag, type);
  1784. return;
  1785. }
  1786. break;
  1787. }
  1788. // If we haven't chosen a more specific destroyer, use the default.
  1789. if (!destroyer) destroyer = getDestroyer(dtorKind);
  1790. // Use an EH cleanup in array destructors iff the destructor itself
  1791. // is being pushed as an EH cleanup.
  1792. bool useEHCleanup = (cleanupKind & EHCleanup);
  1793. EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
  1794. useEHCleanup);
  1795. }
  1796. void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
  1797. assert(emission.Variable && "emission was not valid!");
  1798. // If this was emitted as a global constant, we're done.
  1799. if (emission.wasEmittedAsGlobal()) return;
  1800. // If we don't have an insertion point, we're done. Sema prevents
  1801. // us from jumping into any of these scopes anyway.
  1802. if (!HaveInsertPoint()) return;
  1803. const VarDecl &D = *emission.Variable;
  1804. // Check the type for a cleanup.
  1805. if (QualType::DestructionKind dtorKind = D.needsDestruction(getContext()))
  1806. emitAutoVarTypeCleanup(emission, dtorKind);
  1807. // In GC mode, honor objc_precise_lifetime.
  1808. if (getLangOpts().getGC() != LangOptions::NonGC &&
  1809. D.hasAttr<ObjCPreciseLifetimeAttr>()) {
  1810. EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
  1811. }
  1812. // Handle the cleanup attribute.
  1813. if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
  1814. const FunctionDecl *FD = CA->getFunctionDecl();
  1815. llvm::Constant *F = CGM.GetAddrOfFunction(FD);
  1816. assert(F && "Could not find function!");
  1817. const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
  1818. EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
  1819. }
  1820. // If this is a block variable, call _Block_object_destroy
  1821. // (on the unforwarded address). Don't enter this cleanup if we're in pure-GC
  1822. // mode.
  1823. if (emission.IsEscapingByRef &&
  1824. CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
  1825. BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
  1826. if (emission.Variable->getType().isObjCGCWeak())
  1827. Flags |= BLOCK_FIELD_IS_WEAK;
  1828. enterByrefCleanup(NormalAndEHCleanup, emission.Addr, Flags,
  1829. /*LoadBlockVarAddr*/ false,
  1830. cxxDestructorCanThrow(emission.Variable->getType()));
  1831. }
  1832. }
  1833. CodeGenFunction::Destroyer *
  1834. CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
  1835. switch (kind) {
  1836. case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
  1837. case QualType::DK_cxx_destructor:
  1838. return destroyCXXObject;
  1839. case QualType::DK_objc_strong_lifetime:
  1840. return destroyARCStrongPrecise;
  1841. case QualType::DK_objc_weak_lifetime:
  1842. return destroyARCWeak;
  1843. case QualType::DK_nontrivial_c_struct:
  1844. return destroyNonTrivialCStruct;
  1845. }
  1846. llvm_unreachable("Unknown DestructionKind");
  1847. }
  1848. /// pushEHDestroy - Push the standard destructor for the given type as
  1849. /// an EH-only cleanup.
  1850. void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
  1851. Address addr, QualType type) {
  1852. assert(dtorKind && "cannot push destructor for trivial type");
  1853. assert(needsEHCleanup(dtorKind));
  1854. pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
  1855. }
  1856. /// pushDestroy - Push the standard destructor for the given type as
  1857. /// at least a normal cleanup.
  1858. void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
  1859. Address addr, QualType type) {
  1860. assert(dtorKind && "cannot push destructor for trivial type");
  1861. CleanupKind cleanupKind = getCleanupKind(dtorKind);
  1862. pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
  1863. cleanupKind & EHCleanup);
  1864. }
  1865. void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
  1866. QualType type, Destroyer *destroyer,
  1867. bool useEHCleanupForArray) {
  1868. pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
  1869. destroyer, useEHCleanupForArray);
  1870. }
  1871. void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
  1872. EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
  1873. }
  1874. void CodeGenFunction::pushLifetimeExtendedDestroy(CleanupKind cleanupKind,
  1875. Address addr, QualType type,
  1876. Destroyer *destroyer,
  1877. bool useEHCleanupForArray) {
  1878. // If we're not in a conditional branch, we don't need to bother generating a
  1879. // conditional cleanup.
  1880. if (!isInConditionalBranch()) {
  1881. // Push an EH-only cleanup for the object now.
  1882. // FIXME: When popping normal cleanups, we need to keep this EH cleanup
  1883. // around in case a temporary's destructor throws an exception.
  1884. if (cleanupKind & EHCleanup)
  1885. EHStack.pushCleanup<DestroyObject>(
  1886. static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
  1887. destroyer, useEHCleanupForArray);
  1888. return pushCleanupAfterFullExprWithActiveFlag<DestroyObject>(
  1889. cleanupKind, Address::invalid(), addr, type, destroyer, useEHCleanupForArray);
  1890. }
  1891. // Otherwise, we should only destroy the object if it's been initialized.
  1892. // Re-use the active flag and saved address across both the EH and end of
  1893. // scope cleanups.
  1894. using SavedType = typename DominatingValue<Address>::saved_type;
  1895. using ConditionalCleanupType =
  1896. EHScopeStack::ConditionalCleanup<DestroyObject, Address, QualType,
  1897. Destroyer *, bool>;
  1898. Address ActiveFlag = createCleanupActiveFlag();
  1899. SavedType SavedAddr = saveValueInCond(addr);
  1900. if (cleanupKind & EHCleanup) {
  1901. EHStack.pushCleanup<ConditionalCleanupType>(
  1902. static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), SavedAddr, type,
  1903. destroyer, useEHCleanupForArray);
  1904. initFullExprCleanupWithFlag(ActiveFlag);
  1905. }
  1906. pushCleanupAfterFullExprWithActiveFlag<ConditionalCleanupType>(
  1907. cleanupKind, ActiveFlag, SavedAddr, type, destroyer,
  1908. useEHCleanupForArray);
  1909. }
  1910. /// emitDestroy - Immediately perform the destruction of the given
  1911. /// object.
  1912. ///
  1913. /// \param addr - the address of the object; a type*
  1914. /// \param type - the type of the object; if an array type, all
  1915. /// objects are destroyed in reverse order
  1916. /// \param destroyer - the function to call to destroy individual
  1917. /// elements
  1918. /// \param useEHCleanupForArray - whether an EH cleanup should be
  1919. /// used when destroying array elements, in case one of the
  1920. /// destructions throws an exception
  1921. void CodeGenFunction::emitDestroy(Address addr, QualType type,
  1922. Destroyer *destroyer,
  1923. bool useEHCleanupForArray) {
  1924. const ArrayType *arrayType = getContext().getAsArrayType(type);
  1925. if (!arrayType)
  1926. return destroyer(*this, addr, type);
  1927. llvm::Value *length = emitArrayLength(arrayType, type, addr);
  1928. CharUnits elementAlign =
  1929. addr.getAlignment()
  1930. .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
  1931. // Normally we have to check whether the array is zero-length.
  1932. bool checkZeroLength = true;
  1933. // But if the array length is constant, we can suppress that.
  1934. if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
  1935. // ...and if it's constant zero, we can just skip the entire thing.
  1936. if (constLength->isZero()) return;
  1937. checkZeroLength = false;
  1938. }
  1939. llvm::Value *begin = addr.getPointer();
  1940. llvm::Value *end =
  1941. Builder.CreateInBoundsGEP(addr.getElementType(), begin, length);
  1942. emitArrayDestroy(begin, end, type, elementAlign, destroyer,
  1943. checkZeroLength, useEHCleanupForArray);
  1944. }
  1945. /// emitArrayDestroy - Destroys all the elements of the given array,
  1946. /// beginning from last to first. The array cannot be zero-length.
  1947. ///
  1948. /// \param begin - a type* denoting the first element of the array
  1949. /// \param end - a type* denoting one past the end of the array
  1950. /// \param elementType - the element type of the array
  1951. /// \param destroyer - the function to call to destroy elements
  1952. /// \param useEHCleanup - whether to push an EH cleanup to destroy
  1953. /// the remaining elements in case the destruction of a single
  1954. /// element throws
  1955. void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
  1956. llvm::Value *end,
  1957. QualType elementType,
  1958. CharUnits elementAlign,
  1959. Destroyer *destroyer,
  1960. bool checkZeroLength,
  1961. bool useEHCleanup) {
  1962. assert(!elementType->isArrayType());
  1963. // The basic structure here is a do-while loop, because we don't
  1964. // need to check for the zero-element case.
  1965. llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
  1966. llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
  1967. if (checkZeroLength) {
  1968. llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
  1969. "arraydestroy.isempty");
  1970. Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
  1971. }
  1972. // Enter the loop body, making that address the current address.
  1973. llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
  1974. EmitBlock(bodyBB);
  1975. llvm::PHINode *elementPast =
  1976. Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
  1977. elementPast->addIncoming(end, entryBB);
  1978. // Shift the address back by one element.
  1979. llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
  1980. llvm::Type *llvmElementType = ConvertTypeForMem(elementType);
  1981. llvm::Value *element = Builder.CreateInBoundsGEP(
  1982. llvmElementType, elementPast, negativeOne, "arraydestroy.element");
  1983. if (useEHCleanup)
  1984. pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
  1985. destroyer);
  1986. // Perform the actual destruction there.
  1987. destroyer(*this, Address(element, llvmElementType, elementAlign),
  1988. elementType);
  1989. if (useEHCleanup)
  1990. PopCleanupBlock();
  1991. // Check whether we've reached the end.
  1992. llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
  1993. Builder.CreateCondBr(done, doneBB, bodyBB);
  1994. elementPast->addIncoming(element, Builder.GetInsertBlock());
  1995. // Done.
  1996. EmitBlock(doneBB);
  1997. }
  1998. /// Perform partial array destruction as if in an EH cleanup. Unlike
  1999. /// emitArrayDestroy, the element type here may still be an array type.
  2000. static void emitPartialArrayDestroy(CodeGenFunction &CGF,
  2001. llvm::Value *begin, llvm::Value *end,
  2002. QualType type, CharUnits elementAlign,
  2003. CodeGenFunction::Destroyer *destroyer) {
  2004. llvm::Type *elemTy = CGF.ConvertTypeForMem(type);
  2005. // If the element type is itself an array, drill down.
  2006. unsigned arrayDepth = 0;
  2007. while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
  2008. // VLAs don't require a GEP index to walk into.
  2009. if (!isa<VariableArrayType>(arrayType))
  2010. arrayDepth++;
  2011. type = arrayType->getElementType();
  2012. }
  2013. if (arrayDepth) {
  2014. llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
  2015. SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
  2016. begin = CGF.Builder.CreateInBoundsGEP(
  2017. elemTy, begin, gepIndices, "pad.arraybegin");
  2018. end = CGF.Builder.CreateInBoundsGEP(
  2019. elemTy, end, gepIndices, "pad.arrayend");
  2020. }
  2021. // Destroy the array. We don't ever need an EH cleanup because we
  2022. // assume that we're in an EH cleanup ourselves, so a throwing
  2023. // destructor causes an immediate terminate.
  2024. CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
  2025. /*checkZeroLength*/ true, /*useEHCleanup*/ false);
  2026. }
  2027. namespace {
  2028. /// RegularPartialArrayDestroy - a cleanup which performs a partial
  2029. /// array destroy where the end pointer is regularly determined and
  2030. /// does not need to be loaded from a local.
  2031. class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
  2032. llvm::Value *ArrayBegin;
  2033. llvm::Value *ArrayEnd;
  2034. QualType ElementType;
  2035. CodeGenFunction::Destroyer *Destroyer;
  2036. CharUnits ElementAlign;
  2037. public:
  2038. RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
  2039. QualType elementType, CharUnits elementAlign,
  2040. CodeGenFunction::Destroyer *destroyer)
  2041. : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
  2042. ElementType(elementType), Destroyer(destroyer),
  2043. ElementAlign(elementAlign) {}
  2044. void Emit(CodeGenFunction &CGF, Flags flags) override {
  2045. emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
  2046. ElementType, ElementAlign, Destroyer);
  2047. }
  2048. };
  2049. /// IrregularPartialArrayDestroy - a cleanup which performs a
  2050. /// partial array destroy where the end pointer is irregularly
  2051. /// determined and must be loaded from a local.
  2052. class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
  2053. llvm::Value *ArrayBegin;
  2054. Address ArrayEndPointer;
  2055. QualType ElementType;
  2056. CodeGenFunction::Destroyer *Destroyer;
  2057. CharUnits ElementAlign;
  2058. public:
  2059. IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
  2060. Address arrayEndPointer,
  2061. QualType elementType,
  2062. CharUnits elementAlign,
  2063. CodeGenFunction::Destroyer *destroyer)
  2064. : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
  2065. ElementType(elementType), Destroyer(destroyer),
  2066. ElementAlign(elementAlign) {}
  2067. void Emit(CodeGenFunction &CGF, Flags flags) override {
  2068. llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
  2069. emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
  2070. ElementType, ElementAlign, Destroyer);
  2071. }
  2072. };
  2073. } // end anonymous namespace
  2074. /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
  2075. /// already-constructed elements of the given array. The cleanup
  2076. /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
  2077. ///
  2078. /// \param elementType - the immediate element type of the array;
  2079. /// possibly still an array type
  2080. void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
  2081. Address arrayEndPointer,
  2082. QualType elementType,
  2083. CharUnits elementAlign,
  2084. Destroyer *destroyer) {
  2085. pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
  2086. arrayBegin, arrayEndPointer,
  2087. elementType, elementAlign,
  2088. destroyer);
  2089. }
  2090. /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
  2091. /// already-constructed elements of the given array. The cleanup
  2092. /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
  2093. ///
  2094. /// \param elementType - the immediate element type of the array;
  2095. /// possibly still an array type
  2096. void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
  2097. llvm::Value *arrayEnd,
  2098. QualType elementType,
  2099. CharUnits elementAlign,
  2100. Destroyer *destroyer) {
  2101. pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
  2102. arrayBegin, arrayEnd,
  2103. elementType, elementAlign,
  2104. destroyer);
  2105. }
  2106. /// Lazily declare the @llvm.lifetime.start intrinsic.
  2107. llvm::Function *CodeGenModule::getLLVMLifetimeStartFn() {
  2108. if (LifetimeStartFn)
  2109. return LifetimeStartFn;
  2110. LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
  2111. llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);
  2112. return LifetimeStartFn;
  2113. }
  2114. /// Lazily declare the @llvm.lifetime.end intrinsic.
  2115. llvm::Function *CodeGenModule::getLLVMLifetimeEndFn() {
  2116. if (LifetimeEndFn)
  2117. return LifetimeEndFn;
  2118. LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
  2119. llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);
  2120. return LifetimeEndFn;
  2121. }
  2122. namespace {
  2123. /// A cleanup to perform a release of an object at the end of a
  2124. /// function. This is used to balance out the incoming +1 of a
  2125. /// ns_consumed argument when we can't reasonably do that just by
  2126. /// not doing the initial retain for a __block argument.
  2127. struct ConsumeARCParameter final : EHScopeStack::Cleanup {
  2128. ConsumeARCParameter(llvm::Value *param,
  2129. ARCPreciseLifetime_t precise)
  2130. : Param(param), Precise(precise) {}
  2131. llvm::Value *Param;
  2132. ARCPreciseLifetime_t Precise;
  2133. void Emit(CodeGenFunction &CGF, Flags flags) override {
  2134. CGF.EmitARCRelease(Param, Precise);
  2135. }
  2136. };
  2137. } // end anonymous namespace
  2138. /// Emit an alloca (or GlobalValue depending on target)
  2139. /// for the specified parameter and set up LocalDeclMap.
  2140. void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
  2141. unsigned ArgNo) {
  2142. bool NoDebugInfo = false;
  2143. // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
  2144. assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
  2145. "Invalid argument to EmitParmDecl");
  2146. Arg.getAnyValue()->setName(D.getName());
  2147. QualType Ty = D.getType();
  2148. // Use better IR generation for certain implicit parameters.
  2149. if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
  2150. // The only implicit argument a block has is its literal.
  2151. // This may be passed as an inalloca'ed value on Windows x86.
  2152. if (BlockInfo) {
  2153. llvm::Value *V = Arg.isIndirect()
  2154. ? Builder.CreateLoad(Arg.getIndirectAddress())
  2155. : Arg.getDirectValue();
  2156. setBlockContextParameter(IPD, ArgNo, V);
  2157. return;
  2158. }
  2159. // Suppressing debug info for ThreadPrivateVar parameters, else it hides
  2160. // debug info of TLS variables.
  2161. NoDebugInfo =
  2162. (IPD->getParameterKind() == ImplicitParamDecl::ThreadPrivateVar);
  2163. }
  2164. Address DeclPtr = Address::invalid();
  2165. Address AllocaPtr = Address::invalid();
  2166. bool DoStore = false;
  2167. bool IsScalar = hasScalarEvaluationKind(Ty);
  2168. // If we already have a pointer to the argument, reuse the input pointer.
  2169. if (Arg.isIndirect()) {
  2170. // If we have a prettier pointer type at this point, bitcast to that.
  2171. DeclPtr = Arg.getIndirectAddress();
  2172. DeclPtr = Builder.CreateElementBitCast(DeclPtr, ConvertTypeForMem(Ty),
  2173. D.getName());
  2174. // Indirect argument is in alloca address space, which may be different
  2175. // from the default address space.
  2176. auto AllocaAS = CGM.getASTAllocaAddressSpace();
  2177. auto *V = DeclPtr.getPointer();
  2178. AllocaPtr = DeclPtr;
  2179. auto SrcLangAS = getLangOpts().OpenCL ? LangAS::opencl_private : AllocaAS;
  2180. auto DestLangAS =
  2181. getLangOpts().OpenCL ? LangAS::opencl_private : LangAS::Default;
  2182. if (SrcLangAS != DestLangAS) {
  2183. assert(getContext().getTargetAddressSpace(SrcLangAS) ==
  2184. CGM.getDataLayout().getAllocaAddrSpace());
  2185. auto DestAS = getContext().getTargetAddressSpace(DestLangAS);
  2186. auto *T = DeclPtr.getElementType()->getPointerTo(DestAS);
  2187. DeclPtr = DeclPtr.withPointer(getTargetHooks().performAddrSpaceCast(
  2188. *this, V, SrcLangAS, DestLangAS, T, true));
  2189. }
  2190. // Push a destructor cleanup for this parameter if the ABI requires it.
  2191. // Don't push a cleanup in a thunk for a method that will also emit a
  2192. // cleanup.
  2193. if (Ty->isRecordType() && !CurFuncIsThunk &&
  2194. Ty->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
  2195. if (QualType::DestructionKind DtorKind =
  2196. D.needsDestruction(getContext())) {
  2197. assert((DtorKind == QualType::DK_cxx_destructor ||
  2198. DtorKind == QualType::DK_nontrivial_c_struct) &&
  2199. "unexpected destructor type");
  2200. pushDestroy(DtorKind, DeclPtr, Ty);
  2201. CalleeDestructedParamCleanups[cast<ParmVarDecl>(&D)] =
  2202. EHStack.stable_begin();
  2203. }
  2204. }
  2205. } else {
  2206. // Check if the parameter address is controlled by OpenMP runtime.
  2207. Address OpenMPLocalAddr =
  2208. getLangOpts().OpenMP
  2209. ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
  2210. : Address::invalid();
  2211. if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
  2212. DeclPtr = OpenMPLocalAddr;
  2213. AllocaPtr = DeclPtr;
  2214. } else {
  2215. // Otherwise, create a temporary to hold the value.
  2216. DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
  2217. D.getName() + ".addr", &AllocaPtr);
  2218. }
  2219. DoStore = true;
  2220. }
  2221. llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
  2222. LValue lv = MakeAddrLValue(DeclPtr, Ty);
  2223. if (IsScalar) {
  2224. Qualifiers qs = Ty.getQualifiers();
  2225. if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
  2226. // We honor __attribute__((ns_consumed)) for types with lifetime.
  2227. // For __strong, it's handled by just skipping the initial retain;
  2228. // otherwise we have to balance out the initial +1 with an extra
  2229. // cleanup to do the release at the end of the function.
  2230. bool isConsumed = D.hasAttr<NSConsumedAttr>();
  2231. // If a parameter is pseudo-strong then we can omit the implicit retain.
  2232. if (D.isARCPseudoStrong()) {
  2233. assert(lt == Qualifiers::OCL_Strong &&
  2234. "pseudo-strong variable isn't strong?");
  2235. assert(qs.hasConst() && "pseudo-strong variable should be const!");
  2236. lt = Qualifiers::OCL_ExplicitNone;
  2237. }
  2238. // Load objects passed indirectly.
  2239. if (Arg.isIndirect() && !ArgVal)
  2240. ArgVal = Builder.CreateLoad(DeclPtr);
  2241. if (lt == Qualifiers::OCL_Strong) {
  2242. if (!isConsumed) {
  2243. if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
  2244. // use objc_storeStrong(&dest, value) for retaining the
  2245. // object. But first, store a null into 'dest' because
  2246. // objc_storeStrong attempts to release its old value.
  2247. llvm::Value *Null = CGM.EmitNullConstant(D.getType());
  2248. EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
  2249. EmitARCStoreStrongCall(lv.getAddress(*this), ArgVal, true);
  2250. DoStore = false;
  2251. }
  2252. else
  2253. // Don't use objc_retainBlock for block pointers, because we
  2254. // don't want to Block_copy something just because we got it
  2255. // as a parameter.
  2256. ArgVal = EmitARCRetainNonBlock(ArgVal);
  2257. }
  2258. } else {
  2259. // Push the cleanup for a consumed parameter.
  2260. if (isConsumed) {
  2261. ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
  2262. ? ARCPreciseLifetime : ARCImpreciseLifetime);
  2263. EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
  2264. precise);
  2265. }
  2266. if (lt == Qualifiers::OCL_Weak) {
  2267. EmitARCInitWeak(DeclPtr, ArgVal);
  2268. DoStore = false; // The weak init is a store, no need to do two.
  2269. }
  2270. }
  2271. // Enter the cleanup scope.
  2272. EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
  2273. }
  2274. }
  2275. // Store the initial value into the alloca.
  2276. if (DoStore)
  2277. EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
  2278. setAddrOfLocalVar(&D, DeclPtr);
  2279. // Emit debug info for param declarations in non-thunk functions.
  2280. if (CGDebugInfo *DI = getDebugInfo()) {
  2281. if (CGM.getCodeGenOpts().hasReducedDebugInfo() && !CurFuncIsThunk &&
  2282. !NoDebugInfo) {
  2283. llvm::DILocalVariable *DILocalVar = DI->EmitDeclareOfArgVariable(
  2284. &D, AllocaPtr.getPointer(), ArgNo, Builder);
  2285. if (const auto *Var = dyn_cast_or_null<ParmVarDecl>(&D))
  2286. DI->getParamDbgMappings().insert({Var, DILocalVar});
  2287. }
  2288. }
  2289. if (D.hasAttr<AnnotateAttr>())
  2290. EmitVarAnnotations(&D, DeclPtr.getPointer());
  2291. // We can only check return value nullability if all arguments to the
  2292. // function satisfy their nullability preconditions. This makes it necessary
  2293. // to emit null checks for args in the function body itself.
  2294. if (requiresReturnValueNullabilityCheck()) {
  2295. auto Nullability = Ty->getNullability();
  2296. if (Nullability && *Nullability == NullabilityKind::NonNull) {
  2297. SanitizerScope SanScope(this);
  2298. RetValNullabilityPrecondition =
  2299. Builder.CreateAnd(RetValNullabilityPrecondition,
  2300. Builder.CreateIsNotNull(Arg.getAnyValue()));
  2301. }
  2302. }
  2303. }
  2304. void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
  2305. CodeGenFunction *CGF) {
  2306. if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
  2307. return;
  2308. getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
  2309. }
  2310. void CodeGenModule::EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D,
  2311. CodeGenFunction *CGF) {
  2312. if (!LangOpts.OpenMP || LangOpts.OpenMPSimd ||
  2313. (!LangOpts.EmitAllDecls && !D->isUsed()))
  2314. return;
  2315. getOpenMPRuntime().emitUserDefinedMapper(D, CGF);
  2316. }
  2317. void CodeGenModule::EmitOMPRequiresDecl(const OMPRequiresDecl *D) {
  2318. getOpenMPRuntime().processRequiresDirective(D);
  2319. }
  2320. void CodeGenModule::EmitOMPAllocateDecl(const OMPAllocateDecl *D) {
  2321. for (const Expr *E : D->varlists()) {
  2322. const auto *DE = cast<DeclRefExpr>(E);
  2323. const auto *VD = cast<VarDecl>(DE->getDecl());
  2324. // Skip all but globals.
  2325. if (!VD->hasGlobalStorage())
  2326. continue;
  2327. // Check if the global has been materialized yet or not. If not, we are done
  2328. // as any later generation will utilize the OMPAllocateDeclAttr. However, if
  2329. // we already emitted the global we might have done so before the
  2330. // OMPAllocateDeclAttr was attached, leading to the wrong address space
  2331. // (potentially). While not pretty, common practise is to remove the old IR
  2332. // global and generate a new one, so we do that here too. Uses are replaced
  2333. // properly.
  2334. StringRef MangledName = getMangledName(VD);
  2335. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  2336. if (!Entry)
  2337. continue;
  2338. // We can also keep the existing global if the address space is what we
  2339. // expect it to be, if not, it is replaced.
  2340. QualType ASTTy = VD->getType();
  2341. clang::LangAS GVAS = GetGlobalVarAddressSpace(VD);
  2342. auto TargetAS = getContext().getTargetAddressSpace(GVAS);
  2343. if (Entry->getType()->getAddressSpace() == TargetAS)
  2344. continue;
  2345. // Make a new global with the correct type / address space.
  2346. llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
  2347. llvm::PointerType *PTy = llvm::PointerType::get(Ty, TargetAS);
  2348. // Replace all uses of the old global with a cast. Since we mutate the type
  2349. // in place we neeed an intermediate that takes the spot of the old entry
  2350. // until we can create the cast.
  2351. llvm::GlobalVariable *DummyGV = new llvm::GlobalVariable(
  2352. getModule(), Entry->getValueType(), false,
  2353. llvm::GlobalValue::CommonLinkage, nullptr, "dummy", nullptr,
  2354. llvm::GlobalVariable::NotThreadLocal, Entry->getAddressSpace());
  2355. Entry->replaceAllUsesWith(DummyGV);
  2356. Entry->mutateType(PTy);
  2357. llvm::Constant *NewPtrForOldDecl =
  2358. llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  2359. Entry, DummyGV->getType());
  2360. // Now we have a casted version of the changed global, the dummy can be
  2361. // replaced and deleted.
  2362. DummyGV->replaceAllUsesWith(NewPtrForOldDecl);
  2363. DummyGV->eraseFromParent();
  2364. }
  2365. }
  2366. std::optional<CharUnits>
  2367. CodeGenModule::getOMPAllocateAlignment(const VarDecl *VD) {
  2368. if (const auto *AA = VD->getAttr<OMPAllocateDeclAttr>()) {
  2369. if (Expr *Alignment = AA->getAlignment()) {
  2370. unsigned UserAlign =
  2371. Alignment->EvaluateKnownConstInt(getContext()).getExtValue();
  2372. CharUnits NaturalAlign =
  2373. getNaturalTypeAlignment(VD->getType().getNonReferenceType());
  2374. // OpenMP5.1 pg 185 lines 7-10
  2375. // Each item in the align modifier list must be aligned to the maximum
  2376. // of the specified alignment and the type's natural alignment.
  2377. return CharUnits::fromQuantity(
  2378. std::max<unsigned>(UserAlign, NaturalAlign.getQuantity()));
  2379. }
  2380. }
  2381. return std::nullopt;
  2382. }