CGDecl.cpp 97 KB

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