1 //===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code to emit Decl nodes as LLVM code.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenFunction.h"
15 #include "CGDebugInfo.h"
16 #include "CGOpenCLRuntime.h"
17 #include "CodeGenModule.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "clang/Basic/TargetInfo.h"
24 #include "clang/CodeGen/CGFunctionInfo.h"
25 #include "clang/Frontend/CodeGenOptions.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/GlobalVariable.h"
28 #include "llvm/IR/Intrinsics.h"
29 #include "llvm/IR/Type.h"
30 using namespace clang;
31 using namespace CodeGen;
34 void CodeGenFunction::EmitDecl(const Decl &D) {
35 switch (D.getKind()) {
36 case Decl::TranslationUnit:
38 case Decl::UnresolvedUsingTypename:
39 case Decl::ClassTemplateSpecialization:
40 case Decl::ClassTemplatePartialSpecialization:
41 case Decl::VarTemplateSpecialization:
42 case Decl::VarTemplatePartialSpecialization:
43 case Decl::TemplateTypeParm:
44 case Decl::UnresolvedUsingValue:
45 case Decl::NonTypeTemplateParm:
47 case Decl::CXXConstructor:
48 case Decl::CXXDestructor:
49 case Decl::CXXConversion:
51 case Decl::MSProperty:
52 case Decl::IndirectField:
54 case Decl::ObjCAtDefsField:
56 case Decl::ImplicitParam:
57 case Decl::ClassTemplate:
58 case Decl::VarTemplate:
59 case Decl::FunctionTemplate:
60 case Decl::TypeAliasTemplate:
61 case Decl::TemplateTemplateParm:
62 case Decl::ObjCMethod:
63 case Decl::ObjCCategory:
64 case Decl::ObjCProtocol:
65 case Decl::ObjCInterface:
66 case Decl::ObjCCategoryImpl:
67 case Decl::ObjCImplementation:
68 case Decl::ObjCProperty:
69 case Decl::ObjCCompatibleAlias:
70 case Decl::AccessSpec:
71 case Decl::LinkageSpec:
72 case Decl::ObjCPropertyImpl:
73 case Decl::FileScopeAsm:
75 case Decl::FriendTemplate:
78 case Decl::ClassScopeFunctionSpecialization:
79 case Decl::UsingShadow:
80 llvm_unreachable("Declaration should not be in declstmts!");
81 case Decl::Function: // void X();
82 case Decl::Record: // struct/union/class X;
83 case Decl::Enum: // enum X;
84 case Decl::EnumConstant: // enum ? { X = ? }
85 case Decl::CXXRecord: // struct/union/class X; [C++]
86 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
87 case Decl::Label: // __label__ x;
89 case Decl::OMPThreadPrivate:
91 // None of these decls require codegen support.
94 case Decl::NamespaceAlias:
95 if (CGDebugInfo *DI = getDebugInfo())
96 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
98 case Decl::Using: // using X; [C++]
99 if (CGDebugInfo *DI = getDebugInfo())
100 DI->EmitUsingDecl(cast<UsingDecl>(D));
102 case Decl::UsingDirective: // using namespace X; [C++]
103 if (CGDebugInfo *DI = getDebugInfo())
104 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
107 const VarDecl &VD = cast<VarDecl>(D);
108 assert(VD.isLocalVarDecl() &&
109 "Should not see file-scope variables inside a function!");
110 return EmitVarDecl(VD);
113 case Decl::Typedef: // typedef int X;
114 case Decl::TypeAlias: { // using X = int; [C++0x]
115 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
116 QualType Ty = TD.getUnderlyingType();
118 if (Ty->isVariablyModifiedType())
119 EmitVariablyModifiedType(Ty);
124 /// EmitVarDecl - This method handles emission of any variable declaration
125 /// inside a function, including static vars etc.
126 void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
127 if (D.isStaticLocal()) {
128 llvm::GlobalValue::LinkageTypes Linkage =
129 llvm::GlobalValue::InternalLinkage;
131 // If the variable is externally visible, it must have weak linkage so it
133 if (D.isExternallyVisible()) {
134 Linkage = llvm::GlobalValue::LinkOnceODRLinkage;
136 // FIXME: We need to force the emission/use of a guard variable for
137 // some variables even if we can constant-evaluate them because
138 // we can't guarantee every translation unit will constant-evaluate them.
141 return EmitStaticVarDecl(D, Linkage);
144 if (D.hasExternalStorage())
145 // Don't emit it now, allow it to be emitted lazily on its first use.
148 if (D.getStorageClass() == SC_OpenCLWorkGroupLocal)
149 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
151 assert(D.hasLocalStorage());
152 return EmitAutoVarDecl(D);
155 static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D,
156 const char *Separator) {
157 CodeGenModule &CGM = CGF.CGM;
158 if (CGF.getLangOpts().CPlusPlus) {
159 StringRef Name = CGM.getMangledName(&D);
163 std::string ContextName;
164 if (!CGF.CurFuncDecl) {
165 // Better be in a block declared in global scope.
166 const NamedDecl *ND = cast<NamedDecl>(&D);
167 const DeclContext *DC = ND->getDeclContext();
168 if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
170 CGM.getBlockMangledName(GlobalDecl(), Name, BD);
171 ContextName = Name.getString();
174 llvm_unreachable("Unknown context for block static var decl");
175 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl)) {
176 StringRef Name = CGM.getMangledName(FD);
177 ContextName = Name.str();
178 } else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
179 ContextName = CGF.CurFn->getName();
181 llvm_unreachable("Unknown context for static var decl");
183 return ContextName + Separator + D.getNameAsString();
186 llvm::GlobalVariable *
187 CodeGenFunction::CreateStaticVarDecl(const VarDecl &D,
188 const char *Separator,
189 llvm::GlobalValue::LinkageTypes Linkage) {
190 QualType Ty = D.getType();
191 assert(Ty->isConstantSizeType() && "VLAs can't be static");
193 // Use the label if the variable is renamed with the asm-label extension.
195 if (D.hasAttr<AsmLabelAttr>())
196 Name = CGM.getMangledName(&D);
198 Name = GetStaticDeclName(*this, D, Separator);
200 llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
202 CGM.GetGlobalVarAddressSpace(&D, CGM.getContext().getTargetAddressSpace(Ty));
203 llvm::GlobalVariable *GV =
204 new llvm::GlobalVariable(CGM.getModule(), LTy,
205 Ty.isConstant(getContext()), Linkage,
206 CGM.EmitNullConstant(D.getType()), Name, 0,
207 llvm::GlobalVariable::NotThreadLocal,
209 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
210 CGM.setGlobalVisibility(GV, &D);
213 CGM.setTLSMode(GV, D);
218 /// hasNontrivialDestruction - Determine whether a type's destruction is
219 /// non-trivial. If so, and the variable uses static initialization, we must
220 /// register its destructor to run on exit.
221 static bool hasNontrivialDestruction(QualType T) {
222 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
223 return RD && !RD->hasTrivialDestructor();
226 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
227 /// global variable that has already been created for it. If the initializer
228 /// has a different type than GV does, this may free GV and return a different
229 /// one. Otherwise it just returns GV.
230 llvm::GlobalVariable *
231 CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
232 llvm::GlobalVariable *GV) {
233 llvm::Constant *Init = CGM.EmitConstantInit(D, this);
235 // If constant emission failed, then this should be a C++ static
238 if (!getLangOpts().CPlusPlus)
239 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
240 else if (Builder.GetInsertBlock()) {
241 // Since we have a static initializer, this global variable can't
243 GV->setConstant(false);
245 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
250 // The initializer may differ in type from the global. Rewrite
251 // the global to match the initializer. (We have to do this
252 // because some types, like unions, can't be completely represented
253 // in the LLVM type system.)
254 if (GV->getType()->getElementType() != Init->getType()) {
255 llvm::GlobalVariable *OldGV = GV;
257 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
259 OldGV->getLinkage(), Init, "",
260 /*InsertBefore*/ OldGV,
261 OldGV->getThreadLocalMode(),
262 CGM.getContext().getTargetAddressSpace(D.getType()));
263 GV->setVisibility(OldGV->getVisibility());
265 // Steal the name of the old global
268 // Replace all uses of the old global with the new global
269 llvm::Constant *NewPtrForOldDecl =
270 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
271 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
273 // Erase the old global, since it is no longer used.
274 OldGV->eraseFromParent();
277 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
278 GV->setInitializer(Init);
280 if (hasNontrivialDestruction(D.getType())) {
281 // We have a constant initializer, but a nontrivial destructor. We still
282 // need to perform a guarded "initialization" in order to register the
284 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
290 void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
291 llvm::GlobalValue::LinkageTypes Linkage) {
292 llvm::Value *&DMEntry = LocalDeclMap[&D];
293 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
295 // Check to see if we already have a global variable for this
296 // declaration. This can happen when double-emitting function
297 // bodies, e.g. with complete and base constructors.
298 llvm::Constant *addr =
299 CGM.getStaticLocalDeclAddress(&D);
301 llvm::GlobalVariable *var;
303 var = cast<llvm::GlobalVariable>(addr->stripPointerCasts());
305 addr = var = CreateStaticVarDecl(D, ".", Linkage);
308 // Store into LocalDeclMap before generating initializer to handle
309 // circular references.
311 CGM.setStaticLocalDeclAddress(&D, addr);
313 // We can't have a VLA here, but we can have a pointer to a VLA,
314 // even though that doesn't really make any sense.
315 // Make sure to evaluate VLA bounds now so that we have them for later.
316 if (D.getType()->isVariablyModifiedType())
317 EmitVariablyModifiedType(D.getType());
319 // Save the type in case adding the initializer forces a type change.
320 llvm::Type *expectedType = addr->getType();
322 // If this value has an initializer, emit it.
324 var = AddInitializerToStaticVarDecl(D, var);
326 var->setAlignment(getContext().getDeclAlign(&D).getQuantity());
328 if (D.hasAttr<AnnotateAttr>())
329 CGM.AddGlobalAnnotations(&D, var);
331 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
332 var->setSection(SA->getName());
334 if (D.hasAttr<UsedAttr>())
335 CGM.AddUsedGlobal(var);
337 // We may have to cast the constant because of the initializer
340 // FIXME: It is really dangerous to store this in the map; if anyone
341 // RAUW's the GV uses of this constant will be invalid.
342 llvm::Constant *castedAddr = llvm::ConstantExpr::getBitCast(var, expectedType);
343 DMEntry = castedAddr;
344 CGM.setStaticLocalDeclAddress(&D, castedAddr);
346 // Emit global variable debug descriptor for static vars.
347 CGDebugInfo *DI = getDebugInfo();
349 CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
350 DI->setLocation(D.getLocation());
351 DI->EmitGlobalVariable(var, &D);
356 struct DestroyObject : EHScopeStack::Cleanup {
357 DestroyObject(llvm::Value *addr, QualType type,
358 CodeGenFunction::Destroyer *destroyer,
359 bool useEHCleanupForArray)
360 : addr(addr), type(type), destroyer(destroyer),
361 useEHCleanupForArray(useEHCleanupForArray) {}
365 CodeGenFunction::Destroyer *destroyer;
366 bool useEHCleanupForArray;
368 void Emit(CodeGenFunction &CGF, Flags flags) {
369 // Don't use an EH cleanup recursively from an EH cleanup.
370 bool useEHCleanupForArray =
371 flags.isForNormalCleanup() && this->useEHCleanupForArray;
373 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
377 struct DestroyNRVOVariable : EHScopeStack::Cleanup {
378 DestroyNRVOVariable(llvm::Value *addr,
379 const CXXDestructorDecl *Dtor,
380 llvm::Value *NRVOFlag)
381 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
383 const CXXDestructorDecl *Dtor;
384 llvm::Value *NRVOFlag;
387 void Emit(CodeGenFunction &CGF, Flags flags) {
388 // Along the exceptions path we always execute the dtor.
389 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
391 llvm::BasicBlock *SkipDtorBB = 0;
393 // If we exited via NRVO, we skip the destructor call.
394 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
395 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
396 llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
397 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
398 CGF.EmitBlock(RunDtorBB);
401 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
402 /*ForVirtualBase=*/false,
403 /*Delegating=*/false,
406 if (NRVO) CGF.EmitBlock(SkipDtorBB);
410 struct CallStackRestore : EHScopeStack::Cleanup {
412 CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
413 void Emit(CodeGenFunction &CGF, Flags flags) {
414 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
415 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
416 CGF.Builder.CreateCall(F, V);
420 struct ExtendGCLifetime : EHScopeStack::Cleanup {
422 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
424 void Emit(CodeGenFunction &CGF, Flags flags) {
425 // Compute the address of the local variable, in case it's a
426 // byref or something.
427 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
428 Var.getType(), VK_LValue, SourceLocation());
429 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
431 CGF.EmitExtendGCLifetime(value);
435 struct CallCleanupFunction : EHScopeStack::Cleanup {
436 llvm::Constant *CleanupFn;
437 const CGFunctionInfo &FnInfo;
440 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
442 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
444 void Emit(CodeGenFunction &CGF, Flags flags) {
445 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
446 Var.getType(), VK_LValue, SourceLocation());
447 // Compute the address of the local variable, in case it's a byref
449 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
451 // In some cases, the type of the function argument will be different from
452 // the type of the pointer. An example of this is
453 // void f(void* arg);
454 // __attribute__((cleanup(f))) void *g;
456 // To fix this we insert a bitcast here.
457 QualType ArgTy = FnInfo.arg_begin()->type;
459 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
462 Args.add(RValue::get(Arg),
463 CGF.getContext().getPointerType(Var.getType()));
464 CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
468 /// A cleanup to call @llvm.lifetime.end.
469 class CallLifetimeEnd : public EHScopeStack::Cleanup {
473 CallLifetimeEnd(llvm::Value *addr, llvm::Value *size)
474 : Addr(addr), Size(size) {}
476 void Emit(CodeGenFunction &CGF, Flags flags) {
477 llvm::Value *castAddr = CGF.Builder.CreateBitCast(Addr, CGF.Int8PtrTy);
478 CGF.Builder.CreateCall2(CGF.CGM.getLLVMLifetimeEndFn(),
485 /// EmitAutoVarWithLifetime - Does the setup required for an automatic
486 /// variable with lifetime.
487 static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
489 Qualifiers::ObjCLifetime lifetime) {
491 case Qualifiers::OCL_None:
492 llvm_unreachable("present but none");
494 case Qualifiers::OCL_ExplicitNone:
498 case Qualifiers::OCL_Strong: {
499 CodeGenFunction::Destroyer *destroyer =
500 (var.hasAttr<ObjCPreciseLifetimeAttr>()
501 ? CodeGenFunction::destroyARCStrongPrecise
502 : CodeGenFunction::destroyARCStrongImprecise);
504 CleanupKind cleanupKind = CGF.getARCCleanupKind();
505 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
506 cleanupKind & EHCleanup);
509 case Qualifiers::OCL_Autoreleasing:
513 case Qualifiers::OCL_Weak:
514 // __weak objects always get EH cleanups; otherwise, exceptions
515 // could cause really nasty crashes instead of mere leaks.
516 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
517 CodeGenFunction::destroyARCWeak,
518 /*useEHCleanup*/ true);
523 static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
524 if (const Expr *e = dyn_cast<Expr>(s)) {
525 // Skip the most common kinds of expressions that make
526 // hierarchy-walking expensive.
527 s = e = e->IgnoreParenCasts();
529 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
530 return (ref->getDecl() == &var);
531 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
532 const BlockDecl *block = be->getBlockDecl();
533 for (BlockDecl::capture_const_iterator i = block->capture_begin(),
534 e = block->capture_end(); i != e; ++i) {
535 if (i->getVariable() == &var)
541 for (Stmt::const_child_range children = s->children(); children; ++children)
542 // children might be null; as in missing decl or conditional of an if-stmt.
543 if ((*children) && isAccessedBy(var, *children))
549 static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
550 if (!decl) return false;
551 if (!isa<VarDecl>(decl)) return false;
552 const VarDecl *var = cast<VarDecl>(decl);
553 return isAccessedBy(*var, e);
556 static void drillIntoBlockVariable(CodeGenFunction &CGF,
558 const VarDecl *var) {
559 lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var));
562 void CodeGenFunction::EmitScalarInit(const Expr *init,
565 bool capturedByInit) {
566 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
568 llvm::Value *value = EmitScalarExpr(init);
570 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
571 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
575 // If we're emitting a value with lifetime, we have to do the
576 // initialization *before* we leave the cleanup scopes.
577 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
578 enterFullExpression(ewc);
579 init = ewc->getSubExpr();
581 CodeGenFunction::RunCleanupsScope Scope(*this);
583 // We have to maintain the illusion that the variable is
584 // zero-initialized. If the variable might be accessed in its
585 // initializer, zero-initialize before running the initializer, then
586 // actually perform the initialization with an assign.
587 bool accessedByInit = false;
588 if (lifetime != Qualifiers::OCL_ExplicitNone)
589 accessedByInit = (capturedByInit || isAccessedBy(D, init));
590 if (accessedByInit) {
591 LValue tempLV = lvalue;
592 // Drill down to the __block object if necessary.
593 if (capturedByInit) {
594 // We can use a simple GEP for this because it can't have been
596 tempLV.setAddress(Builder.CreateStructGEP(tempLV.getAddress(),
597 getByRefValueLLVMField(cast<VarDecl>(D))));
600 llvm::PointerType *ty
601 = cast<llvm::PointerType>(tempLV.getAddress()->getType());
602 ty = cast<llvm::PointerType>(ty->getElementType());
604 llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
606 // If __weak, we want to use a barrier under certain conditions.
607 if (lifetime == Qualifiers::OCL_Weak)
608 EmitARCInitWeak(tempLV.getAddress(), zero);
610 // Otherwise just do a simple store.
612 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
615 // Emit the initializer.
616 llvm::Value *value = 0;
619 case Qualifiers::OCL_None:
620 llvm_unreachable("present but none");
622 case Qualifiers::OCL_ExplicitNone:
624 value = EmitScalarExpr(init);
627 case Qualifiers::OCL_Strong: {
628 value = EmitARCRetainScalarExpr(init);
632 case Qualifiers::OCL_Weak: {
633 // No way to optimize a producing initializer into this. It's not
634 // worth optimizing for, because the value will immediately
635 // disappear in the common case.
636 value = EmitScalarExpr(init);
638 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
640 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
642 EmitARCInitWeak(lvalue.getAddress(), value);
646 case Qualifiers::OCL_Autoreleasing:
647 value = EmitARCRetainAutoreleaseScalarExpr(init);
651 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
653 // If the variable might have been accessed by its initializer, we
654 // might have to initialize with a barrier. We have to do this for
655 // both __weak and __strong, but __weak got filtered out above.
656 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
657 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
658 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
659 EmitARCRelease(oldValue, ARCImpreciseLifetime);
663 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
666 /// EmitScalarInit - Initialize the given lvalue with the given object.
667 void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
668 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
670 return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
673 case Qualifiers::OCL_None:
674 llvm_unreachable("present but none");
676 case Qualifiers::OCL_ExplicitNone:
680 case Qualifiers::OCL_Strong:
681 init = EmitARCRetain(lvalue.getType(), init);
684 case Qualifiers::OCL_Weak:
685 // Initialize and then skip the primitive store.
686 EmitARCInitWeak(lvalue.getAddress(), init);
689 case Qualifiers::OCL_Autoreleasing:
690 init = EmitARCRetainAutorelease(lvalue.getType(), init);
694 EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
697 /// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
698 /// non-zero parts of the specified initializer with equal or fewer than
699 /// NumStores scalar stores.
700 static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
701 unsigned &NumStores) {
702 // Zero and Undef never requires any extra stores.
703 if (isa<llvm::ConstantAggregateZero>(Init) ||
704 isa<llvm::ConstantPointerNull>(Init) ||
705 isa<llvm::UndefValue>(Init))
707 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
708 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
709 isa<llvm::ConstantExpr>(Init))
710 return Init->isNullValue() || NumStores--;
712 // See if we can emit each element.
713 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
714 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
715 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
716 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
722 if (llvm::ConstantDataSequential *CDS =
723 dyn_cast<llvm::ConstantDataSequential>(Init)) {
724 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
725 llvm::Constant *Elt = CDS->getElementAsConstant(i);
726 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
732 // Anything else is hard and scary.
736 /// emitStoresForInitAfterMemset - For inits that
737 /// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
738 /// stores that would be required.
739 static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
740 bool isVolatile, CGBuilderTy &Builder) {
741 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
742 "called emitStoresForInitAfterMemset for zero or undef value.");
744 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
745 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
746 isa<llvm::ConstantExpr>(Init)) {
747 Builder.CreateStore(Init, Loc, isVolatile);
751 if (llvm::ConstantDataSequential *CDS =
752 dyn_cast<llvm::ConstantDataSequential>(Init)) {
753 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
754 llvm::Constant *Elt = CDS->getElementAsConstant(i);
756 // If necessary, get a pointer to the element and emit it.
757 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
758 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
759 isVolatile, Builder);
764 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
765 "Unknown value type!");
767 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
768 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
770 // If necessary, get a pointer to the element and emit it.
771 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
772 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
773 isVolatile, Builder);
778 /// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
779 /// plus some stores to initialize a local variable instead of using a memcpy
780 /// from a constant global. It is beneficial to use memset if the global is all
781 /// zeros, or mostly zeros and large.
782 static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
783 uint64_t GlobalSize) {
784 // If a global is all zeros, always use a memset.
785 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
787 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
788 // do it if it will require 6 or fewer scalar stores.
789 // TODO: Should budget depends on the size? Avoiding a large global warrants
790 // plopping in more stores.
791 unsigned StoreBudget = 6;
792 uint64_t SizeLimit = 32;
794 return GlobalSize > SizeLimit &&
795 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
798 /// Should we use the LLVM lifetime intrinsics for the given local variable?
799 static bool shouldUseLifetimeMarkers(CodeGenFunction &CGF, const VarDecl &D,
801 // Always emit lifetime markers in -fsanitize=use-after-scope mode.
802 if (CGF.getLangOpts().Sanitize.UseAfterScope)
804 // For now, only in optimized builds.
805 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0)
808 // Limit the size of marked objects to 32 bytes. We don't want to increase
809 // compile time by marking tiny objects.
810 unsigned SizeThreshold = 32;
812 return Size > SizeThreshold;
816 /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
817 /// variable declaration with auto, register, or no storage class specifier.
818 /// These turn into simple stack objects, or GlobalValues depending on target.
819 void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
820 AutoVarEmission emission = EmitAutoVarAlloca(D);
821 EmitAutoVarInit(emission);
822 EmitAutoVarCleanups(emission);
825 /// EmitAutoVarAlloca - Emit the alloca and debug information for a
826 /// local variable. Does not emit initalization or destruction.
827 CodeGenFunction::AutoVarEmission
828 CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
829 QualType Ty = D.getType();
831 AutoVarEmission emission(D);
833 bool isByRef = D.hasAttr<BlocksAttr>();
834 emission.IsByRef = isByRef;
836 CharUnits alignment = getContext().getDeclAlign(&D);
837 emission.Alignment = alignment;
839 // If the type is variably-modified, emit all the VLA sizes for it.
840 if (Ty->isVariablyModifiedType())
841 EmitVariablyModifiedType(Ty);
843 llvm::Value *DeclPtr;
844 if (Ty->isConstantSizeType()) {
845 bool NRVO = getLangOpts().ElideConstructors &&
848 // If this value is an array or struct with a statically determinable
849 // constant initializer, there are optimizations we can do.
851 // TODO: We should constant-evaluate the initializer of any variable,
852 // as long as it is initialized by a constant expression. Currently,
853 // isConstantInitializer produces wrong answers for structs with
854 // reference or bitfield members, and a few other cases, and checking
855 // for POD-ness protects us from some of these.
856 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
858 ((Ty.isPODType(getContext()) ||
859 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
860 D.getInit()->isConstantInitializer(getContext(), false)))) {
862 // If the variable's a const type, and it's neither an NRVO
863 // candidate nor a __block variable and has no mutable members,
864 // emit it as a global instead.
865 if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
866 CGM.isTypeConstant(Ty, true)) {
867 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
869 emission.Address = 0; // signal this condition to later callbacks
870 assert(emission.wasEmittedAsGlobal());
874 // Otherwise, tell the initialization code that we're in this case.
875 emission.IsConstantAggregate = true;
878 // A normal fixed sized variable becomes an alloca in the entry block,
879 // unless it's an NRVO variable.
880 llvm::Type *LTy = ConvertTypeForMem(Ty);
883 // The named return value optimization: allocate this variable in the
884 // return slot, so that we can elide the copy when returning this
885 // variable (C++0x [class.copy]p34).
886 DeclPtr = ReturnValue;
888 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
889 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
890 // Create a flag that is used to indicate when the NRVO was applied
891 // to this variable. Set it to zero to indicate that NRVO was not
893 llvm::Value *Zero = Builder.getFalse();
894 llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
896 Builder.CreateStore(Zero, NRVOFlag);
898 // Record the NRVO flag for this variable.
899 NRVOFlags[&D] = NRVOFlag;
900 emission.NRVOFlag = NRVOFlag;
905 LTy = BuildByRefType(&D);
907 llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
908 Alloc->setName(D.getName());
910 CharUnits allocaAlignment = alignment;
912 allocaAlignment = std::max(allocaAlignment,
913 getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0)));
914 Alloc->setAlignment(allocaAlignment.getQuantity());
917 // Emit a lifetime intrinsic if meaningful. There's no point
918 // in doing this if we don't have a valid insertion point (?).
919 uint64_t size = CGM.getDataLayout().getTypeAllocSize(LTy);
920 if (HaveInsertPoint() && shouldUseLifetimeMarkers(*this, D, size)) {
921 llvm::Value *sizeV = llvm::ConstantInt::get(Int64Ty, size);
923 emission.SizeForLifetimeMarkers = sizeV;
924 llvm::Value *castAddr = Builder.CreateBitCast(Alloc, Int8PtrTy);
925 Builder.CreateCall2(CGM.getLLVMLifetimeStartFn(), sizeV, castAddr)
928 assert(!emission.useLifetimeMarkers());
934 if (!DidCallStackSave) {
936 llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
938 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
939 llvm::Value *V = Builder.CreateCall(F);
941 Builder.CreateStore(V, Stack);
943 DidCallStackSave = true;
945 // Push a cleanup block and restore the stack there.
946 // FIXME: in general circumstances, this should be an EH cleanup.
947 EHStack.pushCleanup<CallStackRestore>(NormalCleanup, Stack);
950 llvm::Value *elementCount;
951 QualType elementType;
952 llvm::tie(elementCount, elementType) = getVLASize(Ty);
954 llvm::Type *llvmTy = ConvertTypeForMem(elementType);
956 // Allocate memory for the array.
957 llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
958 vla->setAlignment(alignment.getQuantity());
963 llvm::Value *&DMEntry = LocalDeclMap[&D];
964 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
966 emission.Address = DeclPtr;
968 // Emit debug info for local var declaration.
969 if (HaveInsertPoint())
970 if (CGDebugInfo *DI = getDebugInfo()) {
971 if (CGM.getCodeGenOpts().getDebugInfo()
972 >= CodeGenOptions::LimitedDebugInfo) {
973 DI->setLocation(D.getLocation());
974 DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
978 if (D.hasAttr<AnnotateAttr>())
979 EmitVarAnnotations(&D, emission.Address);
984 /// Determines whether the given __block variable is potentially
985 /// captured by the given expression.
986 static bool isCapturedBy(const VarDecl &var, const Expr *e) {
987 // Skip the most common kinds of expressions that make
988 // hierarchy-walking expensive.
989 e = e->IgnoreParenCasts();
991 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
992 const BlockDecl *block = be->getBlockDecl();
993 for (BlockDecl::capture_const_iterator i = block->capture_begin(),
994 e = block->capture_end(); i != e; ++i) {
995 if (i->getVariable() == &var)
999 // No need to walk into the subexpressions.
1003 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1004 const CompoundStmt *CS = SE->getSubStmt();
1005 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1006 BE = CS->body_end(); BI != BE; ++BI)
1007 if (Expr *E = dyn_cast<Expr>((*BI))) {
1008 if (isCapturedBy(var, E))
1011 else if (DeclStmt *DS = dyn_cast<DeclStmt>((*BI))) {
1012 // special case declarations
1013 for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
1015 if (VarDecl *VD = dyn_cast<VarDecl>((*I))) {
1016 Expr *Init = VD->getInit();
1017 if (Init && isCapturedBy(var, Init))
1023 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1024 // Later, provide code to poke into statements for capture analysis.
1029 for (Stmt::const_child_range children = e->children(); children; ++children)
1030 if (isCapturedBy(var, cast<Expr>(*children)))
1036 /// \brief Determine whether the given initializer is trivial in the sense
1037 /// that it requires no code to be generated.
1038 static bool isTrivialInitializer(const Expr *Init) {
1042 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1043 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1044 if (Constructor->isTrivial() &&
1045 Constructor->isDefaultConstructor() &&
1046 !Construct->requiresZeroInitialization())
1051 void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
1052 assert(emission.Variable && "emission was not valid!");
1054 // If this was emitted as a global constant, we're done.
1055 if (emission.wasEmittedAsGlobal()) return;
1057 const VarDecl &D = *emission.Variable;
1058 QualType type = D.getType();
1060 // If this local has an initializer, emit it now.
1061 const Expr *Init = D.getInit();
1063 // If we are at an unreachable point, we don't need to emit the initializer
1064 // unless it contains a label.
1065 if (!HaveInsertPoint()) {
1066 if (!Init || !ContainsLabel(Init)) return;
1067 EnsureInsertPoint();
1070 // Initialize the structure of a __block variable.
1071 if (emission.IsByRef)
1072 emitByrefStructureInit(emission);
1074 if (isTrivialInitializer(Init))
1077 CharUnits alignment = emission.Alignment;
1079 // Check whether this is a byref variable that's potentially
1080 // captured and moved by its own initializer. If so, we'll need to
1081 // emit the initializer first, then copy into the variable.
1082 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1085 capturedByInit ? emission.Address : emission.getObjectAddress(*this);
1087 llvm::Constant *constant = 0;
1088 if (emission.IsConstantAggregate || D.isConstexpr()) {
1089 assert(!capturedByInit && "constant init contains a capturing block?");
1090 constant = CGM.EmitConstantInit(D, this);
1094 LValue lv = MakeAddrLValue(Loc, type, alignment);
1096 return EmitExprAsInit(Init, &D, lv, capturedByInit);
1099 if (!emission.IsConstantAggregate) {
1100 // For simple scalar/complex initialization, store the value directly.
1101 LValue lv = MakeAddrLValue(Loc, type, alignment);
1103 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1106 // If this is a simple aggregate initialization, we can optimize it
1108 bool isVolatile = type.isVolatileQualified();
1110 llvm::Value *SizeVal =
1111 llvm::ConstantInt::get(IntPtrTy,
1112 getContext().getTypeSizeInChars(type).getQuantity());
1114 llvm::Type *BP = Int8PtrTy;
1115 if (Loc->getType() != BP)
1116 Loc = Builder.CreateBitCast(Loc, BP);
1118 // If the initializer is all or mostly zeros, codegen with memset then do
1119 // a few stores afterward.
1120 if (shouldUseMemSetPlusStoresToInitialize(constant,
1121 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
1122 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1123 alignment.getQuantity(), isVolatile);
1124 // Zero and undef don't require a stores.
1125 if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
1126 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
1127 emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
1130 // Otherwise, create a temporary global with the initializer then
1131 // memcpy from the global to the alloca.
1132 std::string Name = GetStaticDeclName(*this, D, ".");
1133 llvm::GlobalVariable *GV =
1134 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
1135 llvm::GlobalValue::PrivateLinkage,
1137 GV->setAlignment(alignment.getQuantity());
1138 GV->setUnnamedAddr(true);
1140 llvm::Value *SrcPtr = GV;
1141 if (SrcPtr->getType() != BP)
1142 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
1144 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
1149 /// Emit an expression as an initializer for a variable at the given
1150 /// location. The expression is not necessarily the normal
1151 /// initializer for the variable, and the address is not necessarily
1152 /// its normal location.
1154 /// \param init the initializing expression
1155 /// \param var the variable to act as if we're initializing
1156 /// \param loc the address to initialize; its type is a pointer
1157 /// to the LLVM mapping of the variable's type
1158 /// \param alignment the alignment of the address
1159 /// \param capturedByInit true if the variable is a __block variable
1160 /// whose address is potentially changed by the initializer
1161 void CodeGenFunction::EmitExprAsInit(const Expr *init,
1164 bool capturedByInit) {
1165 QualType type = D->getType();
1167 if (type->isReferenceType()) {
1168 RValue rvalue = EmitReferenceBindingToExpr(init);
1170 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1171 EmitStoreThroughLValue(rvalue, lvalue, true);
1174 switch (getEvaluationKind(type)) {
1176 EmitScalarInit(init, D, lvalue, capturedByInit);
1179 ComplexPairTy complex = EmitComplexExpr(init);
1181 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1182 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
1186 if (type->isAtomicType()) {
1187 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1189 // TODO: how can we delay here if D is captured by its initializer?
1190 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
1191 AggValueSlot::IsDestructed,
1192 AggValueSlot::DoesNotNeedGCBarriers,
1193 AggValueSlot::IsNotAliased));
1197 llvm_unreachable("bad evaluation kind");
1200 /// Enter a destroy cleanup for the given local variable.
1201 void CodeGenFunction::emitAutoVarTypeCleanup(
1202 const CodeGenFunction::AutoVarEmission &emission,
1203 QualType::DestructionKind dtorKind) {
1204 assert(dtorKind != QualType::DK_none);
1206 // Note that for __block variables, we want to destroy the
1207 // original stack object, not the possibly forwarded object.
1208 llvm::Value *addr = emission.getObjectAddress(*this);
1210 const VarDecl *var = emission.Variable;
1211 QualType type = var->getType();
1213 CleanupKind cleanupKind = NormalAndEHCleanup;
1214 CodeGenFunction::Destroyer *destroyer = 0;
1217 case QualType::DK_none:
1218 llvm_unreachable("no cleanup for trivially-destructible variable");
1220 case QualType::DK_cxx_destructor:
1221 // If there's an NRVO flag on the emission, we need a different
1223 if (emission.NRVOFlag) {
1224 assert(!type->isArrayType());
1225 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1226 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor,
1232 case QualType::DK_objc_strong_lifetime:
1233 // Suppress cleanups for pseudo-strong variables.
1234 if (var->isARCPseudoStrong()) return;
1236 // Otherwise, consider whether to use an EH cleanup or not.
1237 cleanupKind = getARCCleanupKind();
1239 // Use the imprecise destroyer by default.
1240 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1241 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1244 case QualType::DK_objc_weak_lifetime:
1248 // If we haven't chosen a more specific destroyer, use the default.
1249 if (!destroyer) destroyer = getDestroyer(dtorKind);
1251 // Use an EH cleanup in array destructors iff the destructor itself
1252 // is being pushed as an EH cleanup.
1253 bool useEHCleanup = (cleanupKind & EHCleanup);
1254 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1258 void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
1259 assert(emission.Variable && "emission was not valid!");
1261 // If this was emitted as a global constant, we're done.
1262 if (emission.wasEmittedAsGlobal()) return;
1264 // If we don't have an insertion point, we're done. Sema prevents
1265 // us from jumping into any of these scopes anyway.
1266 if (!HaveInsertPoint()) return;
1268 const VarDecl &D = *emission.Variable;
1270 // Make sure we call @llvm.lifetime.end. This needs to happen
1271 // *last*, so the cleanup needs to be pushed *first*.
1272 if (emission.useLifetimeMarkers()) {
1273 EHStack.pushCleanup<CallLifetimeEnd>(NormalCleanup,
1274 emission.getAllocatedAddress(),
1275 emission.getSizeForLifetimeMarkers());
1278 // Check the type for a cleanup.
1279 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1280 emitAutoVarTypeCleanup(emission, dtorKind);
1282 // In GC mode, honor objc_precise_lifetime.
1283 if (getLangOpts().getGC() != LangOptions::NonGC &&
1284 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1285 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1288 // Handle the cleanup attribute.
1289 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
1290 const FunctionDecl *FD = CA->getFunctionDecl();
1292 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
1293 assert(F && "Could not find function!");
1295 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
1296 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
1299 // If this is a block variable, call _Block_object_destroy
1300 // (on the unforwarded address).
1301 if (emission.IsByRef)
1302 enterByrefCleanup(emission);
1305 CodeGenFunction::Destroyer *
1306 CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1308 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
1309 case QualType::DK_cxx_destructor:
1310 return destroyCXXObject;
1311 case QualType::DK_objc_strong_lifetime:
1312 return destroyARCStrongPrecise;
1313 case QualType::DK_objc_weak_lifetime:
1314 return destroyARCWeak;
1316 llvm_unreachable("Unknown DestructionKind");
1319 /// pushEHDestroy - Push the standard destructor for the given type as
1320 /// an EH-only cleanup.
1321 void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
1322 llvm::Value *addr, QualType type) {
1323 assert(dtorKind && "cannot push destructor for trivial type");
1324 assert(needsEHCleanup(dtorKind));
1326 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1329 /// pushDestroy - Push the standard destructor for the given type as
1330 /// at least a normal cleanup.
1331 void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
1332 llvm::Value *addr, QualType type) {
1333 assert(dtorKind && "cannot push destructor for trivial type");
1335 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1336 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1337 cleanupKind & EHCleanup);
1340 void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *addr,
1341 QualType type, Destroyer *destroyer,
1342 bool useEHCleanupForArray) {
1343 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1344 destroyer, useEHCleanupForArray);
1347 void CodeGenFunction::pushLifetimeExtendedDestroy(
1348 CleanupKind cleanupKind, llvm::Value *addr, QualType type,
1349 Destroyer *destroyer, bool useEHCleanupForArray) {
1350 assert(!isInConditionalBranch() &&
1351 "performing lifetime extension from within conditional");
1353 // Push an EH-only cleanup for the object now.
1354 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1355 // around in case a temporary's destructor throws an exception.
1356 if (cleanupKind & EHCleanup)
1357 EHStack.pushCleanup<DestroyObject>(
1358 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1359 destroyer, useEHCleanupForArray);
1361 // Remember that we need to push a full cleanup for the object at the
1362 // end of the full-expression.
1363 pushCleanupAfterFullExpr<DestroyObject>(
1364 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1367 /// emitDestroy - Immediately perform the destruction of the given
1370 /// \param addr - the address of the object; a type*
1371 /// \param type - the type of the object; if an array type, all
1372 /// objects are destroyed in reverse order
1373 /// \param destroyer - the function to call to destroy individual
1375 /// \param useEHCleanupForArray - whether an EH cleanup should be
1376 /// used when destroying array elements, in case one of the
1377 /// destructions throws an exception
1378 void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type,
1379 Destroyer *destroyer,
1380 bool useEHCleanupForArray) {
1381 const ArrayType *arrayType = getContext().getAsArrayType(type);
1383 return destroyer(*this, addr, type);
1385 llvm::Value *begin = addr;
1386 llvm::Value *length = emitArrayLength(arrayType, type, begin);
1388 // Normally we have to check whether the array is zero-length.
1389 bool checkZeroLength = true;
1391 // But if the array length is constant, we can suppress that.
1392 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1393 // ...and if it's constant zero, we can just skip the entire thing.
1394 if (constLength->isZero()) return;
1395 checkZeroLength = false;
1398 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
1399 emitArrayDestroy(begin, end, type, destroyer,
1400 checkZeroLength, useEHCleanupForArray);
1403 /// emitArrayDestroy - Destroys all the elements of the given array,
1404 /// beginning from last to first. The array cannot be zero-length.
1406 /// \param begin - a type* denoting the first element of the array
1407 /// \param end - a type* denoting one past the end of the array
1408 /// \param type - the element type of the array
1409 /// \param destroyer - the function to call to destroy elements
1410 /// \param useEHCleanup - whether to push an EH cleanup to destroy
1411 /// the remaining elements in case the destruction of a single
1413 void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1416 Destroyer *destroyer,
1417 bool checkZeroLength,
1418 bool useEHCleanup) {
1419 assert(!type->isArrayType());
1421 // The basic structure here is a do-while loop, because we don't
1422 // need to check for the zero-element case.
1423 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1424 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1426 if (checkZeroLength) {
1427 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1428 "arraydestroy.isempty");
1429 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1432 // Enter the loop body, making that address the current address.
1433 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1435 llvm::PHINode *elementPast =
1436 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1437 elementPast->addIncoming(end, entryBB);
1439 // Shift the address back by one element.
1440 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1441 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1442 "arraydestroy.element");
1445 pushRegularPartialArrayCleanup(begin, element, type, destroyer);
1447 // Perform the actual destruction there.
1448 destroyer(*this, element, type);
1453 // Check whether we've reached the end.
1454 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1455 Builder.CreateCondBr(done, doneBB, bodyBB);
1456 elementPast->addIncoming(element, Builder.GetInsertBlock());
1462 /// Perform partial array destruction as if in an EH cleanup. Unlike
1463 /// emitArrayDestroy, the element type here may still be an array type.
1464 static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1465 llvm::Value *begin, llvm::Value *end,
1467 CodeGenFunction::Destroyer *destroyer) {
1468 // If the element type is itself an array, drill down.
1469 unsigned arrayDepth = 0;
1470 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1471 // VLAs don't require a GEP index to walk into.
1472 if (!isa<VariableArrayType>(arrayType))
1474 type = arrayType->getElementType();
1478 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, arrayDepth+1);
1480 SmallVector<llvm::Value*,4> gepIndices(arrayDepth, zero);
1481 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1482 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
1485 // Destroy the array. We don't ever need an EH cleanup because we
1486 // assume that we're in an EH cleanup ourselves, so a throwing
1487 // destructor causes an immediate terminate.
1488 CGF.emitArrayDestroy(begin, end, type, destroyer,
1489 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
1493 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1494 /// array destroy where the end pointer is regularly determined and
1495 /// does not need to be loaded from a local.
1496 class RegularPartialArrayDestroy : public EHScopeStack::Cleanup {
1497 llvm::Value *ArrayBegin;
1498 llvm::Value *ArrayEnd;
1499 QualType ElementType;
1500 CodeGenFunction::Destroyer *Destroyer;
1502 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
1503 QualType elementType,
1504 CodeGenFunction::Destroyer *destroyer)
1505 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
1506 ElementType(elementType), Destroyer(destroyer) {}
1508 void Emit(CodeGenFunction &CGF, Flags flags) {
1509 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
1510 ElementType, Destroyer);
1514 /// IrregularPartialArrayDestroy - a cleanup which performs a
1515 /// partial array destroy where the end pointer is irregularly
1516 /// determined and must be loaded from a local.
1517 class IrregularPartialArrayDestroy : public EHScopeStack::Cleanup {
1518 llvm::Value *ArrayBegin;
1519 llvm::Value *ArrayEndPointer;
1520 QualType ElementType;
1521 CodeGenFunction::Destroyer *Destroyer;
1523 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
1524 llvm::Value *arrayEndPointer,
1525 QualType elementType,
1526 CodeGenFunction::Destroyer *destroyer)
1527 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
1528 ElementType(elementType), Destroyer(destroyer) {}
1530 void Emit(CodeGenFunction &CGF, Flags flags) {
1531 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
1532 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
1533 ElementType, Destroyer);
1538 /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
1539 /// already-constructed elements of the given array. The cleanup
1540 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1542 /// \param elementType - the immediate element type of the array;
1543 /// possibly still an array type
1544 void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
1545 llvm::Value *arrayEndPointer,
1546 QualType elementType,
1547 Destroyer *destroyer) {
1548 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1549 arrayBegin, arrayEndPointer,
1550 elementType, destroyer);
1553 /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1554 /// already-constructed elements of the given array. The cleanup
1555 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1557 /// \param elementType - the immediate element type of the array;
1558 /// possibly still an array type
1559 void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1560 llvm::Value *arrayEnd,
1561 QualType elementType,
1562 Destroyer *destroyer) {
1563 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
1564 arrayBegin, arrayEnd,
1565 elementType, destroyer);
1568 /// Lazily declare the @llvm.lifetime.start intrinsic.
1569 llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
1570 if (LifetimeStartFn) return LifetimeStartFn;
1571 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1572 llvm::Intrinsic::lifetime_start);
1573 return LifetimeStartFn;
1576 /// Lazily declare the @llvm.lifetime.end intrinsic.
1577 llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
1578 if (LifetimeEndFn) return LifetimeEndFn;
1579 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1580 llvm::Intrinsic::lifetime_end);
1581 return LifetimeEndFn;
1585 /// A cleanup to perform a release of an object at the end of a
1586 /// function. This is used to balance out the incoming +1 of a
1587 /// ns_consumed argument when we can't reasonably do that just by
1588 /// not doing the initial retain for a __block argument.
1589 struct ConsumeARCParameter : EHScopeStack::Cleanup {
1590 ConsumeARCParameter(llvm::Value *param,
1591 ARCPreciseLifetime_t precise)
1592 : Param(param), Precise(precise) {}
1595 ARCPreciseLifetime_t Precise;
1597 void Emit(CodeGenFunction &CGF, Flags flags) {
1598 CGF.EmitARCRelease(Param, Precise);
1603 /// Emit an alloca (or GlobalValue depending on target)
1604 /// for the specified parameter and set up LocalDeclMap.
1605 void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
1607 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
1608 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
1609 "Invalid argument to EmitParmDecl");
1611 Arg->setName(D.getName());
1613 QualType Ty = D.getType();
1615 // Use better IR generation for certain implicit parameters.
1616 if (isa<ImplicitParamDecl>(D)) {
1617 // The only implicit argument a block has is its literal.
1619 LocalDeclMap[&D] = Arg;
1620 llvm::Value *LocalAddr = 0;
1621 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1622 // Allocate a stack slot to let the debug info survive the RA.
1623 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1624 D.getName() + ".addr");
1625 Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity());
1626 LValue lv = MakeAddrLValue(Alloc, Ty, getContext().getDeclAlign(&D));
1627 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
1628 LocalAddr = Builder.CreateLoad(Alloc);
1631 if (CGDebugInfo *DI = getDebugInfo()) {
1632 if (CGM.getCodeGenOpts().getDebugInfo()
1633 >= CodeGenOptions::LimitedDebugInfo) {
1634 DI->setLocation(D.getLocation());
1635 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, LocalAddr, Builder);
1643 llvm::Value *DeclPtr;
1644 bool HasNonScalarEvalKind = !CodeGenFunction::hasScalarEvaluationKind(Ty);
1645 // If this is an aggregate or variable sized value, reuse the input pointer.
1646 if (HasNonScalarEvalKind || !Ty->isConstantSizeType()) {
1648 // Push a destructor cleanup for this parameter if the ABI requires it.
1649 if (HasNonScalarEvalKind &&
1650 getTarget().getCXXABI().isArgumentDestroyedByCallee()) {
1651 if (const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl()) {
1652 if (RD->hasNonTrivialDestructor())
1653 pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
1657 // Otherwise, create a temporary to hold the value.
1658 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1659 D.getName() + ".addr");
1660 CharUnits Align = getContext().getDeclAlign(&D);
1661 Alloc->setAlignment(Align.getQuantity());
1664 bool doStore = true;
1666 Qualifiers qs = Ty.getQualifiers();
1667 LValue lv = MakeAddrLValue(DeclPtr, Ty, Align);
1668 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1669 // We honor __attribute__((ns_consumed)) for types with lifetime.
1670 // For __strong, it's handled by just skipping the initial retain;
1671 // otherwise we have to balance out the initial +1 with an extra
1672 // cleanup to do the release at the end of the function.
1673 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1675 // 'self' is always formally __strong, but if this is not an
1676 // init method then we don't want to retain it.
1677 if (D.isARCPseudoStrong()) {
1678 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1679 assert(&D == method->getSelfDecl());
1680 assert(lt == Qualifiers::OCL_Strong);
1681 assert(qs.hasConst());
1682 assert(method->getMethodFamily() != OMF_init);
1684 lt = Qualifiers::OCL_ExplicitNone;
1687 if (lt == Qualifiers::OCL_Strong) {
1689 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1690 // use objc_storeStrong(&dest, value) for retaining the
1691 // object. But first, store a null into 'dest' because
1692 // objc_storeStrong attempts to release its old value.
1693 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
1694 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
1695 EmitARCStoreStrongCall(lv.getAddress(), Arg, true);
1699 // Don't use objc_retainBlock for block pointers, because we
1700 // don't want to Block_copy something just because we got it
1702 Arg = EmitARCRetainNonBlock(Arg);
1705 // Push the cleanup for a consumed parameter.
1707 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1708 ? ARCPreciseLifetime : ARCImpreciseLifetime);
1709 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg,
1713 if (lt == Qualifiers::OCL_Weak) {
1714 EmitARCInitWeak(DeclPtr, Arg);
1715 doStore = false; // The weak init is a store, no need to do two.
1719 // Enter the cleanup scope.
1720 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1723 // Store the initial value into the alloca.
1725 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
1728 llvm::Value *&DMEntry = LocalDeclMap[&D];
1729 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
1732 // Emit debug info for param declaration.
1733 if (CGDebugInfo *DI = getDebugInfo()) {
1734 if (CGM.getCodeGenOpts().getDebugInfo()
1735 >= CodeGenOptions::LimitedDebugInfo) {
1736 DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
1740 if (D.hasAttr<AnnotateAttr>())
1741 EmitVarAnnotations(&D, DeclPtr);