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