CGDecl.cpp 78 KB

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