CGDecl.cpp 93 KB

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