CGDecl.cpp 97 KB

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