CGDecl.cpp 97 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534
  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::EmitAutoVarInit(const AutoVarEmission &emission) {
  1451. assert(emission.Variable && "emission was not valid!");
  1452. // If this was emitted as a global constant, we're done.
  1453. if (emission.wasEmittedAsGlobal()) return;
  1454. const VarDecl &D = *emission.Variable;
  1455. auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
  1456. QualType type = D.getType();
  1457. // If this local has an initializer, emit it now.
  1458. const Expr *Init = D.getInit();
  1459. // If we are at an unreachable point, we don't need to emit the initializer
  1460. // unless it contains a label.
  1461. if (!HaveInsertPoint()) {
  1462. if (!Init || !ContainsLabel(Init)) return;
  1463. EnsureInsertPoint();
  1464. }
  1465. // Initialize the structure of a __block variable.
  1466. if (emission.IsEscapingByRef)
  1467. emitByrefStructureInit(emission);
  1468. // Initialize the variable here if it doesn't have a initializer and it is a
  1469. // C struct that is non-trivial to initialize or an array containing such a
  1470. // struct.
  1471. if (!Init &&
  1472. type.isNonTrivialToPrimitiveDefaultInitialize() ==
  1473. QualType::PDIK_Struct) {
  1474. LValue Dst = MakeAddrLValue(emission.getAllocatedAddress(), type);
  1475. if (emission.IsEscapingByRef)
  1476. drillIntoBlockVariable(*this, Dst, &D);
  1477. defaultInitNonTrivialCStructVar(Dst);
  1478. return;
  1479. }
  1480. // Check whether this is a byref variable that's potentially
  1481. // captured and moved by its own initializer. If so, we'll need to
  1482. // emit the initializer first, then copy into the variable.
  1483. bool capturedByInit =
  1484. Init && emission.IsEscapingByRef && isCapturedBy(D, Init);
  1485. bool locIsByrefHeader = !capturedByInit;
  1486. const Address Loc =
  1487. locIsByrefHeader ? emission.getObjectAddress(*this) : emission.Addr;
  1488. // Note: constexpr already initializes everything correctly.
  1489. LangOptions::TrivialAutoVarInitKind trivialAutoVarInit =
  1490. (D.isConstexpr()
  1491. ? LangOptions::TrivialAutoVarInitKind::Uninitialized
  1492. : (D.getAttr<UninitializedAttr>()
  1493. ? LangOptions::TrivialAutoVarInitKind::Uninitialized
  1494. : getContext().getLangOpts().getTrivialAutoVarInit()));
  1495. auto initializeWhatIsTechnicallyUninitialized = [&](Address Loc) {
  1496. if (trivialAutoVarInit ==
  1497. LangOptions::TrivialAutoVarInitKind::Uninitialized)
  1498. return;
  1499. // Only initialize a __block's storage: we always initialize the header.
  1500. if (emission.IsEscapingByRef && !locIsByrefHeader)
  1501. Loc = emitBlockByrefAddress(Loc, &D, /*follow=*/false);
  1502. bool isVolatile = type.isVolatileQualified();
  1503. CharUnits Size = getContext().getTypeSizeInChars(type);
  1504. if (!Size.isZero()) {
  1505. switch (trivialAutoVarInit) {
  1506. case LangOptions::TrivialAutoVarInitKind::Uninitialized:
  1507. llvm_unreachable("Uninitialized handled above");
  1508. case LangOptions::TrivialAutoVarInitKind::Zero:
  1509. emitStoresForZeroInit(CGM, D, Loc, isVolatile, Builder);
  1510. break;
  1511. case LangOptions::TrivialAutoVarInitKind::Pattern:
  1512. emitStoresForPatternInit(CGM, D, Loc, isVolatile, Builder);
  1513. break;
  1514. }
  1515. return;
  1516. }
  1517. // VLAs look zero-sized to getTypeInfo. We can't emit constant stores to
  1518. // them, so emit a memcpy with the VLA size to initialize each element.
  1519. // Technically zero-sized or negative-sized VLAs are undefined, and UBSan
  1520. // will catch that code, but there exists code which generates zero-sized
  1521. // VLAs. Be nice and initialize whatever they requested.
  1522. const auto *VlaType = getContext().getAsVariableArrayType(type);
  1523. if (!VlaType)
  1524. return;
  1525. auto VlaSize = getVLASize(VlaType);
  1526. auto SizeVal = VlaSize.NumElts;
  1527. CharUnits EltSize = getContext().getTypeSizeInChars(VlaSize.Type);
  1528. switch (trivialAutoVarInit) {
  1529. case LangOptions::TrivialAutoVarInitKind::Uninitialized:
  1530. llvm_unreachable("Uninitialized handled above");
  1531. case LangOptions::TrivialAutoVarInitKind::Zero:
  1532. if (!EltSize.isOne())
  1533. SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
  1534. Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
  1535. isVolatile);
  1536. break;
  1537. case LangOptions::TrivialAutoVarInitKind::Pattern: {
  1538. llvm::Type *ElTy = Loc.getElementType();
  1539. llvm::Constant *Constant = constWithPadding(
  1540. CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));
  1541. CharUnits ConstantAlign = getContext().getTypeAlignInChars(VlaSize.Type);
  1542. llvm::BasicBlock *SetupBB = createBasicBlock("vla-setup.loop");
  1543. llvm::BasicBlock *LoopBB = createBasicBlock("vla-init.loop");
  1544. llvm::BasicBlock *ContBB = createBasicBlock("vla-init.cont");
  1545. llvm::Value *IsZeroSizedVLA = Builder.CreateICmpEQ(
  1546. SizeVal, llvm::ConstantInt::get(SizeVal->getType(), 0),
  1547. "vla.iszerosized");
  1548. Builder.CreateCondBr(IsZeroSizedVLA, ContBB, SetupBB);
  1549. EmitBlock(SetupBB);
  1550. if (!EltSize.isOne())
  1551. SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
  1552. llvm::Value *BaseSizeInChars =
  1553. llvm::ConstantInt::get(IntPtrTy, EltSize.getQuantity());
  1554. Address Begin = Builder.CreateElementBitCast(Loc, Int8Ty, "vla.begin");
  1555. llvm::Value *End =
  1556. Builder.CreateInBoundsGEP(Begin.getPointer(), SizeVal, "vla.end");
  1557. llvm::BasicBlock *OriginBB = Builder.GetInsertBlock();
  1558. EmitBlock(LoopBB);
  1559. llvm::PHINode *Cur = Builder.CreatePHI(Begin.getType(), 2, "vla.cur");
  1560. Cur->addIncoming(Begin.getPointer(), OriginBB);
  1561. CharUnits CurAlign = Loc.getAlignment().alignmentOfArrayElement(EltSize);
  1562. Builder.CreateMemCpy(Address(Cur, CurAlign),
  1563. createUnnamedGlobalForMemcpyFrom(
  1564. CGM, D, Builder, Constant, ConstantAlign),
  1565. BaseSizeInChars, isVolatile);
  1566. llvm::Value *Next =
  1567. Builder.CreateInBoundsGEP(Int8Ty, Cur, BaseSizeInChars, "vla.next");
  1568. llvm::Value *Done = Builder.CreateICmpEQ(Next, End, "vla-init.isdone");
  1569. Builder.CreateCondBr(Done, ContBB, LoopBB);
  1570. Cur->addIncoming(Next, LoopBB);
  1571. EmitBlock(ContBB);
  1572. } break;
  1573. }
  1574. };
  1575. if (isTrivialInitializer(Init)) {
  1576. initializeWhatIsTechnicallyUninitialized(Loc);
  1577. return;
  1578. }
  1579. llvm::Constant *constant = nullptr;
  1580. if (emission.IsConstantAggregate ||
  1581. D.mightBeUsableInConstantExpressions(getContext())) {
  1582. assert(!capturedByInit && "constant init contains a capturing block?");
  1583. constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(D);
  1584. if (constant && !constant->isZeroValue() &&
  1585. (trivialAutoVarInit !=
  1586. LangOptions::TrivialAutoVarInitKind::Uninitialized)) {
  1587. IsPattern isPattern =
  1588. (trivialAutoVarInit == LangOptions::TrivialAutoVarInitKind::Pattern)
  1589. ? IsPattern::Yes
  1590. : IsPattern::No;
  1591. // C guarantees that brace-init with fewer initializers than members in
  1592. // the aggregate will initialize the rest of the aggregate as-if it were
  1593. // static initialization. In turn static initialization guarantees that
  1594. // padding is initialized to zero bits. We could instead pattern-init if D
  1595. // has any ImplicitValueInitExpr, but that seems to be unintuitive
  1596. // behavior.
  1597. constant = constWithPadding(CGM, IsPattern::No,
  1598. replaceUndef(CGM, isPattern, constant));
  1599. }
  1600. }
  1601. if (!constant) {
  1602. initializeWhatIsTechnicallyUninitialized(Loc);
  1603. LValue lv = MakeAddrLValue(Loc, type);
  1604. lv.setNonGC(true);
  1605. return EmitExprAsInit(Init, &D, lv, capturedByInit);
  1606. }
  1607. if (!emission.IsConstantAggregate) {
  1608. // For simple scalar/complex initialization, store the value directly.
  1609. LValue lv = MakeAddrLValue(Loc, type);
  1610. lv.setNonGC(true);
  1611. return EmitStoreThroughLValue(RValue::get(constant), lv, true);
  1612. }
  1613. llvm::Type *BP = CGM.Int8Ty->getPointerTo(Loc.getAddressSpace());
  1614. emitStoresForConstant(
  1615. CGM, D, (Loc.getType() == BP) ? Loc : Builder.CreateBitCast(Loc, BP),
  1616. type.isVolatileQualified(), Builder, constant);
  1617. }
  1618. /// Emit an expression as an initializer for an object (variable, field, etc.)
  1619. /// at the given location. The expression is not necessarily the normal
  1620. /// initializer for the object, and the address is not necessarily
  1621. /// its normal location.
  1622. ///
  1623. /// \param init the initializing expression
  1624. /// \param D the object to act as if we're initializing
  1625. /// \param loc the address to initialize; its type is a pointer
  1626. /// to the LLVM mapping of the object's type
  1627. /// \param alignment the alignment of the address
  1628. /// \param capturedByInit true if \p D is a __block variable
  1629. /// whose address is potentially changed by the initializer
  1630. void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
  1631. LValue lvalue, bool capturedByInit) {
  1632. QualType type = D->getType();
  1633. if (type->isReferenceType()) {
  1634. RValue rvalue = EmitReferenceBindingToExpr(init);
  1635. if (capturedByInit)
  1636. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  1637. EmitStoreThroughLValue(rvalue, lvalue, true);
  1638. return;
  1639. }
  1640. switch (getEvaluationKind(type)) {
  1641. case TEK_Scalar:
  1642. EmitScalarInit(init, D, lvalue, capturedByInit);
  1643. return;
  1644. case TEK_Complex: {
  1645. ComplexPairTy complex = EmitComplexExpr(init);
  1646. if (capturedByInit)
  1647. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  1648. EmitStoreOfComplex(complex, lvalue, /*init*/ true);
  1649. return;
  1650. }
  1651. case TEK_Aggregate:
  1652. if (type->isAtomicType()) {
  1653. EmitAtomicInit(const_cast<Expr*>(init), lvalue);
  1654. } else {
  1655. AggValueSlot::Overlap_t Overlap = AggValueSlot::MayOverlap;
  1656. if (isa<VarDecl>(D))
  1657. Overlap = AggValueSlot::DoesNotOverlap;
  1658. else if (auto *FD = dyn_cast<FieldDecl>(D))
  1659. Overlap = getOverlapForFieldInit(FD);
  1660. // TODO: how can we delay here if D is captured by its initializer?
  1661. EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
  1662. AggValueSlot::IsDestructed,
  1663. AggValueSlot::DoesNotNeedGCBarriers,
  1664. AggValueSlot::IsNotAliased,
  1665. Overlap));
  1666. }
  1667. return;
  1668. }
  1669. llvm_unreachable("bad evaluation kind");
  1670. }
  1671. /// Enter a destroy cleanup for the given local variable.
  1672. void CodeGenFunction::emitAutoVarTypeCleanup(
  1673. const CodeGenFunction::AutoVarEmission &emission,
  1674. QualType::DestructionKind dtorKind) {
  1675. assert(dtorKind != QualType::DK_none);
  1676. // Note that for __block variables, we want to destroy the
  1677. // original stack object, not the possibly forwarded object.
  1678. Address addr = emission.getObjectAddress(*this);
  1679. const VarDecl *var = emission.Variable;
  1680. QualType type = var->getType();
  1681. CleanupKind cleanupKind = NormalAndEHCleanup;
  1682. CodeGenFunction::Destroyer *destroyer = nullptr;
  1683. switch (dtorKind) {
  1684. case QualType::DK_none:
  1685. llvm_unreachable("no cleanup for trivially-destructible variable");
  1686. case QualType::DK_cxx_destructor:
  1687. // If there's an NRVO flag on the emission, we need a different
  1688. // cleanup.
  1689. if (emission.NRVOFlag) {
  1690. assert(!type->isArrayType());
  1691. CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
  1692. EHStack.pushCleanup<DestroyNRVOVariableCXX>(cleanupKind, addr, dtor,
  1693. emission.NRVOFlag);
  1694. return;
  1695. }
  1696. break;
  1697. case QualType::DK_objc_strong_lifetime:
  1698. // Suppress cleanups for pseudo-strong variables.
  1699. if (var->isARCPseudoStrong()) return;
  1700. // Otherwise, consider whether to use an EH cleanup or not.
  1701. cleanupKind = getARCCleanupKind();
  1702. // Use the imprecise destroyer by default.
  1703. if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
  1704. destroyer = CodeGenFunction::destroyARCStrongImprecise;
  1705. break;
  1706. case QualType::DK_objc_weak_lifetime:
  1707. break;
  1708. case QualType::DK_nontrivial_c_struct:
  1709. destroyer = CodeGenFunction::destroyNonTrivialCStruct;
  1710. if (emission.NRVOFlag) {
  1711. assert(!type->isArrayType());
  1712. EHStack.pushCleanup<DestroyNRVOVariableC>(cleanupKind, addr,
  1713. emission.NRVOFlag, type);
  1714. return;
  1715. }
  1716. break;
  1717. }
  1718. // If we haven't chosen a more specific destroyer, use the default.
  1719. if (!destroyer) destroyer = getDestroyer(dtorKind);
  1720. // Use an EH cleanup in array destructors iff the destructor itself
  1721. // is being pushed as an EH cleanup.
  1722. bool useEHCleanup = (cleanupKind & EHCleanup);
  1723. EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
  1724. useEHCleanup);
  1725. }
  1726. void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
  1727. assert(emission.Variable && "emission was not valid!");
  1728. // If this was emitted as a global constant, we're done.
  1729. if (emission.wasEmittedAsGlobal()) return;
  1730. // If we don't have an insertion point, we're done. Sema prevents
  1731. // us from jumping into any of these scopes anyway.
  1732. if (!HaveInsertPoint()) return;
  1733. const VarDecl &D = *emission.Variable;
  1734. // Check the type for a cleanup.
  1735. if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
  1736. emitAutoVarTypeCleanup(emission, dtorKind);
  1737. // In GC mode, honor objc_precise_lifetime.
  1738. if (getLangOpts().getGC() != LangOptions::NonGC &&
  1739. D.hasAttr<ObjCPreciseLifetimeAttr>()) {
  1740. EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
  1741. }
  1742. // Handle the cleanup attribute.
  1743. if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
  1744. const FunctionDecl *FD = CA->getFunctionDecl();
  1745. llvm::Constant *F = CGM.GetAddrOfFunction(FD);
  1746. assert(F && "Could not find function!");
  1747. const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
  1748. EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
  1749. }
  1750. // If this is a block variable, call _Block_object_destroy
  1751. // (on the unforwarded address). Don't enter this cleanup if we're in pure-GC
  1752. // mode.
  1753. if (emission.IsEscapingByRef &&
  1754. CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
  1755. BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
  1756. if (emission.Variable->getType().isObjCGCWeak())
  1757. Flags |= BLOCK_FIELD_IS_WEAK;
  1758. enterByrefCleanup(NormalAndEHCleanup, emission.Addr, Flags,
  1759. /*LoadBlockVarAddr*/ false,
  1760. cxxDestructorCanThrow(emission.Variable->getType()));
  1761. }
  1762. }
  1763. CodeGenFunction::Destroyer *
  1764. CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
  1765. switch (kind) {
  1766. case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
  1767. case QualType::DK_cxx_destructor:
  1768. return destroyCXXObject;
  1769. case QualType::DK_objc_strong_lifetime:
  1770. return destroyARCStrongPrecise;
  1771. case QualType::DK_objc_weak_lifetime:
  1772. return destroyARCWeak;
  1773. case QualType::DK_nontrivial_c_struct:
  1774. return destroyNonTrivialCStruct;
  1775. }
  1776. llvm_unreachable("Unknown DestructionKind");
  1777. }
  1778. /// pushEHDestroy - Push the standard destructor for the given type as
  1779. /// an EH-only cleanup.
  1780. void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
  1781. Address addr, QualType type) {
  1782. assert(dtorKind && "cannot push destructor for trivial type");
  1783. assert(needsEHCleanup(dtorKind));
  1784. pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
  1785. }
  1786. /// pushDestroy - Push the standard destructor for the given type as
  1787. /// at least a normal cleanup.
  1788. void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
  1789. Address addr, QualType type) {
  1790. assert(dtorKind && "cannot push destructor for trivial type");
  1791. CleanupKind cleanupKind = getCleanupKind(dtorKind);
  1792. pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
  1793. cleanupKind & EHCleanup);
  1794. }
  1795. void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
  1796. QualType type, Destroyer *destroyer,
  1797. bool useEHCleanupForArray) {
  1798. pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
  1799. destroyer, useEHCleanupForArray);
  1800. }
  1801. void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
  1802. EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
  1803. }
  1804. void CodeGenFunction::pushLifetimeExtendedDestroy(
  1805. CleanupKind cleanupKind, Address addr, QualType type,
  1806. Destroyer *destroyer, bool useEHCleanupForArray) {
  1807. // Push an EH-only cleanup for the object now.
  1808. // FIXME: When popping normal cleanups, we need to keep this EH cleanup
  1809. // around in case a temporary's destructor throws an exception.
  1810. if (cleanupKind & EHCleanup)
  1811. EHStack.pushCleanup<DestroyObject>(
  1812. static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
  1813. destroyer, useEHCleanupForArray);
  1814. // Remember that we need to push a full cleanup for the object at the
  1815. // end of the full-expression.
  1816. pushCleanupAfterFullExpr<DestroyObject>(
  1817. cleanupKind, addr, type, destroyer, useEHCleanupForArray);
  1818. }
  1819. /// emitDestroy - Immediately perform the destruction of the given
  1820. /// object.
  1821. ///
  1822. /// \param addr - the address of the object; a type*
  1823. /// \param type - the type of the object; if an array type, all
  1824. /// objects are destroyed in reverse order
  1825. /// \param destroyer - the function to call to destroy individual
  1826. /// elements
  1827. /// \param useEHCleanupForArray - whether an EH cleanup should be
  1828. /// used when destroying array elements, in case one of the
  1829. /// destructions throws an exception
  1830. void CodeGenFunction::emitDestroy(Address addr, QualType type,
  1831. Destroyer *destroyer,
  1832. bool useEHCleanupForArray) {
  1833. const ArrayType *arrayType = getContext().getAsArrayType(type);
  1834. if (!arrayType)
  1835. return destroyer(*this, addr, type);
  1836. llvm::Value *length = emitArrayLength(arrayType, type, addr);
  1837. CharUnits elementAlign =
  1838. addr.getAlignment()
  1839. .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
  1840. // Normally we have to check whether the array is zero-length.
  1841. bool checkZeroLength = true;
  1842. // But if the array length is constant, we can suppress that.
  1843. if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
  1844. // ...and if it's constant zero, we can just skip the entire thing.
  1845. if (constLength->isZero()) return;
  1846. checkZeroLength = false;
  1847. }
  1848. llvm::Value *begin = addr.getPointer();
  1849. llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
  1850. emitArrayDestroy(begin, end, type, elementAlign, destroyer,
  1851. checkZeroLength, useEHCleanupForArray);
  1852. }
  1853. /// emitArrayDestroy - Destroys all the elements of the given array,
  1854. /// beginning from last to first. The array cannot be zero-length.
  1855. ///
  1856. /// \param begin - a type* denoting the first element of the array
  1857. /// \param end - a type* denoting one past the end of the array
  1858. /// \param elementType - the element type of the array
  1859. /// \param destroyer - the function to call to destroy elements
  1860. /// \param useEHCleanup - whether to push an EH cleanup to destroy
  1861. /// the remaining elements in case the destruction of a single
  1862. /// element throws
  1863. void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
  1864. llvm::Value *end,
  1865. QualType elementType,
  1866. CharUnits elementAlign,
  1867. Destroyer *destroyer,
  1868. bool checkZeroLength,
  1869. bool useEHCleanup) {
  1870. assert(!elementType->isArrayType());
  1871. // The basic structure here is a do-while loop, because we don't
  1872. // need to check for the zero-element case.
  1873. llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
  1874. llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
  1875. if (checkZeroLength) {
  1876. llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
  1877. "arraydestroy.isempty");
  1878. Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
  1879. }
  1880. // Enter the loop body, making that address the current address.
  1881. llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
  1882. EmitBlock(bodyBB);
  1883. llvm::PHINode *elementPast =
  1884. Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
  1885. elementPast->addIncoming(end, entryBB);
  1886. // Shift the address back by one element.
  1887. llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
  1888. llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
  1889. "arraydestroy.element");
  1890. if (useEHCleanup)
  1891. pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
  1892. destroyer);
  1893. // Perform the actual destruction there.
  1894. destroyer(*this, Address(element, elementAlign), elementType);
  1895. if (useEHCleanup)
  1896. PopCleanupBlock();
  1897. // Check whether we've reached the end.
  1898. llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
  1899. Builder.CreateCondBr(done, doneBB, bodyBB);
  1900. elementPast->addIncoming(element, Builder.GetInsertBlock());
  1901. // Done.
  1902. EmitBlock(doneBB);
  1903. }
  1904. /// Perform partial array destruction as if in an EH cleanup. Unlike
  1905. /// emitArrayDestroy, the element type here may still be an array type.
  1906. static void emitPartialArrayDestroy(CodeGenFunction &CGF,
  1907. llvm::Value *begin, llvm::Value *end,
  1908. QualType type, CharUnits elementAlign,
  1909. CodeGenFunction::Destroyer *destroyer) {
  1910. // If the element type is itself an array, drill down.
  1911. unsigned arrayDepth = 0;
  1912. while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
  1913. // VLAs don't require a GEP index to walk into.
  1914. if (!isa<VariableArrayType>(arrayType))
  1915. arrayDepth++;
  1916. type = arrayType->getElementType();
  1917. }
  1918. if (arrayDepth) {
  1919. llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
  1920. SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
  1921. begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
  1922. end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
  1923. }
  1924. // Destroy the array. We don't ever need an EH cleanup because we
  1925. // assume that we're in an EH cleanup ourselves, so a throwing
  1926. // destructor causes an immediate terminate.
  1927. CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
  1928. /*checkZeroLength*/ true, /*useEHCleanup*/ false);
  1929. }
  1930. namespace {
  1931. /// RegularPartialArrayDestroy - a cleanup which performs a partial
  1932. /// array destroy where the end pointer is regularly determined and
  1933. /// does not need to be loaded from a local.
  1934. class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
  1935. llvm::Value *ArrayBegin;
  1936. llvm::Value *ArrayEnd;
  1937. QualType ElementType;
  1938. CodeGenFunction::Destroyer *Destroyer;
  1939. CharUnits ElementAlign;
  1940. public:
  1941. RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
  1942. QualType elementType, CharUnits elementAlign,
  1943. CodeGenFunction::Destroyer *destroyer)
  1944. : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
  1945. ElementType(elementType), Destroyer(destroyer),
  1946. ElementAlign(elementAlign) {}
  1947. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1948. emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
  1949. ElementType, ElementAlign, Destroyer);
  1950. }
  1951. };
  1952. /// IrregularPartialArrayDestroy - a cleanup which performs a
  1953. /// partial array destroy where the end pointer is irregularly
  1954. /// determined and must be loaded from a local.
  1955. class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
  1956. llvm::Value *ArrayBegin;
  1957. Address ArrayEndPointer;
  1958. QualType ElementType;
  1959. CodeGenFunction::Destroyer *Destroyer;
  1960. CharUnits ElementAlign;
  1961. public:
  1962. IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
  1963. Address arrayEndPointer,
  1964. QualType elementType,
  1965. CharUnits elementAlign,
  1966. CodeGenFunction::Destroyer *destroyer)
  1967. : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
  1968. ElementType(elementType), Destroyer(destroyer),
  1969. ElementAlign(elementAlign) {}
  1970. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1971. llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
  1972. emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
  1973. ElementType, ElementAlign, Destroyer);
  1974. }
  1975. };
  1976. } // end anonymous namespace
  1977. /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
  1978. /// already-constructed elements of the given array. The cleanup
  1979. /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
  1980. ///
  1981. /// \param elementType - the immediate element type of the array;
  1982. /// possibly still an array type
  1983. void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
  1984. Address arrayEndPointer,
  1985. QualType elementType,
  1986. CharUnits elementAlign,
  1987. Destroyer *destroyer) {
  1988. pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
  1989. arrayBegin, arrayEndPointer,
  1990. elementType, elementAlign,
  1991. destroyer);
  1992. }
  1993. /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
  1994. /// already-constructed elements of the given array. The cleanup
  1995. /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
  1996. ///
  1997. /// \param elementType - the immediate element type of the array;
  1998. /// possibly still an array type
  1999. void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
  2000. llvm::Value *arrayEnd,
  2001. QualType elementType,
  2002. CharUnits elementAlign,
  2003. Destroyer *destroyer) {
  2004. pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
  2005. arrayBegin, arrayEnd,
  2006. elementType, elementAlign,
  2007. destroyer);
  2008. }
  2009. /// Lazily declare the @llvm.lifetime.start intrinsic.
  2010. llvm::Function *CodeGenModule::getLLVMLifetimeStartFn() {
  2011. if (LifetimeStartFn)
  2012. return LifetimeStartFn;
  2013. LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
  2014. llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);
  2015. return LifetimeStartFn;
  2016. }
  2017. /// Lazily declare the @llvm.lifetime.end intrinsic.
  2018. llvm::Function *CodeGenModule::getLLVMLifetimeEndFn() {
  2019. if (LifetimeEndFn)
  2020. return LifetimeEndFn;
  2021. LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
  2022. llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);
  2023. return LifetimeEndFn;
  2024. }
  2025. namespace {
  2026. /// A cleanup to perform a release of an object at the end of a
  2027. /// function. This is used to balance out the incoming +1 of a
  2028. /// ns_consumed argument when we can't reasonably do that just by
  2029. /// not doing the initial retain for a __block argument.
  2030. struct ConsumeARCParameter final : EHScopeStack::Cleanup {
  2031. ConsumeARCParameter(llvm::Value *param,
  2032. ARCPreciseLifetime_t precise)
  2033. : Param(param), Precise(precise) {}
  2034. llvm::Value *Param;
  2035. ARCPreciseLifetime_t Precise;
  2036. void Emit(CodeGenFunction &CGF, Flags flags) override {
  2037. CGF.EmitARCRelease(Param, Precise);
  2038. }
  2039. };
  2040. } // end anonymous namespace
  2041. /// Emit an alloca (or GlobalValue depending on target)
  2042. /// for the specified parameter and set up LocalDeclMap.
  2043. void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
  2044. unsigned ArgNo) {
  2045. // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
  2046. assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
  2047. "Invalid argument to EmitParmDecl");
  2048. Arg.getAnyValue()->setName(D.getName());
  2049. QualType Ty = D.getType();
  2050. // Use better IR generation for certain implicit parameters.
  2051. if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
  2052. // The only implicit argument a block has is its literal.
  2053. // This may be passed as an inalloca'ed value on Windows x86.
  2054. if (BlockInfo) {
  2055. llvm::Value *V = Arg.isIndirect()
  2056. ? Builder.CreateLoad(Arg.getIndirectAddress())
  2057. : Arg.getDirectValue();
  2058. setBlockContextParameter(IPD, ArgNo, V);
  2059. return;
  2060. }
  2061. }
  2062. Address DeclPtr = Address::invalid();
  2063. bool DoStore = false;
  2064. bool IsScalar = hasScalarEvaluationKind(Ty);
  2065. // If we already have a pointer to the argument, reuse the input pointer.
  2066. if (Arg.isIndirect()) {
  2067. DeclPtr = Arg.getIndirectAddress();
  2068. // If we have a prettier pointer type at this point, bitcast to that.
  2069. unsigned AS = DeclPtr.getType()->getAddressSpace();
  2070. llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
  2071. if (DeclPtr.getType() != IRTy)
  2072. DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
  2073. // Indirect argument is in alloca address space, which may be different
  2074. // from the default address space.
  2075. auto AllocaAS = CGM.getASTAllocaAddressSpace();
  2076. auto *V = DeclPtr.getPointer();
  2077. auto SrcLangAS = getLangOpts().OpenCL ? LangAS::opencl_private : AllocaAS;
  2078. auto DestLangAS =
  2079. getLangOpts().OpenCL ? LangAS::opencl_private : LangAS::Default;
  2080. if (SrcLangAS != DestLangAS) {
  2081. assert(getContext().getTargetAddressSpace(SrcLangAS) ==
  2082. CGM.getDataLayout().getAllocaAddrSpace());
  2083. auto DestAS = getContext().getTargetAddressSpace(DestLangAS);
  2084. auto *T = V->getType()->getPointerElementType()->getPointerTo(DestAS);
  2085. DeclPtr = Address(getTargetHooks().performAddrSpaceCast(
  2086. *this, V, SrcLangAS, DestLangAS, T, true),
  2087. DeclPtr.getAlignment());
  2088. }
  2089. // Push a destructor cleanup for this parameter if the ABI requires it.
  2090. // Don't push a cleanup in a thunk for a method that will also emit a
  2091. // cleanup.
  2092. if (hasAggregateEvaluationKind(Ty) && !CurFuncIsThunk &&
  2093. Ty->getAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
  2094. if (QualType::DestructionKind DtorKind = Ty.isDestructedType()) {
  2095. assert((DtorKind == QualType::DK_cxx_destructor ||
  2096. DtorKind == QualType::DK_nontrivial_c_struct) &&
  2097. "unexpected destructor type");
  2098. pushDestroy(DtorKind, DeclPtr, Ty);
  2099. CalleeDestructedParamCleanups[cast<ParmVarDecl>(&D)] =
  2100. EHStack.stable_begin();
  2101. }
  2102. }
  2103. } else {
  2104. // Check if the parameter address is controlled by OpenMP runtime.
  2105. Address OpenMPLocalAddr =
  2106. getLangOpts().OpenMP
  2107. ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
  2108. : Address::invalid();
  2109. if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
  2110. DeclPtr = OpenMPLocalAddr;
  2111. } else {
  2112. // Otherwise, create a temporary to hold the value.
  2113. DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
  2114. D.getName() + ".addr");
  2115. }
  2116. DoStore = true;
  2117. }
  2118. llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
  2119. LValue lv = MakeAddrLValue(DeclPtr, Ty);
  2120. if (IsScalar) {
  2121. Qualifiers qs = Ty.getQualifiers();
  2122. if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
  2123. // We honor __attribute__((ns_consumed)) for types with lifetime.
  2124. // For __strong, it's handled by just skipping the initial retain;
  2125. // otherwise we have to balance out the initial +1 with an extra
  2126. // cleanup to do the release at the end of the function.
  2127. bool isConsumed = D.hasAttr<NSConsumedAttr>();
  2128. // If a parameter is pseudo-strong then we can omit the implicit retain.
  2129. if (D.isARCPseudoStrong()) {
  2130. assert(lt == Qualifiers::OCL_Strong &&
  2131. "pseudo-strong variable isn't strong?");
  2132. assert(qs.hasConst() && "pseudo-strong variable should be const!");
  2133. lt = Qualifiers::OCL_ExplicitNone;
  2134. }
  2135. // Load objects passed indirectly.
  2136. if (Arg.isIndirect() && !ArgVal)
  2137. ArgVal = Builder.CreateLoad(DeclPtr);
  2138. if (lt == Qualifiers::OCL_Strong) {
  2139. if (!isConsumed) {
  2140. if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
  2141. // use objc_storeStrong(&dest, value) for retaining the
  2142. // object. But first, store a null into 'dest' because
  2143. // objc_storeStrong attempts to release its old value.
  2144. llvm::Value *Null = CGM.EmitNullConstant(D.getType());
  2145. EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
  2146. EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
  2147. DoStore = false;
  2148. }
  2149. else
  2150. // Don't use objc_retainBlock for block pointers, because we
  2151. // don't want to Block_copy something just because we got it
  2152. // as a parameter.
  2153. ArgVal = EmitARCRetainNonBlock(ArgVal);
  2154. }
  2155. } else {
  2156. // Push the cleanup for a consumed parameter.
  2157. if (isConsumed) {
  2158. ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
  2159. ? ARCPreciseLifetime : ARCImpreciseLifetime);
  2160. EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
  2161. precise);
  2162. }
  2163. if (lt == Qualifiers::OCL_Weak) {
  2164. EmitARCInitWeak(DeclPtr, ArgVal);
  2165. DoStore = false; // The weak init is a store, no need to do two.
  2166. }
  2167. }
  2168. // Enter the cleanup scope.
  2169. EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
  2170. }
  2171. }
  2172. // Store the initial value into the alloca.
  2173. if (DoStore)
  2174. EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
  2175. setAddrOfLocalVar(&D, DeclPtr);
  2176. // Emit debug info for param declaration.
  2177. if (CGDebugInfo *DI = getDebugInfo()) {
  2178. if (CGM.getCodeGenOpts().getDebugInfo() >=
  2179. codegenoptions::LimitedDebugInfo) {
  2180. DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
  2181. }
  2182. }
  2183. if (D.hasAttr<AnnotateAttr>())
  2184. EmitVarAnnotations(&D, DeclPtr.getPointer());
  2185. // We can only check return value nullability if all arguments to the
  2186. // function satisfy their nullability preconditions. This makes it necessary
  2187. // to emit null checks for args in the function body itself.
  2188. if (requiresReturnValueNullabilityCheck()) {
  2189. auto Nullability = Ty->getNullability(getContext());
  2190. if (Nullability && *Nullability == NullabilityKind::NonNull) {
  2191. SanitizerScope SanScope(this);
  2192. RetValNullabilityPrecondition =
  2193. Builder.CreateAnd(RetValNullabilityPrecondition,
  2194. Builder.CreateIsNotNull(Arg.getAnyValue()));
  2195. }
  2196. }
  2197. }
  2198. void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
  2199. CodeGenFunction *CGF) {
  2200. if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
  2201. return;
  2202. getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
  2203. }
  2204. void CodeGenModule::EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D,
  2205. CodeGenFunction *CGF) {
  2206. if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
  2207. return;
  2208. // FIXME: need to implement mapper code generation
  2209. }
  2210. void CodeGenModule::EmitOMPRequiresDecl(const OMPRequiresDecl *D) {
  2211. getOpenMPRuntime().checkArchForUnifiedAddressing(D);
  2212. }