CGDecl.cpp 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745
  1. //===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This contains code to emit Decl nodes as LLVM code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CodeGenFunction.h"
  14. #include "CGDebugInfo.h"
  15. #include "CGOpenCLRuntime.h"
  16. #include "CodeGenModule.h"
  17. #include "clang/AST/ASTContext.h"
  18. #include "clang/AST/CharUnits.h"
  19. #include "clang/AST/Decl.h"
  20. #include "clang/AST/DeclObjC.h"
  21. #include "clang/Basic/SourceManager.h"
  22. #include "clang/Basic/TargetInfo.h"
  23. #include "clang/CodeGen/CGFunctionInfo.h"
  24. #include "clang/Frontend/CodeGenOptions.h"
  25. #include "llvm/IR/DataLayout.h"
  26. #include "llvm/IR/GlobalVariable.h"
  27. #include "llvm/IR/Intrinsics.h"
  28. #include "llvm/IR/Type.h"
  29. using namespace clang;
  30. using namespace CodeGen;
  31. void CodeGenFunction::EmitDecl(const Decl &D) {
  32. switch (D.getKind()) {
  33. case Decl::TranslationUnit:
  34. case Decl::Namespace:
  35. case Decl::UnresolvedUsingTypename:
  36. case Decl::ClassTemplateSpecialization:
  37. case Decl::ClassTemplatePartialSpecialization:
  38. case Decl::VarTemplateSpecialization:
  39. case Decl::VarTemplatePartialSpecialization:
  40. case Decl::TemplateTypeParm:
  41. case Decl::UnresolvedUsingValue:
  42. case Decl::NonTypeTemplateParm:
  43. case Decl::CXXMethod:
  44. case Decl::CXXConstructor:
  45. case Decl::CXXDestructor:
  46. case Decl::CXXConversion:
  47. case Decl::Field:
  48. case Decl::MSProperty:
  49. case Decl::IndirectField:
  50. case Decl::ObjCIvar:
  51. case Decl::ObjCAtDefsField:
  52. case Decl::ParmVar:
  53. case Decl::ImplicitParam:
  54. case Decl::ClassTemplate:
  55. case Decl::VarTemplate:
  56. case Decl::FunctionTemplate:
  57. case Decl::TypeAliasTemplate:
  58. case Decl::TemplateTemplateParm:
  59. case Decl::ObjCMethod:
  60. case Decl::ObjCCategory:
  61. case Decl::ObjCProtocol:
  62. case Decl::ObjCInterface:
  63. case Decl::ObjCCategoryImpl:
  64. case Decl::ObjCImplementation:
  65. case Decl::ObjCProperty:
  66. case Decl::ObjCCompatibleAlias:
  67. case Decl::AccessSpec:
  68. case Decl::LinkageSpec:
  69. case Decl::ObjCPropertyImpl:
  70. case Decl::FileScopeAsm:
  71. case Decl::Friend:
  72. case Decl::FriendTemplate:
  73. case Decl::Block:
  74. case Decl::Captured:
  75. case Decl::ClassScopeFunctionSpecialization:
  76. case Decl::UsingShadow:
  77. llvm_unreachable("Declaration should not be in declstmts!");
  78. case Decl::Function: // void X();
  79. case Decl::Record: // struct/union/class X;
  80. case Decl::Enum: // enum X;
  81. case Decl::EnumConstant: // enum ? { X = ? }
  82. case Decl::CXXRecord: // struct/union/class X; [C++]
  83. case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
  84. case Decl::Label: // __label__ x;
  85. case Decl::Import:
  86. case Decl::OMPThreadPrivate:
  87. case Decl::Empty:
  88. // None of these decls require codegen support.
  89. return;
  90. case Decl::NamespaceAlias:
  91. if (CGDebugInfo *DI = getDebugInfo())
  92. DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
  93. return;
  94. case Decl::Using: // using X; [C++]
  95. if (CGDebugInfo *DI = getDebugInfo())
  96. DI->EmitUsingDecl(cast<UsingDecl>(D));
  97. return;
  98. case Decl::UsingDirective: // using namespace X; [C++]
  99. if (CGDebugInfo *DI = getDebugInfo())
  100. DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
  101. return;
  102. case Decl::Var: {
  103. const VarDecl &VD = cast<VarDecl>(D);
  104. assert(VD.isLocalVarDecl() &&
  105. "Should not see file-scope variables inside a function!");
  106. return EmitVarDecl(VD);
  107. }
  108. case Decl::Typedef: // typedef int X;
  109. case Decl::TypeAlias: { // using X = int; [C++0x]
  110. const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
  111. QualType Ty = TD.getUnderlyingType();
  112. if (Ty->isVariablyModifiedType())
  113. EmitVariablyModifiedType(Ty);
  114. }
  115. }
  116. }
  117. /// EmitVarDecl - This method handles emission of any variable declaration
  118. /// inside a function, including static vars etc.
  119. void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
  120. if (D.isStaticLocal()) {
  121. llvm::GlobalValue::LinkageTypes Linkage =
  122. CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
  123. // FIXME: We need to force the emission/use of a guard variable for
  124. // some variables even if we can constant-evaluate them because
  125. // we can't guarantee every translation unit will constant-evaluate them.
  126. return EmitStaticVarDecl(D, Linkage);
  127. }
  128. if (D.hasExternalStorage())
  129. // Don't emit it now, allow it to be emitted lazily on its first use.
  130. return;
  131. if (D.getStorageClass() == SC_OpenCLWorkGroupLocal)
  132. return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
  133. assert(D.hasLocalStorage());
  134. return EmitAutoVarDecl(D);
  135. }
  136. static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D,
  137. const char *Separator) {
  138. CodeGenModule &CGM = CGF.CGM;
  139. if (CGF.getLangOpts().CPlusPlus)
  140. return CGM.getMangledName(&D).str();
  141. StringRef ContextName;
  142. if (!CGF.CurFuncDecl) {
  143. // Better be in a block declared in global scope.
  144. const NamedDecl *ND = cast<NamedDecl>(&D);
  145. const DeclContext *DC = ND->getDeclContext();
  146. if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
  147. ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
  148. else
  149. llvm_unreachable("Unknown context for block static var decl");
  150. } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl))
  151. ContextName = CGM.getMangledName(FD);
  152. else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
  153. ContextName = CGF.CurFn->getName();
  154. else
  155. llvm_unreachable("Unknown context for static var decl");
  156. return ContextName.str() + Separator + D.getNameAsString();
  157. }
  158. llvm::Constant *
  159. CodeGenFunction::CreateStaticVarDecl(const VarDecl &D,
  160. const char *Separator,
  161. llvm::GlobalValue::LinkageTypes Linkage) {
  162. QualType Ty = D.getType();
  163. assert(Ty->isConstantSizeType() && "VLAs can't be static");
  164. // Use the label if the variable is renamed with the asm-label extension.
  165. std::string Name;
  166. if (D.hasAttr<AsmLabelAttr>())
  167. Name = CGM.getMangledName(&D);
  168. else
  169. Name = GetStaticDeclName(*this, D, Separator);
  170. llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
  171. unsigned AddrSpace =
  172. CGM.GetGlobalVarAddressSpace(&D, CGM.getContext().getTargetAddressSpace(Ty));
  173. llvm::GlobalVariable *GV =
  174. new llvm::GlobalVariable(CGM.getModule(), LTy,
  175. Ty.isConstant(getContext()), Linkage,
  176. CGM.EmitNullConstant(D.getType()), Name, nullptr,
  177. llvm::GlobalVariable::NotThreadLocal,
  178. AddrSpace);
  179. GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
  180. CGM.setGlobalVisibility(GV, &D);
  181. if (D.getTLSKind())
  182. CGM.setTLSMode(GV, D);
  183. // Make sure the result is of the correct type.
  184. unsigned ExpectedAddrSpace = CGM.getContext().getTargetAddressSpace(Ty);
  185. if (AddrSpace != ExpectedAddrSpace) {
  186. llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace);
  187. return llvm::ConstantExpr::getAddrSpaceCast(GV, PTy);
  188. }
  189. return GV;
  190. }
  191. /// hasNontrivialDestruction - Determine whether a type's destruction is
  192. /// non-trivial. If so, and the variable uses static initialization, we must
  193. /// register its destructor to run on exit.
  194. static bool hasNontrivialDestruction(QualType T) {
  195. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  196. return RD && !RD->hasTrivialDestructor();
  197. }
  198. /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
  199. /// global variable that has already been created for it. If the initializer
  200. /// has a different type than GV does, this may free GV and return a different
  201. /// one. Otherwise it just returns GV.
  202. llvm::GlobalVariable *
  203. CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
  204. llvm::GlobalVariable *GV) {
  205. llvm::Constant *Init = CGM.EmitConstantInit(D, this);
  206. // If constant emission failed, then this should be a C++ static
  207. // initializer.
  208. if (!Init) {
  209. if (!getLangOpts().CPlusPlus)
  210. CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
  211. else if (Builder.GetInsertBlock()) {
  212. // Since we have a static initializer, this global variable can't
  213. // be constant.
  214. GV->setConstant(false);
  215. EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
  216. }
  217. return GV;
  218. }
  219. // The initializer may differ in type from the global. Rewrite
  220. // the global to match the initializer. (We have to do this
  221. // because some types, like unions, can't be completely represented
  222. // in the LLVM type system.)
  223. if (GV->getType()->getElementType() != Init->getType()) {
  224. llvm::GlobalVariable *OldGV = GV;
  225. GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
  226. OldGV->isConstant(),
  227. OldGV->getLinkage(), Init, "",
  228. /*InsertBefore*/ OldGV,
  229. OldGV->getThreadLocalMode(),
  230. CGM.getContext().getTargetAddressSpace(D.getType()));
  231. GV->setVisibility(OldGV->getVisibility());
  232. // Steal the name of the old global
  233. GV->takeName(OldGV);
  234. // Replace all uses of the old global with the new global
  235. llvm::Constant *NewPtrForOldDecl =
  236. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  237. OldGV->replaceAllUsesWith(NewPtrForOldDecl);
  238. // Erase the old global, since it is no longer used.
  239. OldGV->eraseFromParent();
  240. }
  241. GV->setConstant(CGM.isTypeConstant(D.getType(), true));
  242. GV->setInitializer(Init);
  243. if (hasNontrivialDestruction(D.getType())) {
  244. // We have a constant initializer, but a nontrivial destructor. We still
  245. // need to perform a guarded "initialization" in order to register the
  246. // destructor.
  247. EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
  248. }
  249. return GV;
  250. }
  251. void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
  252. llvm::GlobalValue::LinkageTypes Linkage) {
  253. llvm::Value *&DMEntry = LocalDeclMap[&D];
  254. assert(!DMEntry && "Decl already exists in localdeclmap!");
  255. // Check to see if we already have a global variable for this
  256. // declaration. This can happen when double-emitting function
  257. // bodies, e.g. with complete and base constructors.
  258. llvm::Constant *addr =
  259. CGM.getStaticLocalDeclAddress(&D);
  260. if (!addr)
  261. addr = CreateStaticVarDecl(D, ".", Linkage);
  262. // Store into LocalDeclMap before generating initializer to handle
  263. // circular references.
  264. DMEntry = addr;
  265. CGM.setStaticLocalDeclAddress(&D, addr);
  266. // We can't have a VLA here, but we can have a pointer to a VLA,
  267. // even though that doesn't really make any sense.
  268. // Make sure to evaluate VLA bounds now so that we have them for later.
  269. if (D.getType()->isVariablyModifiedType())
  270. EmitVariablyModifiedType(D.getType());
  271. // Save the type in case adding the initializer forces a type change.
  272. llvm::Type *expectedType = addr->getType();
  273. llvm::GlobalVariable *var =
  274. cast<llvm::GlobalVariable>(addr->stripPointerCasts());
  275. // If this value has an initializer, emit it.
  276. if (D.getInit())
  277. var = AddInitializerToStaticVarDecl(D, var);
  278. var->setAlignment(getContext().getDeclAlign(&D).getQuantity());
  279. if (D.hasAttr<AnnotateAttr>())
  280. CGM.AddGlobalAnnotations(&D, var);
  281. if (const SectionAttr *SA = D.getAttr<SectionAttr>())
  282. var->setSection(SA->getName());
  283. if (D.hasAttr<UsedAttr>())
  284. CGM.addUsedGlobal(var);
  285. // We may have to cast the constant because of the initializer
  286. // mismatch above.
  287. //
  288. // FIXME: It is really dangerous to store this in the map; if anyone
  289. // RAUW's the GV uses of this constant will be invalid.
  290. llvm::Constant *castedAddr =
  291. llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
  292. DMEntry = castedAddr;
  293. CGM.setStaticLocalDeclAddress(&D, castedAddr);
  294. // Emit global variable debug descriptor for static vars.
  295. CGDebugInfo *DI = getDebugInfo();
  296. if (DI &&
  297. CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
  298. DI->setLocation(D.getLocation());
  299. DI->EmitGlobalVariable(var, &D);
  300. }
  301. }
  302. namespace {
  303. struct DestroyObject : EHScopeStack::Cleanup {
  304. DestroyObject(llvm::Value *addr, QualType type,
  305. CodeGenFunction::Destroyer *destroyer,
  306. bool useEHCleanupForArray)
  307. : addr(addr), type(type), destroyer(destroyer),
  308. useEHCleanupForArray(useEHCleanupForArray) {}
  309. llvm::Value *addr;
  310. QualType type;
  311. CodeGenFunction::Destroyer *destroyer;
  312. bool useEHCleanupForArray;
  313. void Emit(CodeGenFunction &CGF, Flags flags) override {
  314. // Don't use an EH cleanup recursively from an EH cleanup.
  315. bool useEHCleanupForArray =
  316. flags.isForNormalCleanup() && this->useEHCleanupForArray;
  317. CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
  318. }
  319. };
  320. struct DestroyNRVOVariable : EHScopeStack::Cleanup {
  321. DestroyNRVOVariable(llvm::Value *addr,
  322. const CXXDestructorDecl *Dtor,
  323. llvm::Value *NRVOFlag)
  324. : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
  325. const CXXDestructorDecl *Dtor;
  326. llvm::Value *NRVOFlag;
  327. llvm::Value *Loc;
  328. void Emit(CodeGenFunction &CGF, Flags flags) override {
  329. // Along the exceptions path we always execute the dtor.
  330. bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
  331. llvm::BasicBlock *SkipDtorBB = nullptr;
  332. if (NRVO) {
  333. // If we exited via NRVO, we skip the destructor call.
  334. llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
  335. SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
  336. llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
  337. CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
  338. CGF.EmitBlock(RunDtorBB);
  339. }
  340. CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
  341. /*ForVirtualBase=*/false,
  342. /*Delegating=*/false,
  343. Loc);
  344. if (NRVO) CGF.EmitBlock(SkipDtorBB);
  345. }
  346. };
  347. struct CallStackRestore : EHScopeStack::Cleanup {
  348. llvm::Value *Stack;
  349. CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
  350. void Emit(CodeGenFunction &CGF, Flags flags) override {
  351. llvm::Value *V = CGF.Builder.CreateLoad(Stack);
  352. llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
  353. CGF.Builder.CreateCall(F, V);
  354. }
  355. };
  356. struct ExtendGCLifetime : EHScopeStack::Cleanup {
  357. const VarDecl &Var;
  358. ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
  359. void Emit(CodeGenFunction &CGF, Flags flags) override {
  360. // Compute the address of the local variable, in case it's a
  361. // byref or something.
  362. DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
  363. Var.getType(), VK_LValue, SourceLocation());
  364. llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
  365. SourceLocation());
  366. CGF.EmitExtendGCLifetime(value);
  367. }
  368. };
  369. struct CallCleanupFunction : EHScopeStack::Cleanup {
  370. llvm::Constant *CleanupFn;
  371. const CGFunctionInfo &FnInfo;
  372. const VarDecl &Var;
  373. CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
  374. const VarDecl *Var)
  375. : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
  376. void Emit(CodeGenFunction &CGF, Flags flags) override {
  377. DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
  378. Var.getType(), VK_LValue, SourceLocation());
  379. // Compute the address of the local variable, in case it's a byref
  380. // or something.
  381. llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
  382. // In some cases, the type of the function argument will be different from
  383. // the type of the pointer. An example of this is
  384. // void f(void* arg);
  385. // __attribute__((cleanup(f))) void *g;
  386. //
  387. // To fix this we insert a bitcast here.
  388. QualType ArgTy = FnInfo.arg_begin()->type;
  389. llvm::Value *Arg =
  390. CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
  391. CallArgList Args;
  392. Args.add(RValue::get(Arg),
  393. CGF.getContext().getPointerType(Var.getType()));
  394. CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
  395. }
  396. };
  397. /// A cleanup to call @llvm.lifetime.end.
  398. class CallLifetimeEnd : public EHScopeStack::Cleanup {
  399. llvm::Value *Addr;
  400. llvm::Value *Size;
  401. public:
  402. CallLifetimeEnd(llvm::Value *addr, llvm::Value *size)
  403. : Addr(addr), Size(size) {}
  404. void Emit(CodeGenFunction &CGF, Flags flags) override {
  405. llvm::Value *castAddr = CGF.Builder.CreateBitCast(Addr, CGF.Int8PtrTy);
  406. CGF.Builder.CreateCall2(CGF.CGM.getLLVMLifetimeEndFn(),
  407. Size, castAddr)
  408. ->setDoesNotThrow();
  409. }
  410. };
  411. }
  412. /// EmitAutoVarWithLifetime - Does the setup required for an automatic
  413. /// variable with lifetime.
  414. static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
  415. llvm::Value *addr,
  416. Qualifiers::ObjCLifetime lifetime) {
  417. switch (lifetime) {
  418. case Qualifiers::OCL_None:
  419. llvm_unreachable("present but none");
  420. case Qualifiers::OCL_ExplicitNone:
  421. // nothing to do
  422. break;
  423. case Qualifiers::OCL_Strong: {
  424. CodeGenFunction::Destroyer *destroyer =
  425. (var.hasAttr<ObjCPreciseLifetimeAttr>()
  426. ? CodeGenFunction::destroyARCStrongPrecise
  427. : CodeGenFunction::destroyARCStrongImprecise);
  428. CleanupKind cleanupKind = CGF.getARCCleanupKind();
  429. CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
  430. cleanupKind & EHCleanup);
  431. break;
  432. }
  433. case Qualifiers::OCL_Autoreleasing:
  434. // nothing to do
  435. break;
  436. case Qualifiers::OCL_Weak:
  437. // __weak objects always get EH cleanups; otherwise, exceptions
  438. // could cause really nasty crashes instead of mere leaks.
  439. CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
  440. CodeGenFunction::destroyARCWeak,
  441. /*useEHCleanup*/ true);
  442. break;
  443. }
  444. }
  445. static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
  446. if (const Expr *e = dyn_cast<Expr>(s)) {
  447. // Skip the most common kinds of expressions that make
  448. // hierarchy-walking expensive.
  449. s = e = e->IgnoreParenCasts();
  450. if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
  451. return (ref->getDecl() == &var);
  452. if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
  453. const BlockDecl *block = be->getBlockDecl();
  454. for (const auto &I : block->captures()) {
  455. if (I.getVariable() == &var)
  456. return true;
  457. }
  458. }
  459. }
  460. for (Stmt::const_child_range children = s->children(); children; ++children)
  461. // children might be null; as in missing decl or conditional of an if-stmt.
  462. if ((*children) && isAccessedBy(var, *children))
  463. return true;
  464. return false;
  465. }
  466. static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
  467. if (!decl) return false;
  468. if (!isa<VarDecl>(decl)) return false;
  469. const VarDecl *var = cast<VarDecl>(decl);
  470. return isAccessedBy(*var, e);
  471. }
  472. static void drillIntoBlockVariable(CodeGenFunction &CGF,
  473. LValue &lvalue,
  474. const VarDecl *var) {
  475. lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var));
  476. }
  477. void CodeGenFunction::EmitScalarInit(const Expr *init,
  478. const ValueDecl *D,
  479. LValue lvalue,
  480. bool capturedByInit) {
  481. Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
  482. if (!lifetime) {
  483. llvm::Value *value = EmitScalarExpr(init);
  484. if (capturedByInit)
  485. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  486. EmitStoreThroughLValue(RValue::get(value), lvalue, true);
  487. return;
  488. }
  489. if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
  490. init = DIE->getExpr();
  491. // If we're emitting a value with lifetime, we have to do the
  492. // initialization *before* we leave the cleanup scopes.
  493. if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
  494. enterFullExpression(ewc);
  495. init = ewc->getSubExpr();
  496. }
  497. CodeGenFunction::RunCleanupsScope Scope(*this);
  498. // We have to maintain the illusion that the variable is
  499. // zero-initialized. If the variable might be accessed in its
  500. // initializer, zero-initialize before running the initializer, then
  501. // actually perform the initialization with an assign.
  502. bool accessedByInit = false;
  503. if (lifetime != Qualifiers::OCL_ExplicitNone)
  504. accessedByInit = (capturedByInit || isAccessedBy(D, init));
  505. if (accessedByInit) {
  506. LValue tempLV = lvalue;
  507. // Drill down to the __block object if necessary.
  508. if (capturedByInit) {
  509. // We can use a simple GEP for this because it can't have been
  510. // moved yet.
  511. tempLV.setAddress(Builder.CreateStructGEP(tempLV.getAddress(),
  512. getByRefValueLLVMField(cast<VarDecl>(D))));
  513. }
  514. llvm::PointerType *ty
  515. = cast<llvm::PointerType>(tempLV.getAddress()->getType());
  516. ty = cast<llvm::PointerType>(ty->getElementType());
  517. llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
  518. // If __weak, we want to use a barrier under certain conditions.
  519. if (lifetime == Qualifiers::OCL_Weak)
  520. EmitARCInitWeak(tempLV.getAddress(), zero);
  521. // Otherwise just do a simple store.
  522. else
  523. EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
  524. }
  525. // Emit the initializer.
  526. llvm::Value *value = nullptr;
  527. switch (lifetime) {
  528. case Qualifiers::OCL_None:
  529. llvm_unreachable("present but none");
  530. case Qualifiers::OCL_ExplicitNone:
  531. // nothing to do
  532. value = EmitScalarExpr(init);
  533. break;
  534. case Qualifiers::OCL_Strong: {
  535. value = EmitARCRetainScalarExpr(init);
  536. break;
  537. }
  538. case Qualifiers::OCL_Weak: {
  539. // No way to optimize a producing initializer into this. It's not
  540. // worth optimizing for, because the value will immediately
  541. // disappear in the common case.
  542. value = EmitScalarExpr(init);
  543. if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  544. if (accessedByInit)
  545. EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
  546. else
  547. EmitARCInitWeak(lvalue.getAddress(), value);
  548. return;
  549. }
  550. case Qualifiers::OCL_Autoreleasing:
  551. value = EmitARCRetainAutoreleaseScalarExpr(init);
  552. break;
  553. }
  554. if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  555. // If the variable might have been accessed by its initializer, we
  556. // might have to initialize with a barrier. We have to do this for
  557. // both __weak and __strong, but __weak got filtered out above.
  558. if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
  559. llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
  560. EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
  561. EmitARCRelease(oldValue, ARCImpreciseLifetime);
  562. return;
  563. }
  564. EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
  565. }
  566. /// EmitScalarInit - Initialize the given lvalue with the given object.
  567. void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
  568. Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
  569. if (!lifetime)
  570. return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
  571. switch (lifetime) {
  572. case Qualifiers::OCL_None:
  573. llvm_unreachable("present but none");
  574. case Qualifiers::OCL_ExplicitNone:
  575. // nothing to do
  576. break;
  577. case Qualifiers::OCL_Strong:
  578. init = EmitARCRetain(lvalue.getType(), init);
  579. break;
  580. case Qualifiers::OCL_Weak:
  581. // Initialize and then skip the primitive store.
  582. EmitARCInitWeak(lvalue.getAddress(), init);
  583. return;
  584. case Qualifiers::OCL_Autoreleasing:
  585. init = EmitARCRetainAutorelease(lvalue.getType(), init);
  586. break;
  587. }
  588. EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
  589. }
  590. /// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
  591. /// non-zero parts of the specified initializer with equal or fewer than
  592. /// NumStores scalar stores.
  593. static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
  594. unsigned &NumStores) {
  595. // Zero and Undef never requires any extra stores.
  596. if (isa<llvm::ConstantAggregateZero>(Init) ||
  597. isa<llvm::ConstantPointerNull>(Init) ||
  598. isa<llvm::UndefValue>(Init))
  599. return true;
  600. if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
  601. isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
  602. isa<llvm::ConstantExpr>(Init))
  603. return Init->isNullValue() || NumStores--;
  604. // See if we can emit each element.
  605. if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
  606. for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
  607. llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
  608. if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
  609. return false;
  610. }
  611. return true;
  612. }
  613. if (llvm::ConstantDataSequential *CDS =
  614. dyn_cast<llvm::ConstantDataSequential>(Init)) {
  615. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  616. llvm::Constant *Elt = CDS->getElementAsConstant(i);
  617. if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
  618. return false;
  619. }
  620. return true;
  621. }
  622. // Anything else is hard and scary.
  623. return false;
  624. }
  625. /// emitStoresForInitAfterMemset - For inits that
  626. /// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
  627. /// stores that would be required.
  628. static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
  629. bool isVolatile, CGBuilderTy &Builder) {
  630. assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
  631. "called emitStoresForInitAfterMemset for zero or undef value.");
  632. if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
  633. isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
  634. isa<llvm::ConstantExpr>(Init)) {
  635. Builder.CreateStore(Init, Loc, isVolatile);
  636. return;
  637. }
  638. if (llvm::ConstantDataSequential *CDS =
  639. dyn_cast<llvm::ConstantDataSequential>(Init)) {
  640. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  641. llvm::Constant *Elt = CDS->getElementAsConstant(i);
  642. // If necessary, get a pointer to the element and emit it.
  643. if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
  644. emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
  645. isVolatile, Builder);
  646. }
  647. return;
  648. }
  649. assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
  650. "Unknown value type!");
  651. for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
  652. llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
  653. // If necessary, get a pointer to the element and emit it.
  654. if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
  655. emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
  656. isVolatile, Builder);
  657. }
  658. }
  659. /// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
  660. /// plus some stores to initialize a local variable instead of using a memcpy
  661. /// from a constant global. It is beneficial to use memset if the global is all
  662. /// zeros, or mostly zeros and large.
  663. static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
  664. uint64_t GlobalSize) {
  665. // If a global is all zeros, always use a memset.
  666. if (isa<llvm::ConstantAggregateZero>(Init)) return true;
  667. // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
  668. // do it if it will require 6 or fewer scalar stores.
  669. // TODO: Should budget depends on the size? Avoiding a large global warrants
  670. // plopping in more stores.
  671. unsigned StoreBudget = 6;
  672. uint64_t SizeLimit = 32;
  673. return GlobalSize > SizeLimit &&
  674. canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
  675. }
  676. /// Should we use the LLVM lifetime intrinsics for the given local variable?
  677. static bool shouldUseLifetimeMarkers(CodeGenFunction &CGF, const VarDecl &D,
  678. unsigned Size) {
  679. // Always emit lifetime markers in -fsanitize=use-after-scope mode.
  680. if (CGF.getLangOpts().Sanitize.UseAfterScope)
  681. return true;
  682. // For now, only in optimized builds.
  683. if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0)
  684. return false;
  685. // Limit the size of marked objects to 32 bytes. We don't want to increase
  686. // compile time by marking tiny objects.
  687. unsigned SizeThreshold = 32;
  688. return Size > SizeThreshold;
  689. }
  690. /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
  691. /// variable declaration with auto, register, or no storage class specifier.
  692. /// These turn into simple stack objects, or GlobalValues depending on target.
  693. void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
  694. AutoVarEmission emission = EmitAutoVarAlloca(D);
  695. EmitAutoVarInit(emission);
  696. EmitAutoVarCleanups(emission);
  697. }
  698. /// EmitAutoVarAlloca - Emit the alloca and debug information for a
  699. /// local variable. Does not emit initialization or destruction.
  700. CodeGenFunction::AutoVarEmission
  701. CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
  702. QualType Ty = D.getType();
  703. AutoVarEmission emission(D);
  704. bool isByRef = D.hasAttr<BlocksAttr>();
  705. emission.IsByRef = isByRef;
  706. CharUnits alignment = getContext().getDeclAlign(&D);
  707. emission.Alignment = alignment;
  708. // If the type is variably-modified, emit all the VLA sizes for it.
  709. if (Ty->isVariablyModifiedType())
  710. EmitVariablyModifiedType(Ty);
  711. llvm::Value *DeclPtr;
  712. if (Ty->isConstantSizeType()) {
  713. bool NRVO = getLangOpts().ElideConstructors &&
  714. D.isNRVOVariable();
  715. // If this value is an array or struct with a statically determinable
  716. // constant initializer, there are optimizations we can do.
  717. //
  718. // TODO: We should constant-evaluate the initializer of any variable,
  719. // as long as it is initialized by a constant expression. Currently,
  720. // isConstantInitializer produces wrong answers for structs with
  721. // reference or bitfield members, and a few other cases, and checking
  722. // for POD-ness protects us from some of these.
  723. if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
  724. (D.isConstexpr() ||
  725. ((Ty.isPODType(getContext()) ||
  726. getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
  727. D.getInit()->isConstantInitializer(getContext(), false)))) {
  728. // If the variable's a const type, and it's neither an NRVO
  729. // candidate nor a __block variable and has no mutable members,
  730. // emit it as a global instead.
  731. if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
  732. CGM.isTypeConstant(Ty, true)) {
  733. EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
  734. emission.Address = nullptr; // signal this condition to later callbacks
  735. assert(emission.wasEmittedAsGlobal());
  736. return emission;
  737. }
  738. // Otherwise, tell the initialization code that we're in this case.
  739. emission.IsConstantAggregate = true;
  740. }
  741. // A normal fixed sized variable becomes an alloca in the entry block,
  742. // unless it's an NRVO variable.
  743. llvm::Type *LTy = ConvertTypeForMem(Ty);
  744. if (NRVO) {
  745. // The named return value optimization: allocate this variable in the
  746. // return slot, so that we can elide the copy when returning this
  747. // variable (C++0x [class.copy]p34).
  748. DeclPtr = ReturnValue;
  749. if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
  750. if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
  751. // Create a flag that is used to indicate when the NRVO was applied
  752. // to this variable. Set it to zero to indicate that NRVO was not
  753. // applied.
  754. llvm::Value *Zero = Builder.getFalse();
  755. llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
  756. EnsureInsertPoint();
  757. Builder.CreateStore(Zero, NRVOFlag);
  758. // Record the NRVO flag for this variable.
  759. NRVOFlags[&D] = NRVOFlag;
  760. emission.NRVOFlag = NRVOFlag;
  761. }
  762. }
  763. } else {
  764. if (isByRef)
  765. LTy = BuildByRefType(&D);
  766. llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
  767. Alloc->setName(D.getName());
  768. CharUnits allocaAlignment = alignment;
  769. if (isByRef)
  770. allocaAlignment = std::max(allocaAlignment,
  771. getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0)));
  772. Alloc->setAlignment(allocaAlignment.getQuantity());
  773. DeclPtr = Alloc;
  774. // Emit a lifetime intrinsic if meaningful. There's no point
  775. // in doing this if we don't have a valid insertion point (?).
  776. uint64_t size = CGM.getDataLayout().getTypeAllocSize(LTy);
  777. if (HaveInsertPoint() && shouldUseLifetimeMarkers(*this, D, size)) {
  778. llvm::Value *sizeV = llvm::ConstantInt::get(Int64Ty, size);
  779. emission.SizeForLifetimeMarkers = sizeV;
  780. llvm::Value *castAddr = Builder.CreateBitCast(Alloc, Int8PtrTy);
  781. Builder.CreateCall2(CGM.getLLVMLifetimeStartFn(), sizeV, castAddr)
  782. ->setDoesNotThrow();
  783. } else {
  784. assert(!emission.useLifetimeMarkers());
  785. }
  786. }
  787. } else {
  788. EnsureInsertPoint();
  789. if (!DidCallStackSave) {
  790. // Save the stack.
  791. llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
  792. llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
  793. llvm::Value *V = Builder.CreateCall(F);
  794. Builder.CreateStore(V, Stack);
  795. DidCallStackSave = true;
  796. // Push a cleanup block and restore the stack there.
  797. // FIXME: in general circumstances, this should be an EH cleanup.
  798. pushStackRestore(NormalCleanup, Stack);
  799. }
  800. llvm::Value *elementCount;
  801. QualType elementType;
  802. std::tie(elementCount, elementType) = getVLASize(Ty);
  803. llvm::Type *llvmTy = ConvertTypeForMem(elementType);
  804. // Allocate memory for the array.
  805. llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
  806. vla->setAlignment(alignment.getQuantity());
  807. DeclPtr = vla;
  808. }
  809. llvm::Value *&DMEntry = LocalDeclMap[&D];
  810. assert(!DMEntry && "Decl already exists in localdeclmap!");
  811. DMEntry = DeclPtr;
  812. emission.Address = DeclPtr;
  813. // Emit debug info for local var declaration.
  814. if (HaveInsertPoint())
  815. if (CGDebugInfo *DI = getDebugInfo()) {
  816. if (CGM.getCodeGenOpts().getDebugInfo()
  817. >= CodeGenOptions::LimitedDebugInfo) {
  818. DI->setLocation(D.getLocation());
  819. DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
  820. }
  821. }
  822. if (D.hasAttr<AnnotateAttr>())
  823. EmitVarAnnotations(&D, emission.Address);
  824. return emission;
  825. }
  826. /// Determines whether the given __block variable is potentially
  827. /// captured by the given expression.
  828. static bool isCapturedBy(const VarDecl &var, const Expr *e) {
  829. // Skip the most common kinds of expressions that make
  830. // hierarchy-walking expensive.
  831. e = e->IgnoreParenCasts();
  832. if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
  833. const BlockDecl *block = be->getBlockDecl();
  834. for (const auto &I : block->captures()) {
  835. if (I.getVariable() == &var)
  836. return true;
  837. }
  838. // No need to walk into the subexpressions.
  839. return false;
  840. }
  841. if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
  842. const CompoundStmt *CS = SE->getSubStmt();
  843. for (const auto *BI : CS->body())
  844. if (const auto *E = dyn_cast<Expr>(BI)) {
  845. if (isCapturedBy(var, E))
  846. return true;
  847. }
  848. else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
  849. // special case declarations
  850. for (const auto *I : DS->decls()) {
  851. if (const auto *VD = dyn_cast<VarDecl>((I))) {
  852. const Expr *Init = VD->getInit();
  853. if (Init && isCapturedBy(var, Init))
  854. return true;
  855. }
  856. }
  857. }
  858. else
  859. // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
  860. // Later, provide code to poke into statements for capture analysis.
  861. return true;
  862. return false;
  863. }
  864. for (Stmt::const_child_range children = e->children(); children; ++children)
  865. if (isCapturedBy(var, cast<Expr>(*children)))
  866. return true;
  867. return false;
  868. }
  869. /// \brief Determine whether the given initializer is trivial in the sense
  870. /// that it requires no code to be generated.
  871. static bool isTrivialInitializer(const Expr *Init) {
  872. if (!Init)
  873. return true;
  874. if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
  875. if (CXXConstructorDecl *Constructor = Construct->getConstructor())
  876. if (Constructor->isTrivial() &&
  877. Constructor->isDefaultConstructor() &&
  878. !Construct->requiresZeroInitialization())
  879. return true;
  880. return false;
  881. }
  882. void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
  883. assert(emission.Variable && "emission was not valid!");
  884. // If this was emitted as a global constant, we're done.
  885. if (emission.wasEmittedAsGlobal()) return;
  886. const VarDecl &D = *emission.Variable;
  887. QualType type = D.getType();
  888. // If this local has an initializer, emit it now.
  889. const Expr *Init = D.getInit();
  890. // If we are at an unreachable point, we don't need to emit the initializer
  891. // unless it contains a label.
  892. if (!HaveInsertPoint()) {
  893. if (!Init || !ContainsLabel(Init)) return;
  894. EnsureInsertPoint();
  895. }
  896. // Initialize the structure of a __block variable.
  897. if (emission.IsByRef)
  898. emitByrefStructureInit(emission);
  899. if (isTrivialInitializer(Init))
  900. return;
  901. CharUnits alignment = emission.Alignment;
  902. // Check whether this is a byref variable that's potentially
  903. // captured and moved by its own initializer. If so, we'll need to
  904. // emit the initializer first, then copy into the variable.
  905. bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
  906. llvm::Value *Loc =
  907. capturedByInit ? emission.Address : emission.getObjectAddress(*this);
  908. llvm::Constant *constant = nullptr;
  909. if (emission.IsConstantAggregate || D.isConstexpr()) {
  910. assert(!capturedByInit && "constant init contains a capturing block?");
  911. constant = CGM.EmitConstantInit(D, this);
  912. }
  913. if (!constant) {
  914. LValue lv = MakeAddrLValue(Loc, type, alignment);
  915. lv.setNonGC(true);
  916. return EmitExprAsInit(Init, &D, lv, capturedByInit);
  917. }
  918. if (!emission.IsConstantAggregate) {
  919. // For simple scalar/complex initialization, store the value directly.
  920. LValue lv = MakeAddrLValue(Loc, type, alignment);
  921. lv.setNonGC(true);
  922. return EmitStoreThroughLValue(RValue::get(constant), lv, true);
  923. }
  924. // If this is a simple aggregate initialization, we can optimize it
  925. // in various ways.
  926. bool isVolatile = type.isVolatileQualified();
  927. llvm::Value *SizeVal =
  928. llvm::ConstantInt::get(IntPtrTy,
  929. getContext().getTypeSizeInChars(type).getQuantity());
  930. llvm::Type *BP = Int8PtrTy;
  931. if (Loc->getType() != BP)
  932. Loc = Builder.CreateBitCast(Loc, BP);
  933. // If the initializer is all or mostly zeros, codegen with memset then do
  934. // a few stores afterward.
  935. if (shouldUseMemSetPlusStoresToInitialize(constant,
  936. CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
  937. Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
  938. alignment.getQuantity(), isVolatile);
  939. // Zero and undef don't require a stores.
  940. if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
  941. Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
  942. emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
  943. }
  944. } else {
  945. // Otherwise, create a temporary global with the initializer then
  946. // memcpy from the global to the alloca.
  947. std::string Name = GetStaticDeclName(*this, D, ".");
  948. llvm::GlobalVariable *GV =
  949. new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
  950. llvm::GlobalValue::PrivateLinkage,
  951. constant, Name);
  952. GV->setAlignment(alignment.getQuantity());
  953. GV->setUnnamedAddr(true);
  954. llvm::Value *SrcPtr = GV;
  955. if (SrcPtr->getType() != BP)
  956. SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
  957. Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
  958. isVolatile);
  959. }
  960. }
  961. /// Emit an expression as an initializer for a variable at the given
  962. /// location. The expression is not necessarily the normal
  963. /// initializer for the variable, and the address is not necessarily
  964. /// its normal location.
  965. ///
  966. /// \param init the initializing expression
  967. /// \param var the variable to act as if we're initializing
  968. /// \param loc the address to initialize; its type is a pointer
  969. /// to the LLVM mapping of the variable's type
  970. /// \param alignment the alignment of the address
  971. /// \param capturedByInit true if the variable is a __block variable
  972. /// whose address is potentially changed by the initializer
  973. void CodeGenFunction::EmitExprAsInit(const Expr *init,
  974. const ValueDecl *D,
  975. LValue lvalue,
  976. bool capturedByInit) {
  977. QualType type = D->getType();
  978. if (type->isReferenceType()) {
  979. RValue rvalue = EmitReferenceBindingToExpr(init);
  980. if (capturedByInit)
  981. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  982. EmitStoreThroughLValue(rvalue, lvalue, true);
  983. return;
  984. }
  985. switch (getEvaluationKind(type)) {
  986. case TEK_Scalar:
  987. EmitScalarInit(init, D, lvalue, capturedByInit);
  988. return;
  989. case TEK_Complex: {
  990. ComplexPairTy complex = EmitComplexExpr(init);
  991. if (capturedByInit)
  992. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  993. EmitStoreOfComplex(complex, lvalue, /*init*/ true);
  994. return;
  995. }
  996. case TEK_Aggregate:
  997. if (type->isAtomicType()) {
  998. EmitAtomicInit(const_cast<Expr*>(init), lvalue);
  999. } else {
  1000. // TODO: how can we delay here if D is captured by its initializer?
  1001. EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
  1002. AggValueSlot::IsDestructed,
  1003. AggValueSlot::DoesNotNeedGCBarriers,
  1004. AggValueSlot::IsNotAliased));
  1005. }
  1006. return;
  1007. }
  1008. llvm_unreachable("bad evaluation kind");
  1009. }
  1010. /// Enter a destroy cleanup for the given local variable.
  1011. void CodeGenFunction::emitAutoVarTypeCleanup(
  1012. const CodeGenFunction::AutoVarEmission &emission,
  1013. QualType::DestructionKind dtorKind) {
  1014. assert(dtorKind != QualType::DK_none);
  1015. // Note that for __block variables, we want to destroy the
  1016. // original stack object, not the possibly forwarded object.
  1017. llvm::Value *addr = emission.getObjectAddress(*this);
  1018. const VarDecl *var = emission.Variable;
  1019. QualType type = var->getType();
  1020. CleanupKind cleanupKind = NormalAndEHCleanup;
  1021. CodeGenFunction::Destroyer *destroyer = nullptr;
  1022. switch (dtorKind) {
  1023. case QualType::DK_none:
  1024. llvm_unreachable("no cleanup for trivially-destructible variable");
  1025. case QualType::DK_cxx_destructor:
  1026. // If there's an NRVO flag on the emission, we need a different
  1027. // cleanup.
  1028. if (emission.NRVOFlag) {
  1029. assert(!type->isArrayType());
  1030. CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
  1031. EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor,
  1032. emission.NRVOFlag);
  1033. return;
  1034. }
  1035. break;
  1036. case QualType::DK_objc_strong_lifetime:
  1037. // Suppress cleanups for pseudo-strong variables.
  1038. if (var->isARCPseudoStrong()) return;
  1039. // Otherwise, consider whether to use an EH cleanup or not.
  1040. cleanupKind = getARCCleanupKind();
  1041. // Use the imprecise destroyer by default.
  1042. if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
  1043. destroyer = CodeGenFunction::destroyARCStrongImprecise;
  1044. break;
  1045. case QualType::DK_objc_weak_lifetime:
  1046. break;
  1047. }
  1048. // If we haven't chosen a more specific destroyer, use the default.
  1049. if (!destroyer) destroyer = getDestroyer(dtorKind);
  1050. // Use an EH cleanup in array destructors iff the destructor itself
  1051. // is being pushed as an EH cleanup.
  1052. bool useEHCleanup = (cleanupKind & EHCleanup);
  1053. EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
  1054. useEHCleanup);
  1055. }
  1056. void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
  1057. assert(emission.Variable && "emission was not valid!");
  1058. // If this was emitted as a global constant, we're done.
  1059. if (emission.wasEmittedAsGlobal()) return;
  1060. // If we don't have an insertion point, we're done. Sema prevents
  1061. // us from jumping into any of these scopes anyway.
  1062. if (!HaveInsertPoint()) return;
  1063. const VarDecl &D = *emission.Variable;
  1064. // Make sure we call @llvm.lifetime.end. This needs to happen
  1065. // *last*, so the cleanup needs to be pushed *first*.
  1066. if (emission.useLifetimeMarkers()) {
  1067. EHStack.pushCleanup<CallLifetimeEnd>(NormalCleanup,
  1068. emission.getAllocatedAddress(),
  1069. emission.getSizeForLifetimeMarkers());
  1070. }
  1071. // Check the type for a cleanup.
  1072. if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
  1073. emitAutoVarTypeCleanup(emission, dtorKind);
  1074. // In GC mode, honor objc_precise_lifetime.
  1075. if (getLangOpts().getGC() != LangOptions::NonGC &&
  1076. D.hasAttr<ObjCPreciseLifetimeAttr>()) {
  1077. EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
  1078. }
  1079. // Handle the cleanup attribute.
  1080. if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
  1081. const FunctionDecl *FD = CA->getFunctionDecl();
  1082. llvm::Constant *F = CGM.GetAddrOfFunction(FD);
  1083. assert(F && "Could not find function!");
  1084. const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
  1085. EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
  1086. }
  1087. // If this is a block variable, call _Block_object_destroy
  1088. // (on the unforwarded address).
  1089. if (emission.IsByRef)
  1090. enterByrefCleanup(emission);
  1091. }
  1092. CodeGenFunction::Destroyer *
  1093. CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
  1094. switch (kind) {
  1095. case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
  1096. case QualType::DK_cxx_destructor:
  1097. return destroyCXXObject;
  1098. case QualType::DK_objc_strong_lifetime:
  1099. return destroyARCStrongPrecise;
  1100. case QualType::DK_objc_weak_lifetime:
  1101. return destroyARCWeak;
  1102. }
  1103. llvm_unreachable("Unknown DestructionKind");
  1104. }
  1105. /// pushEHDestroy - Push the standard destructor for the given type as
  1106. /// an EH-only cleanup.
  1107. void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
  1108. llvm::Value *addr, QualType type) {
  1109. assert(dtorKind && "cannot push destructor for trivial type");
  1110. assert(needsEHCleanup(dtorKind));
  1111. pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
  1112. }
  1113. /// pushDestroy - Push the standard destructor for the given type as
  1114. /// at least a normal cleanup.
  1115. void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
  1116. llvm::Value *addr, QualType type) {
  1117. assert(dtorKind && "cannot push destructor for trivial type");
  1118. CleanupKind cleanupKind = getCleanupKind(dtorKind);
  1119. pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
  1120. cleanupKind & EHCleanup);
  1121. }
  1122. void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *addr,
  1123. QualType type, Destroyer *destroyer,
  1124. bool useEHCleanupForArray) {
  1125. pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
  1126. destroyer, useEHCleanupForArray);
  1127. }
  1128. void CodeGenFunction::pushStackRestore(CleanupKind Kind, llvm::Value *SPMem) {
  1129. EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
  1130. }
  1131. void CodeGenFunction::pushLifetimeExtendedDestroy(
  1132. CleanupKind cleanupKind, llvm::Value *addr, QualType type,
  1133. Destroyer *destroyer, bool useEHCleanupForArray) {
  1134. assert(!isInConditionalBranch() &&
  1135. "performing lifetime extension from within conditional");
  1136. // Push an EH-only cleanup for the object now.
  1137. // FIXME: When popping normal cleanups, we need to keep this EH cleanup
  1138. // around in case a temporary's destructor throws an exception.
  1139. if (cleanupKind & EHCleanup)
  1140. EHStack.pushCleanup<DestroyObject>(
  1141. static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
  1142. destroyer, useEHCleanupForArray);
  1143. // Remember that we need to push a full cleanup for the object at the
  1144. // end of the full-expression.
  1145. pushCleanupAfterFullExpr<DestroyObject>(
  1146. cleanupKind, addr, type, destroyer, useEHCleanupForArray);
  1147. }
  1148. /// emitDestroy - Immediately perform the destruction of the given
  1149. /// object.
  1150. ///
  1151. /// \param addr - the address of the object; a type*
  1152. /// \param type - the type of the object; if an array type, all
  1153. /// objects are destroyed in reverse order
  1154. /// \param destroyer - the function to call to destroy individual
  1155. /// elements
  1156. /// \param useEHCleanupForArray - whether an EH cleanup should be
  1157. /// used when destroying array elements, in case one of the
  1158. /// destructions throws an exception
  1159. void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type,
  1160. Destroyer *destroyer,
  1161. bool useEHCleanupForArray) {
  1162. const ArrayType *arrayType = getContext().getAsArrayType(type);
  1163. if (!arrayType)
  1164. return destroyer(*this, addr, type);
  1165. llvm::Value *begin = addr;
  1166. llvm::Value *length = emitArrayLength(arrayType, type, begin);
  1167. // Normally we have to check whether the array is zero-length.
  1168. bool checkZeroLength = true;
  1169. // But if the array length is constant, we can suppress that.
  1170. if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
  1171. // ...and if it's constant zero, we can just skip the entire thing.
  1172. if (constLength->isZero()) return;
  1173. checkZeroLength = false;
  1174. }
  1175. llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
  1176. emitArrayDestroy(begin, end, type, destroyer,
  1177. checkZeroLength, useEHCleanupForArray);
  1178. }
  1179. /// emitArrayDestroy - Destroys all the elements of the given array,
  1180. /// beginning from last to first. The array cannot be zero-length.
  1181. ///
  1182. /// \param begin - a type* denoting the first element of the array
  1183. /// \param end - a type* denoting one past the end of the array
  1184. /// \param type - the element type of the array
  1185. /// \param destroyer - the function to call to destroy elements
  1186. /// \param useEHCleanup - whether to push an EH cleanup to destroy
  1187. /// the remaining elements in case the destruction of a single
  1188. /// element throws
  1189. void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
  1190. llvm::Value *end,
  1191. QualType type,
  1192. Destroyer *destroyer,
  1193. bool checkZeroLength,
  1194. bool useEHCleanup) {
  1195. assert(!type->isArrayType());
  1196. // The basic structure here is a do-while loop, because we don't
  1197. // need to check for the zero-element case.
  1198. llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
  1199. llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
  1200. if (checkZeroLength) {
  1201. llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
  1202. "arraydestroy.isempty");
  1203. Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
  1204. }
  1205. // Enter the loop body, making that address the current address.
  1206. llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
  1207. EmitBlock(bodyBB);
  1208. llvm::PHINode *elementPast =
  1209. Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
  1210. elementPast->addIncoming(end, entryBB);
  1211. // Shift the address back by one element.
  1212. llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
  1213. llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
  1214. "arraydestroy.element");
  1215. if (useEHCleanup)
  1216. pushRegularPartialArrayCleanup(begin, element, type, destroyer);
  1217. // Perform the actual destruction there.
  1218. destroyer(*this, element, type);
  1219. if (useEHCleanup)
  1220. PopCleanupBlock();
  1221. // Check whether we've reached the end.
  1222. llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
  1223. Builder.CreateCondBr(done, doneBB, bodyBB);
  1224. elementPast->addIncoming(element, Builder.GetInsertBlock());
  1225. // Done.
  1226. EmitBlock(doneBB);
  1227. }
  1228. /// Perform partial array destruction as if in an EH cleanup. Unlike
  1229. /// emitArrayDestroy, the element type here may still be an array type.
  1230. static void emitPartialArrayDestroy(CodeGenFunction &CGF,
  1231. llvm::Value *begin, llvm::Value *end,
  1232. QualType type,
  1233. CodeGenFunction::Destroyer *destroyer) {
  1234. // If the element type is itself an array, drill down.
  1235. unsigned arrayDepth = 0;
  1236. while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
  1237. // VLAs don't require a GEP index to walk into.
  1238. if (!isa<VariableArrayType>(arrayType))
  1239. arrayDepth++;
  1240. type = arrayType->getElementType();
  1241. }
  1242. if (arrayDepth) {
  1243. llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, arrayDepth+1);
  1244. SmallVector<llvm::Value*,4> gepIndices(arrayDepth, zero);
  1245. begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
  1246. end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
  1247. }
  1248. // Destroy the array. We don't ever need an EH cleanup because we
  1249. // assume that we're in an EH cleanup ourselves, so a throwing
  1250. // destructor causes an immediate terminate.
  1251. CGF.emitArrayDestroy(begin, end, type, destroyer,
  1252. /*checkZeroLength*/ true, /*useEHCleanup*/ false);
  1253. }
  1254. namespace {
  1255. /// RegularPartialArrayDestroy - a cleanup which performs a partial
  1256. /// array destroy where the end pointer is regularly determined and
  1257. /// does not need to be loaded from a local.
  1258. class RegularPartialArrayDestroy : public EHScopeStack::Cleanup {
  1259. llvm::Value *ArrayBegin;
  1260. llvm::Value *ArrayEnd;
  1261. QualType ElementType;
  1262. CodeGenFunction::Destroyer *Destroyer;
  1263. public:
  1264. RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
  1265. QualType elementType,
  1266. CodeGenFunction::Destroyer *destroyer)
  1267. : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
  1268. ElementType(elementType), Destroyer(destroyer) {}
  1269. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1270. emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
  1271. ElementType, Destroyer);
  1272. }
  1273. };
  1274. /// IrregularPartialArrayDestroy - a cleanup which performs a
  1275. /// partial array destroy where the end pointer is irregularly
  1276. /// determined and must be loaded from a local.
  1277. class IrregularPartialArrayDestroy : public EHScopeStack::Cleanup {
  1278. llvm::Value *ArrayBegin;
  1279. llvm::Value *ArrayEndPointer;
  1280. QualType ElementType;
  1281. CodeGenFunction::Destroyer *Destroyer;
  1282. public:
  1283. IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
  1284. llvm::Value *arrayEndPointer,
  1285. QualType elementType,
  1286. CodeGenFunction::Destroyer *destroyer)
  1287. : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
  1288. ElementType(elementType), Destroyer(destroyer) {}
  1289. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1290. llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
  1291. emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
  1292. ElementType, Destroyer);
  1293. }
  1294. };
  1295. }
  1296. /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
  1297. /// already-constructed elements of the given array. The cleanup
  1298. /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
  1299. ///
  1300. /// \param elementType - the immediate element type of the array;
  1301. /// possibly still an array type
  1302. void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
  1303. llvm::Value *arrayEndPointer,
  1304. QualType elementType,
  1305. Destroyer *destroyer) {
  1306. pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
  1307. arrayBegin, arrayEndPointer,
  1308. elementType, destroyer);
  1309. }
  1310. /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
  1311. /// already-constructed elements of the given array. The cleanup
  1312. /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
  1313. ///
  1314. /// \param elementType - the immediate element type of the array;
  1315. /// possibly still an array type
  1316. void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
  1317. llvm::Value *arrayEnd,
  1318. QualType elementType,
  1319. Destroyer *destroyer) {
  1320. pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
  1321. arrayBegin, arrayEnd,
  1322. elementType, destroyer);
  1323. }
  1324. /// Lazily declare the @llvm.lifetime.start intrinsic.
  1325. llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
  1326. if (LifetimeStartFn) return LifetimeStartFn;
  1327. LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
  1328. llvm::Intrinsic::lifetime_start);
  1329. return LifetimeStartFn;
  1330. }
  1331. /// Lazily declare the @llvm.lifetime.end intrinsic.
  1332. llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
  1333. if (LifetimeEndFn) return LifetimeEndFn;
  1334. LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
  1335. llvm::Intrinsic::lifetime_end);
  1336. return LifetimeEndFn;
  1337. }
  1338. namespace {
  1339. /// A cleanup to perform a release of an object at the end of a
  1340. /// function. This is used to balance out the incoming +1 of a
  1341. /// ns_consumed argument when we can't reasonably do that just by
  1342. /// not doing the initial retain for a __block argument.
  1343. struct ConsumeARCParameter : EHScopeStack::Cleanup {
  1344. ConsumeARCParameter(llvm::Value *param,
  1345. ARCPreciseLifetime_t precise)
  1346. : Param(param), Precise(precise) {}
  1347. llvm::Value *Param;
  1348. ARCPreciseLifetime_t Precise;
  1349. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1350. CGF.EmitARCRelease(Param, Precise);
  1351. }
  1352. };
  1353. }
  1354. /// Emit an alloca (or GlobalValue depending on target)
  1355. /// for the specified parameter and set up LocalDeclMap.
  1356. void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
  1357. bool ArgIsPointer, unsigned ArgNo) {
  1358. // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
  1359. assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
  1360. "Invalid argument to EmitParmDecl");
  1361. Arg->setName(D.getName());
  1362. QualType Ty = D.getType();
  1363. // Use better IR generation for certain implicit parameters.
  1364. if (isa<ImplicitParamDecl>(D)) {
  1365. // The only implicit argument a block has is its literal.
  1366. if (BlockInfo) {
  1367. LocalDeclMap[&D] = Arg;
  1368. llvm::Value *LocalAddr = nullptr;
  1369. if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
  1370. // Allocate a stack slot to let the debug info survive the RA.
  1371. llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
  1372. D.getName() + ".addr");
  1373. Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity());
  1374. LValue lv = MakeAddrLValue(Alloc, Ty, getContext().getDeclAlign(&D));
  1375. EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
  1376. LocalAddr = Builder.CreateLoad(Alloc);
  1377. }
  1378. if (CGDebugInfo *DI = getDebugInfo()) {
  1379. if (CGM.getCodeGenOpts().getDebugInfo()
  1380. >= CodeGenOptions::LimitedDebugInfo) {
  1381. DI->setLocation(D.getLocation());
  1382. DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, LocalAddr, Builder);
  1383. }
  1384. }
  1385. return;
  1386. }
  1387. }
  1388. llvm::Value *DeclPtr;
  1389. bool DoStore = false;
  1390. bool IsScalar = hasScalarEvaluationKind(Ty);
  1391. CharUnits Align = getContext().getDeclAlign(&D);
  1392. // If we already have a pointer to the argument, reuse the input pointer.
  1393. if (ArgIsPointer) {
  1394. // If we have a prettier pointer type at this point, bitcast to that.
  1395. unsigned AS = cast<llvm::PointerType>(Arg->getType())->getAddressSpace();
  1396. llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
  1397. DeclPtr = Arg->getType() == IRTy ? Arg : Builder.CreateBitCast(Arg, IRTy,
  1398. D.getName());
  1399. // Push a destructor cleanup for this parameter if the ABI requires it.
  1400. if (!IsScalar &&
  1401. getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
  1402. const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  1403. if (RD && RD->hasNonTrivialDestructor())
  1404. pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
  1405. }
  1406. } else {
  1407. // Otherwise, create a temporary to hold the value.
  1408. llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
  1409. D.getName() + ".addr");
  1410. Alloc->setAlignment(Align.getQuantity());
  1411. DeclPtr = Alloc;
  1412. DoStore = true;
  1413. }
  1414. LValue lv = MakeAddrLValue(DeclPtr, Ty, Align);
  1415. if (IsScalar) {
  1416. Qualifiers qs = Ty.getQualifiers();
  1417. if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
  1418. // We honor __attribute__((ns_consumed)) for types with lifetime.
  1419. // For __strong, it's handled by just skipping the initial retain;
  1420. // otherwise we have to balance out the initial +1 with an extra
  1421. // cleanup to do the release at the end of the function.
  1422. bool isConsumed = D.hasAttr<NSConsumedAttr>();
  1423. // 'self' is always formally __strong, but if this is not an
  1424. // init method then we don't want to retain it.
  1425. if (D.isARCPseudoStrong()) {
  1426. const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
  1427. assert(&D == method->getSelfDecl());
  1428. assert(lt == Qualifiers::OCL_Strong);
  1429. assert(qs.hasConst());
  1430. assert(method->getMethodFamily() != OMF_init);
  1431. (void) method;
  1432. lt = Qualifiers::OCL_ExplicitNone;
  1433. }
  1434. if (lt == Qualifiers::OCL_Strong) {
  1435. if (!isConsumed) {
  1436. if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
  1437. // use objc_storeStrong(&dest, value) for retaining the
  1438. // object. But first, store a null into 'dest' because
  1439. // objc_storeStrong attempts to release its old value.
  1440. llvm::Value *Null = CGM.EmitNullConstant(D.getType());
  1441. EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
  1442. EmitARCStoreStrongCall(lv.getAddress(), Arg, true);
  1443. DoStore = false;
  1444. }
  1445. else
  1446. // Don't use objc_retainBlock for block pointers, because we
  1447. // don't want to Block_copy something just because we got it
  1448. // as a parameter.
  1449. Arg = EmitARCRetainNonBlock(Arg);
  1450. }
  1451. } else {
  1452. // Push the cleanup for a consumed parameter.
  1453. if (isConsumed) {
  1454. ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
  1455. ? ARCPreciseLifetime : ARCImpreciseLifetime);
  1456. EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg,
  1457. precise);
  1458. }
  1459. if (lt == Qualifiers::OCL_Weak) {
  1460. EmitARCInitWeak(DeclPtr, Arg);
  1461. DoStore = false; // The weak init is a store, no need to do two.
  1462. }
  1463. }
  1464. // Enter the cleanup scope.
  1465. EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
  1466. }
  1467. }
  1468. // Store the initial value into the alloca.
  1469. if (DoStore)
  1470. EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
  1471. llvm::Value *&DMEntry = LocalDeclMap[&D];
  1472. assert(!DMEntry && "Decl already exists in localdeclmap!");
  1473. DMEntry = DeclPtr;
  1474. // Emit debug info for param declaration.
  1475. if (CGDebugInfo *DI = getDebugInfo()) {
  1476. if (CGM.getCodeGenOpts().getDebugInfo()
  1477. >= CodeGenOptions::LimitedDebugInfo) {
  1478. DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
  1479. }
  1480. }
  1481. if (D.hasAttr<AnnotateAttr>())
  1482. EmitVarAnnotations(&D, DeclPtr);
  1483. }