CGDecl.cpp 55 KB

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