blob: 46de0e50b356be657d89881eb26660dff755d2d5 [file] [log] [blame]
Chris Lattner84915fa2007-06-02 04:16:21 +00001//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner84915fa2007-06-02 04:16:21 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Decl nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CGDebugInfo.h"
Peter Collingbourne2dbb7082011-09-19 21:14:35 +000016#include "CGOpenCLRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "CodeGenModule.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000018#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000019#include "clang/AST/CharUnits.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000020#include "clang/AST/Decl.h"
Anders Carlsson4c03d982008-08-25 01:38:19 +000021#include "clang/AST/DeclObjC.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000022#include "clang/Basic/SourceManager.h"
Chris Lattnerb781dc792008-05-08 05:58:21 +000023#include "clang/Basic/TargetInfo.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000024#include "clang/CodeGen/CGFunctionInfo.h"
Chandler Carruth85098242010-06-15 23:19:56 +000025#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/GlobalVariable.h"
28#include "llvm/IR/Intrinsics.h"
29#include "llvm/IR/Type.h"
Chris Lattner84915fa2007-06-02 04:16:21 +000030using namespace clang;
31using namespace CodeGen;
32
33
Chris Lattner1ad38f82007-06-09 01:20:56 +000034void CodeGenFunction::EmitDecl(const Decl &D) {
Chris Lattner1ad38f82007-06-09 01:20:56 +000035 switch (D.getKind()) {
Douglas Gregor19043f02010-04-23 02:02:43 +000036 case Decl::TranslationUnit:
37 case Decl::Namespace:
38 case Decl::UnresolvedUsingTypename:
39 case Decl::ClassTemplateSpecialization:
40 case Decl::ClassTemplatePartialSpecialization:
Larisse Voufo39a1e502013-08-06 01:03:05 +000041 case Decl::VarTemplateSpecialization:
42 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor19043f02010-04-23 02:02:43 +000043 case Decl::TemplateTypeParm:
44 case Decl::UnresolvedUsingValue:
Alexis Hunted053252010-05-30 07:21:58 +000045 case Decl::NonTypeTemplateParm:
Douglas Gregor19043f02010-04-23 02:02:43 +000046 case Decl::CXXMethod:
47 case Decl::CXXConstructor:
48 case Decl::CXXDestructor:
49 case Decl::CXXConversion:
50 case Decl::Field:
John McCall5e77d762013-04-16 07:28:30 +000051 case Decl::MSProperty:
Francois Pichetdf946c32010-11-21 06:49:41 +000052 case Decl::IndirectField:
Douglas Gregor19043f02010-04-23 02:02:43 +000053 case Decl::ObjCIvar:
Eric Christopher31ab1302011-08-23 22:38:00 +000054 case Decl::ObjCAtDefsField:
Chris Lattnerba9dddb2007-10-08 21:37:32 +000055 case Decl::ParmVar:
Douglas Gregor19043f02010-04-23 02:02:43 +000056 case Decl::ImplicitParam:
57 case Decl::ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +000058 case Decl::VarTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000059 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +000060 case Decl::TypeAliasTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000061 case Decl::TemplateTemplateParm:
62 case Decl::ObjCMethod:
63 case Decl::ObjCCategory:
64 case Decl::ObjCProtocol:
65 case Decl::ObjCInterface:
66 case Decl::ObjCCategoryImpl:
67 case Decl::ObjCImplementation:
68 case Decl::ObjCProperty:
69 case Decl::ObjCCompatibleAlias:
Abramo Bagnarad7340582010-06-05 05:09:32 +000070 case Decl::AccessSpec:
Douglas Gregor19043f02010-04-23 02:02:43 +000071 case Decl::LinkageSpec:
72 case Decl::ObjCPropertyImpl:
Douglas Gregor19043f02010-04-23 02:02:43 +000073 case Decl::FileScopeAsm:
74 case Decl::Friend:
75 case Decl::FriendTemplate:
76 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +000077 case Decl::Captured:
Francois Pichet00c7e6c2011-08-14 03:52:19 +000078 case Decl::ClassScopeFunctionSpecialization:
David Blaikiebd483762013-05-20 04:58:53 +000079 case Decl::UsingShadow:
David Blaikie83d382b2011-09-23 05:06:16 +000080 llvm_unreachable("Declaration should not be in declstmts!");
Chris Lattner84915fa2007-06-02 04:16:21 +000081 case Decl::Function: // void X();
Argyrios Kyrtzidis88e1b972008-10-15 00:42:39 +000082 case Decl::Record: // struct/union/class X;
Chris Lattner84915fa2007-06-02 04:16:21 +000083 case Decl::Enum: // enum X;
Mike Stump11289f42009-09-09 15:08:12 +000084 case Decl::EnumConstant: // enum ? { X = ? }
Argyrios Kyrtzidis88e1b972008-10-15 00:42:39 +000085 case Decl::CXXRecord: // struct/union/class X; [C++]
Anders Carlssonce2cd012009-12-03 17:26:31 +000086 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
Chris Lattner43e7f312011-02-18 02:08:43 +000087 case Decl::Label: // __label__ x;
Douglas Gregorba345522011-12-02 23:23:56 +000088 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +000089 case Decl::OMPThreadPrivate:
Michael Han84324352013-02-22 17:15:32 +000090 case Decl::Empty:
Chris Lattner84915fa2007-06-02 04:16:21 +000091 // None of these decls require codegen support.
92 return;
David Blaikieb7d1e1f2013-02-02 00:39:32 +000093
David Blaikief121b932013-05-20 22:50:41 +000094 case Decl::NamespaceAlias:
95 if (CGDebugInfo *DI = getDebugInfo())
96 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
97 return;
David Blaikiebd483762013-05-20 04:58:53 +000098 case Decl::Using: // using X; [C++]
99 if (CGDebugInfo *DI = getDebugInfo())
100 DI->EmitUsingDecl(cast<UsingDecl>(D));
101 return;
David Blaikie9f88fe82013-04-22 06:13:21 +0000102 case Decl::UsingDirective: // using namespace X; [C++]
103 if (CGDebugInfo *DI = getDebugInfo())
104 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
105 return;
Daniel Dunbara7998072008-08-29 17:28:43 +0000106 case Decl::Var: {
107 const VarDecl &VD = cast<VarDecl>(D);
John McCall1c9c3fd2010-10-15 04:57:14 +0000108 assert(VD.isLocalVarDecl() &&
Daniel Dunbara7998072008-08-29 17:28:43 +0000109 "Should not see file-scope variables inside a function!");
John McCall1c9c3fd2010-10-15 04:57:14 +0000110 return EmitVarDecl(VD);
Chris Lattner84915fa2007-06-02 04:16:21 +0000111 }
Mike Stump11289f42009-09-09 15:08:12 +0000112
Richard Smithdda56e42011-04-15 14:24:37 +0000113 case Decl::Typedef: // typedef int X;
114 case Decl::TypeAlias: { // using X = int; [C++0x]
115 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000116 QualType Ty = TD.getUnderlyingType();
Mike Stump11289f42009-09-09 15:08:12 +0000117
Anders Carlsson5d985f52008-12-20 21:51:53 +0000118 if (Ty->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000119 EmitVariablyModifiedType(Ty);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000120 }
Daniel Dunbara7998072008-08-29 17:28:43 +0000121 }
Chris Lattner84915fa2007-06-02 04:16:21 +0000122}
Chris Lattner03df1222007-06-02 04:53:11 +0000123
John McCall1c9c3fd2010-10-15 04:57:14 +0000124/// EmitVarDecl - This method handles emission of any variable declaration
Chris Lattner03df1222007-06-02 04:53:11 +0000125/// inside a function, including static vars etc.
John McCall1c9c3fd2010-10-15 04:57:14 +0000126void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000127 if (D.isStaticLocal()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000128 llvm::GlobalValue::LinkageTypes Linkage =
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000129 llvm::GlobalValue::InternalLinkage;
130
Eli Friedmanc48d31c2013-07-01 20:53:07 +0000131 // If the variable is externally visible, it must have weak linkage so it
132 // can be uniqued.
Rafael Espindolaa4184182013-06-17 20:04:51 +0000133 if (D.isExternallyVisible()) {
Eli Friedmanc48d31c2013-07-01 20:53:07 +0000134 Linkage = llvm::GlobalValue::LinkOnceODRLinkage;
Eli Friedman7e346a82013-07-01 20:22:57 +0000135
136 // FIXME: We need to force the emission/use of a guard variable for
137 // some variables even if we can constant-evaluate them because
138 // we can't guarantee every translation unit will constant-evaluate them.
Eli Friedmand4b6e7a92013-06-13 21:50:44 +0000139 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000140
John McCall1c9c3fd2010-10-15 04:57:14 +0000141 return EmitStaticVarDecl(D, Linkage);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000142 }
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000143
144 if (D.hasExternalStorage())
Lauro Ramos Venanciobada8d42008-02-16 22:30:38 +0000145 // Don't emit it now, allow it to be emitted lazily on its first use.
146 return;
Daniel Dunbar0ca16602009-04-14 02:25:56 +0000147
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000148 if (D.getStorageClass() == SC_OpenCLWorkGroupLocal)
149 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
150
151 assert(D.hasLocalStorage());
152 return EmitAutoVarDecl(D);
Chris Lattner03df1222007-06-02 04:53:11 +0000153}
154
Chris Lattnere99c1102009-12-05 08:22:11 +0000155static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D,
156 const char *Separator) {
157 CodeGenModule &CGM = CGF.CGM;
Richard Smith9c6890a2012-11-01 22:30:59 +0000158 if (CGF.getLangOpts().CPlusPlus) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000159 StringRef Name = CGM.getMangledName(&D);
Anders Carlssonea836bc2010-06-22 16:16:50 +0000160 return Name.str();
John McCall7ec50432010-03-19 23:29:14 +0000161 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000162
Chris Lattnere99c1102009-12-05 08:22:11 +0000163 std::string ContextName;
Fariborz Jahanian3a4ea9a2010-11-30 23:07:14 +0000164 if (!CGF.CurFuncDecl) {
165 // Better be in a block declared in global scope.
166 const NamedDecl *ND = cast<NamedDecl>(&D);
167 const DeclContext *DC = ND->getDeclContext();
168 if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
169 MangleBuffer Name;
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000170 CGM.getBlockMangledName(GlobalDecl(), Name, BD);
Fariborz Jahanian3a4ea9a2010-11-30 23:07:14 +0000171 ContextName = Name.getString();
172 }
173 else
David Blaikie83d382b2011-09-23 05:06:16 +0000174 llvm_unreachable("Unknown context for block static var decl");
Fariborz Jahanian3a4ea9a2010-11-30 23:07:14 +0000175 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000176 StringRef Name = CGM.getMangledName(FD);
Anders Carlssonea836bc2010-06-22 16:16:50 +0000177 ContextName = Name.str();
John McCall7ec50432010-03-19 23:29:14 +0000178 } else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
Chris Lattnere99c1102009-12-05 08:22:11 +0000179 ContextName = CGF.CurFn->getName();
180 else
David Blaikie83d382b2011-09-23 05:06:16 +0000181 llvm_unreachable("Unknown context for static var decl");
Eric Christopher31ab1302011-08-23 22:38:00 +0000182
Chris Lattnere99c1102009-12-05 08:22:11 +0000183 return ContextName + Separator + D.getNameAsString();
184}
185
Chandler Carruth84537952012-03-30 19:44:53 +0000186llvm::GlobalVariable *
John McCall1c9c3fd2010-10-15 04:57:14 +0000187CodeGenFunction::CreateStaticVarDecl(const VarDecl &D,
188 const char *Separator,
189 llvm::GlobalValue::LinkageTypes Linkage) {
Chris Lattnerfc4379f2008-04-06 23:10:54 +0000190 QualType Ty = D.getType();
Eli Friedmana682d392008-02-15 12:20:59 +0000191 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begemanfaae0812008-04-19 04:17:09 +0000192
Benjamin Kramerddbb2b82011-11-20 21:05:04 +0000193 // Use the label if the variable is renamed with the asm-label extension.
194 std::string Name;
Benjamin Kramer5642e192011-11-21 15:47:23 +0000195 if (D.hasAttr<AsmLabelAttr>())
196 Name = CGM.getMangledName(&D);
197 else
Benjamin Kramerddbb2b82011-11-20 21:05:04 +0000198 Name = GetStaticDeclName(*this, D, Separator);
Nate Begemanfaae0812008-04-19 04:17:09 +0000199
Chris Lattner2192fe52011-07-18 04:24:23 +0000200 llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
Peter Collingbourneee0502d2012-08-28 20:37:10 +0000201 unsigned AddrSpace =
202 CGM.GetGlobalVarAddressSpace(&D, CGM.getContext().getTargetAddressSpace(Ty));
Anders Carlssone33eed52009-09-26 18:16:06 +0000203 llvm::GlobalVariable *GV =
204 new llvm::GlobalVariable(CGM.getModule(), LTy,
205 Ty.isConstant(getContext()), Linkage,
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000206 CGM.EmitNullConstant(D.getType()), Name, 0,
207 llvm::GlobalVariable::NotThreadLocal,
Peter Collingbourneee0502d2012-08-28 20:37:10 +0000208 AddrSpace);
Ken Dyck160146e2010-01-27 17:10:57 +0000209 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Eli Friedman40a4bec2013-06-17 21:51:45 +0000210 CGM.setGlobalVisibility(GV, &D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000211
Richard Smithfd3834f2013-04-13 02:43:54 +0000212 if (D.getTLSKind())
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000213 CGM.setTLSMode(GV, D);
214
Anders Carlssone33eed52009-09-26 18:16:06 +0000215 return GV;
Daniel Dunbar22a87f92009-02-25 19:24:29 +0000216}
217
Richard Smith6331c402012-02-13 22:16:19 +0000218/// hasNontrivialDestruction - Determine whether a type's destruction is
219/// non-trivial. If so, and the variable uses static initialization, we must
220/// register its destructor to run on exit.
221static bool hasNontrivialDestruction(QualType T) {
222 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
223 return RD && !RD->hasTrivialDestructor();
224}
225
Chandler Carruth84537952012-03-30 19:44:53 +0000226/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
227/// global variable that has already been created for it. If the initializer
228/// has a different type than GV does, this may free GV and return a different
229/// one. Otherwise it just returns GV.
230llvm::GlobalVariable *
John McCall1c9c3fd2010-10-15 04:57:14 +0000231CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
Chandler Carruth84537952012-03-30 19:44:53 +0000232 llvm::GlobalVariable *GV) {
233 llvm::Constant *Init = CGM.EmitConstantInit(D, this);
John McCall70013b62010-07-15 23:40:35 +0000234
Chris Lattnere99c1102009-12-05 08:22:11 +0000235 // If constant emission failed, then this should be a C++ static
236 // initializer.
Chandler Carruth84537952012-03-30 19:44:53 +0000237 if (!Init) {
Richard Smith9c6890a2012-11-01 22:30:59 +0000238 if (!getLangOpts().CPlusPlus)
Chris Lattnere99c1102009-12-05 08:22:11 +0000239 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
John McCall68ff0372010-09-08 01:44:27 +0000240 else if (Builder.GetInsertBlock()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000241 // Since we have a static initializer, this global variable can't
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000242 // be constant.
Chandler Carruth84537952012-03-30 19:44:53 +0000243 GV->setConstant(false);
John McCall68ff0372010-09-08 01:44:27 +0000244
Chandler Carruth84537952012-03-30 19:44:53 +0000245 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000246 }
Chandler Carruth84537952012-03-30 19:44:53 +0000247 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000248 }
John McCall70013b62010-07-15 23:40:35 +0000249
Chris Lattnere99c1102009-12-05 08:22:11 +0000250 // The initializer may differ in type from the global. Rewrite
251 // the global to match the initializer. (We have to do this
252 // because some types, like unions, can't be completely represented
253 // in the LLVM type system.)
Chandler Carruth84537952012-03-30 19:44:53 +0000254 if (GV->getType()->getElementType() != Init->getType()) {
255 llvm::GlobalVariable *OldGV = GV;
256
257 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
258 OldGV->isConstant(),
259 OldGV->getLinkage(), Init, "",
260 /*InsertBefore*/ OldGV,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +0000261 OldGV->getThreadLocalMode(),
Chandler Carruth84537952012-03-30 19:44:53 +0000262 CGM.getContext().getTargetAddressSpace(D.getType()));
263 GV->setVisibility(OldGV->getVisibility());
Eric Christopher31ab1302011-08-23 22:38:00 +0000264
Chris Lattnere99c1102009-12-05 08:22:11 +0000265 // Steal the name of the old global
Chandler Carruth84537952012-03-30 19:44:53 +0000266 GV->takeName(OldGV);
Eric Christopher31ab1302011-08-23 22:38:00 +0000267
Chris Lattnere99c1102009-12-05 08:22:11 +0000268 // Replace all uses of the old global with the new global
Chandler Carruth84537952012-03-30 19:44:53 +0000269 llvm::Constant *NewPtrForOldDecl =
270 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
271 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eric Christopher31ab1302011-08-23 22:38:00 +0000272
Chris Lattnere99c1102009-12-05 08:22:11 +0000273 // Erase the old global, since it is no longer used.
Chandler Carruth84537952012-03-30 19:44:53 +0000274 OldGV->eraseFromParent();
Chris Lattnere99c1102009-12-05 08:22:11 +0000275 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000276
Chandler Carruth84537952012-03-30 19:44:53 +0000277 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
278 GV->setInitializer(Init);
Richard Smith6331c402012-02-13 22:16:19 +0000279
280 if (hasNontrivialDestruction(D.getType())) {
281 // We have a constant initializer, but a nontrivial destructor. We still
282 // need to perform a guarded "initialization" in order to register the
Richard Smithe070fd22012-02-17 06:48:11 +0000283 // destructor.
Chandler Carruth84537952012-03-30 19:44:53 +0000284 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
Richard Smith6331c402012-02-13 22:16:19 +0000285 }
286
Chandler Carruth84537952012-03-30 19:44:53 +0000287 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000288}
289
John McCall1c9c3fd2010-10-15 04:57:14 +0000290void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000291 llvm::GlobalValue::LinkageTypes Linkage) {
Chandler Carruth84537952012-03-30 19:44:53 +0000292 llvm::Value *&DMEntry = LocalDeclMap[&D];
293 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
Mike Stump11289f42009-09-09 15:08:12 +0000294
John McCallb88a5662012-03-30 21:00:39 +0000295 // Check to see if we already have a global variable for this
296 // declaration. This can happen when double-emitting function
297 // bodies, e.g. with complete and base constructors.
298 llvm::Constant *addr =
299 CGM.getStaticLocalDeclAddress(&D);
300
301 llvm::GlobalVariable *var;
302 if (addr) {
303 var = cast<llvm::GlobalVariable>(addr->stripPointerCasts());
304 } else {
305 addr = var = CreateStaticVarDecl(D, ".", Linkage);
306 }
Daniel Dunbara374e602009-02-25 19:45:19 +0000307
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000308 // Store into LocalDeclMap before generating initializer to handle
309 // circular references.
John McCallb88a5662012-03-30 21:00:39 +0000310 DMEntry = addr;
311 CGM.setStaticLocalDeclAddress(&D, addr);
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000312
John McCall4a39ab82010-05-04 20:45:42 +0000313 // We can't have a VLA here, but we can have a pointer to a VLA,
314 // even though that doesn't really make any sense.
Eli Friedmanbc633be2009-04-20 03:54:15 +0000315 // Make sure to evaluate VLA bounds now so that we have them for later.
316 if (D.getType()->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000317 EmitVariablyModifiedType(D.getType());
Eric Christopher31ab1302011-08-23 22:38:00 +0000318
John McCallb88a5662012-03-30 21:00:39 +0000319 // Save the type in case adding the initializer forces a type change.
320 llvm::Type *expectedType = addr->getType();
Eli Friedmanbc633be2009-04-20 03:54:15 +0000321
Chris Lattnere99c1102009-12-05 08:22:11 +0000322 // If this value has an initializer, emit it.
323 if (D.getInit())
John McCallb88a5662012-03-30 21:00:39 +0000324 var = AddInitializerToStaticVarDecl(D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000325
John McCallb88a5662012-03-30 21:00:39 +0000326 var->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Chris Lattner4d941092010-03-10 23:59:59 +0000327
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000328 if (D.hasAttr<AnnotateAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000329 CGM.AddGlobalAnnotations(&D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000330
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000331 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000332 var->setSection(SA->getName());
Mike Stump11289f42009-09-09 15:08:12 +0000333
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000334 if (D.hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +0000335 CGM.addUsedGlobal(var);
Daniel Dunbar128a1382009-02-13 22:08:43 +0000336
Chandler Carruth84537952012-03-30 19:44:53 +0000337 // We may have to cast the constant because of the initializer
338 // mismatch above.
339 //
340 // FIXME: It is really dangerous to store this in the map; if anyone
341 // RAUW's the GV uses of this constant will be invalid.
John McCallb88a5662012-03-30 21:00:39 +0000342 llvm::Constant *castedAddr = llvm::ConstantExpr::getBitCast(var, expectedType);
343 DMEntry = castedAddr;
344 CGM.setStaticLocalDeclAddress(&D, castedAddr);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000345
346 // Emit global variable debug descriptor for static vars.
Anders Carlsson63784f42009-02-13 08:11:52 +0000347 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov74a38682012-05-04 07:39:27 +0000348 if (DI &&
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000349 CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
Daniel Dunbarb9fd9022008-10-17 16:15:48 +0000350 DI->setLocation(D.getLocation());
John McCallb88a5662012-03-30 21:00:39 +0000351 DI->EmitGlobalVariable(var, &D);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000352 }
Anders Carlssonf94cd1f2007-10-17 00:52:43 +0000353}
Mike Stump11289f42009-09-09 15:08:12 +0000354
John McCall2b7fc382010-07-13 20:32:21 +0000355namespace {
John McCall82fe67b2011-07-09 01:37:26 +0000356 struct DestroyObject : EHScopeStack::Cleanup {
357 DestroyObject(llvm::Value *addr, QualType type,
John McCall178360e2011-07-11 08:38:19 +0000358 CodeGenFunction::Destroyer *destroyer,
359 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +0000360 : addr(addr), type(type), destroyer(destroyer),
John McCall178360e2011-07-11 08:38:19 +0000361 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall2b7fc382010-07-13 20:32:21 +0000362
John McCall82fe67b2011-07-09 01:37:26 +0000363 llvm::Value *addr;
364 QualType type;
Peter Collingbourne1425b452012-01-26 03:33:36 +0000365 CodeGenFunction::Destroyer *destroyer;
John McCall178360e2011-07-11 08:38:19 +0000366 bool useEHCleanupForArray;
John McCall2b7fc382010-07-13 20:32:21 +0000367
John McCall30317fd2011-07-12 20:27:29 +0000368 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall178360e2011-07-11 08:38:19 +0000369 // Don't use an EH cleanup recursively from an EH cleanup.
John McCall30317fd2011-07-12 20:27:29 +0000370 bool useEHCleanupForArray =
371 flags.isForNormalCleanup() && this->useEHCleanupForArray;
John McCall178360e2011-07-11 08:38:19 +0000372
373 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
John McCall2b7fc382010-07-13 20:32:21 +0000374 }
375 };
376
John McCall82fe67b2011-07-09 01:37:26 +0000377 struct DestroyNRVOVariable : EHScopeStack::Cleanup {
378 DestroyNRVOVariable(llvm::Value *addr,
379 const CXXDestructorDecl *Dtor,
380 llvm::Value *NRVOFlag)
381 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
John McCall2b7fc382010-07-13 20:32:21 +0000382
383 const CXXDestructorDecl *Dtor;
384 llvm::Value *NRVOFlag;
385 llvm::Value *Loc;
386
John McCall30317fd2011-07-12 20:27:29 +0000387 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall2b7fc382010-07-13 20:32:21 +0000388 // Along the exceptions path we always execute the dtor.
John McCall30317fd2011-07-12 20:27:29 +0000389 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
John McCall2b7fc382010-07-13 20:32:21 +0000390
391 llvm::BasicBlock *SkipDtorBB = 0;
392 if (NRVO) {
393 // If we exited via NRVO, we skip the destructor call.
394 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
395 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
396 llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
397 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
398 CGF.EmitBlock(RunDtorBB);
399 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000400
John McCall2b7fc382010-07-13 20:32:21 +0000401 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +0000402 /*ForVirtualBase=*/false,
403 /*Delegating=*/false,
404 Loc);
John McCall2b7fc382010-07-13 20:32:21 +0000405
406 if (NRVO) CGF.EmitBlock(SkipDtorBB);
407 }
408 };
John McCall2b7fc382010-07-13 20:32:21 +0000409
John McCallcda666c2010-07-21 07:22:38 +0000410 struct CallStackRestore : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000411 llvm::Value *Stack;
412 CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
John McCall30317fd2011-07-12 20:27:29 +0000413 void Emit(CodeGenFunction &CGF, Flags flags) {
Benjamin Kramer76399eb2011-09-27 21:06:10 +0000414 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
John McCalla464ff92010-07-21 06:13:08 +0000415 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
416 CGF.Builder.CreateCall(F, V);
417 }
418 };
419
John McCall1bd25562011-06-24 23:21:27 +0000420 struct ExtendGCLifetime : EHScopeStack::Cleanup {
421 const VarDecl &Var;
422 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
423
John McCall30317fd2011-07-12 20:27:29 +0000424 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall1bd25562011-06-24 23:21:27 +0000425 // Compute the address of the local variable, in case it's a
426 // byref or something.
John McCall113bee02012-03-10 09:33:50 +0000427 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
428 Var.getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +0000429 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
430 SourceLocation());
John McCall1bd25562011-06-24 23:21:27 +0000431 CGF.EmitExtendGCLifetime(value);
432 }
433 };
434
John McCallcda666c2010-07-21 07:22:38 +0000435 struct CallCleanupFunction : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000436 llvm::Constant *CleanupFn;
437 const CGFunctionInfo &FnInfo;
John McCalla464ff92010-07-21 06:13:08 +0000438 const VarDecl &Var;
Eric Christopher31ab1302011-08-23 22:38:00 +0000439
John McCalla464ff92010-07-21 06:13:08 +0000440 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCallc533cb72011-02-22 06:44:22 +0000441 const VarDecl *Var)
442 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalla464ff92010-07-21 06:13:08 +0000443
John McCall30317fd2011-07-12 20:27:29 +0000444 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall113bee02012-03-10 09:33:50 +0000445 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
446 Var.getType(), VK_LValue, SourceLocation());
John McCallc533cb72011-02-22 06:44:22 +0000447 // Compute the address of the local variable, in case it's a byref
448 // or something.
449 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
450
John McCalla464ff92010-07-21 06:13:08 +0000451 // In some cases, the type of the function argument will be different from
452 // the type of the pointer. An example of this is
453 // void f(void* arg);
454 // __attribute__((cleanup(f))) void *g;
455 //
456 // To fix this we insert a bitcast here.
457 QualType ArgTy = FnInfo.arg_begin()->type;
458 llvm::Value *Arg =
459 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
460
461 CallArgList Args;
Eli Friedman43dca6a2011-05-02 17:57:46 +0000462 Args.add(RValue::get(Arg),
463 CGF.getContext().getPointerType(Var.getType()));
John McCalla464ff92010-07-21 06:13:08 +0000464 CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
465 }
466 };
Nadav Rotem1da30942013-03-23 06:43:35 +0000467
468 /// A cleanup to call @llvm.lifetime.end.
469 class CallLifetimeEnd : public EHScopeStack::Cleanup {
470 llvm::Value *Addr;
471 llvm::Value *Size;
472 public:
473 CallLifetimeEnd(llvm::Value *addr, llvm::Value *size)
474 : Addr(addr), Size(size) {}
475
476 void Emit(CodeGenFunction &CGF, Flags flags) {
477 llvm::Value *castAddr = CGF.Builder.CreateBitCast(Addr, CGF.Int8PtrTy);
478 CGF.Builder.CreateCall2(CGF.CGM.getLLVMLifetimeEndFn(),
479 Size, castAddr)
480 ->setDoesNotThrow();
481 }
482 };
John McCalla464ff92010-07-21 06:13:08 +0000483}
484
John McCall31168b02011-06-15 23:02:42 +0000485/// EmitAutoVarWithLifetime - Does the setup required for an automatic
486/// variable with lifetime.
487static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
488 llvm::Value *addr,
489 Qualifiers::ObjCLifetime lifetime) {
490 switch (lifetime) {
491 case Qualifiers::OCL_None:
492 llvm_unreachable("present but none");
493
494 case Qualifiers::OCL_ExplicitNone:
495 // nothing to do
496 break;
497
498 case Qualifiers::OCL_Strong: {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000499 CodeGenFunction::Destroyer *destroyer =
John McCall4bd0fb12011-07-12 16:41:08 +0000500 (var.hasAttr<ObjCPreciseLifetimeAttr>()
501 ? CodeGenFunction::destroyARCStrongPrecise
502 : CodeGenFunction::destroyARCStrongImprecise);
503
504 CleanupKind cleanupKind = CGF.getARCCleanupKind();
505 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
506 cleanupKind & EHCleanup);
John McCall31168b02011-06-15 23:02:42 +0000507 break;
508 }
509 case Qualifiers::OCL_Autoreleasing:
510 // nothing to do
511 break;
Eric Christopher31ab1302011-08-23 22:38:00 +0000512
John McCall31168b02011-06-15 23:02:42 +0000513 case Qualifiers::OCL_Weak:
514 // __weak objects always get EH cleanups; otherwise, exceptions
515 // could cause really nasty crashes instead of mere leaks.
John McCall4bd0fb12011-07-12 16:41:08 +0000516 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
517 CodeGenFunction::destroyARCWeak,
518 /*useEHCleanup*/ true);
John McCall31168b02011-06-15 23:02:42 +0000519 break;
520 }
521}
522
523static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
524 if (const Expr *e = dyn_cast<Expr>(s)) {
525 // Skip the most common kinds of expressions that make
526 // hierarchy-walking expensive.
527 s = e = e->IgnoreParenCasts();
528
529 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
530 return (ref->getDecl() == &var);
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000531 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
532 const BlockDecl *block = be->getBlockDecl();
533 for (BlockDecl::capture_const_iterator i = block->capture_begin(),
534 e = block->capture_end(); i != e; ++i) {
535 if (i->getVariable() == &var)
536 return true;
537 }
538 }
John McCall31168b02011-06-15 23:02:42 +0000539 }
540
541 for (Stmt::const_child_range children = s->children(); children; ++children)
Fariborz Jahanian326701e2011-06-29 20:00:16 +0000542 // children might be null; as in missing decl or conditional of an if-stmt.
543 if ((*children) && isAccessedBy(var, *children))
John McCall31168b02011-06-15 23:02:42 +0000544 return true;
545
546 return false;
547}
548
549static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
550 if (!decl) return false;
551 if (!isa<VarDecl>(decl)) return false;
552 const VarDecl *var = cast<VarDecl>(decl);
553 return isAccessedBy(*var, e);
554}
555
John McCall1553b192011-06-16 04:16:24 +0000556static void drillIntoBlockVariable(CodeGenFunction &CGF,
557 LValue &lvalue,
558 const VarDecl *var) {
559 lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var));
560}
561
John McCall31168b02011-06-15 23:02:42 +0000562void CodeGenFunction::EmitScalarInit(const Expr *init,
563 const ValueDecl *D,
John McCall1553b192011-06-16 04:16:24 +0000564 LValue lvalue,
565 bool capturedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000566 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +0000567 if (!lifetime) {
568 llvm::Value *value = EmitScalarExpr(init);
John McCall1553b192011-06-16 04:16:24 +0000569 if (capturedByInit)
570 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Chisnallfa35df62012-01-16 17:27:18 +0000571 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
John McCall31168b02011-06-15 23:02:42 +0000572 return;
573 }
574
575 // If we're emitting a value with lifetime, we have to do the
576 // initialization *before* we leave the cleanup scopes.
John McCall08ef4662011-11-10 08:15:53 +0000577 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
578 enterFullExpression(ewc);
John McCall31168b02011-06-15 23:02:42 +0000579 init = ewc->getSubExpr();
John McCall08ef4662011-11-10 08:15:53 +0000580 }
581 CodeGenFunction::RunCleanupsScope Scope(*this);
John McCall31168b02011-06-15 23:02:42 +0000582
583 // We have to maintain the illusion that the variable is
584 // zero-initialized. If the variable might be accessed in its
585 // initializer, zero-initialize before running the initializer, then
586 // actually perform the initialization with an assign.
587 bool accessedByInit = false;
588 if (lifetime != Qualifiers::OCL_ExplicitNone)
John McCallb726a552011-07-28 07:23:35 +0000589 accessedByInit = (capturedByInit || isAccessedBy(D, init));
John McCall31168b02011-06-15 23:02:42 +0000590 if (accessedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000591 LValue tempLV = lvalue;
John McCall31168b02011-06-15 23:02:42 +0000592 // Drill down to the __block object if necessary.
John McCall31168b02011-06-15 23:02:42 +0000593 if (capturedByInit) {
594 // We can use a simple GEP for this because it can't have been
595 // moved yet.
John McCall1553b192011-06-16 04:16:24 +0000596 tempLV.setAddress(Builder.CreateStructGEP(tempLV.getAddress(),
597 getByRefValueLLVMField(cast<VarDecl>(D))));
John McCall31168b02011-06-15 23:02:42 +0000598 }
599
Chris Lattner2192fe52011-07-18 04:24:23 +0000600 llvm::PointerType *ty
John McCall1553b192011-06-16 04:16:24 +0000601 = cast<llvm::PointerType>(tempLV.getAddress()->getType());
John McCall31168b02011-06-15 23:02:42 +0000602 ty = cast<llvm::PointerType>(ty->getElementType());
603
604 llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
Eric Christopher31ab1302011-08-23 22:38:00 +0000605
John McCall31168b02011-06-15 23:02:42 +0000606 // If __weak, we want to use a barrier under certain conditions.
607 if (lifetime == Qualifiers::OCL_Weak)
John McCall1553b192011-06-16 04:16:24 +0000608 EmitARCInitWeak(tempLV.getAddress(), zero);
John McCall31168b02011-06-15 23:02:42 +0000609
610 // Otherwise just do a simple store.
611 else
David Chisnallfa35df62012-01-16 17:27:18 +0000612 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000613 }
614
615 // Emit the initializer.
616 llvm::Value *value = 0;
617
618 switch (lifetime) {
619 case Qualifiers::OCL_None:
620 llvm_unreachable("present but none");
621
622 case Qualifiers::OCL_ExplicitNone:
623 // nothing to do
624 value = EmitScalarExpr(init);
625 break;
626
627 case Qualifiers::OCL_Strong: {
628 value = EmitARCRetainScalarExpr(init);
629 break;
630 }
631
632 case Qualifiers::OCL_Weak: {
633 // No way to optimize a producing initializer into this. It's not
634 // worth optimizing for, because the value will immediately
635 // disappear in the common case.
636 value = EmitScalarExpr(init);
637
John McCall1553b192011-06-16 04:16:24 +0000638 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000639 if (accessedByInit)
John McCall1553b192011-06-16 04:16:24 +0000640 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +0000641 else
John McCall1553b192011-06-16 04:16:24 +0000642 EmitARCInitWeak(lvalue.getAddress(), value);
John McCall31168b02011-06-15 23:02:42 +0000643 return;
644 }
645
646 case Qualifiers::OCL_Autoreleasing:
647 value = EmitARCRetainAutoreleaseScalarExpr(init);
648 break;
649 }
650
John McCall1553b192011-06-16 04:16:24 +0000651 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000652
653 // If the variable might have been accessed by its initializer, we
654 // might have to initialize with a barrier. We have to do this for
655 // both __weak and __strong, but __weak got filtered out above.
656 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000657 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
David Chisnallfa35df62012-01-16 17:27:18 +0000658 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCallcdda29c2013-03-13 03:10:54 +0000659 EmitARCRelease(oldValue, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +0000660 return;
661 }
662
David Chisnallfa35df62012-01-16 17:27:18 +0000663 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000664}
Chris Lattnerb85025f2010-12-01 02:05:19 +0000665
John McCalld4631322011-06-17 06:42:21 +0000666/// EmitScalarInit - Initialize the given lvalue with the given object.
667void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
668 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
669 if (!lifetime)
David Chisnallfa35df62012-01-16 17:27:18 +0000670 return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
John McCalld4631322011-06-17 06:42:21 +0000671
672 switch (lifetime) {
673 case Qualifiers::OCL_None:
674 llvm_unreachable("present but none");
675
676 case Qualifiers::OCL_ExplicitNone:
677 // nothing to do
678 break;
679
680 case Qualifiers::OCL_Strong:
681 init = EmitARCRetain(lvalue.getType(), init);
682 break;
683
684 case Qualifiers::OCL_Weak:
685 // Initialize and then skip the primitive store.
686 EmitARCInitWeak(lvalue.getAddress(), init);
687 return;
688
689 case Qualifiers::OCL_Autoreleasing:
690 init = EmitARCRetainAutorelease(lvalue.getType(), init);
691 break;
692 }
693
David Chisnallfa35df62012-01-16 17:27:18 +0000694 EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
John McCalld4631322011-06-17 06:42:21 +0000695}
696
Chris Lattnerb85025f2010-12-01 02:05:19 +0000697/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
698/// non-zero parts of the specified initializer with equal or fewer than
699/// NumStores scalar stores.
700static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
701 unsigned &NumStores) {
Chris Lattnere6af8862010-12-02 01:58:41 +0000702 // Zero and Undef never requires any extra stores.
703 if (isa<llvm::ConstantAggregateZero>(Init) ||
704 isa<llvm::ConstantPointerNull>(Init) ||
705 isa<llvm::UndefValue>(Init))
706 return true;
707 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
708 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
709 isa<llvm::ConstantExpr>(Init))
710 return Init->isNullValue() || NumStores--;
711
712 // See if we can emit each element.
713 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
714 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
715 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
716 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
717 return false;
718 }
719 return true;
720 }
Chris Lattner236b3572012-01-31 04:36:19 +0000721
722 if (llvm::ConstantDataSequential *CDS =
723 dyn_cast<llvm::ConstantDataSequential>(Init)) {
724 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
725 llvm::Constant *Elt = CDS->getElementAsConstant(i);
726 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
727 return false;
728 }
729 return true;
730 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000731
Chris Lattnerb85025f2010-12-01 02:05:19 +0000732 // Anything else is hard and scary.
733 return false;
734}
735
736/// emitStoresForInitAfterMemset - For inits that
737/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
738/// stores that would be required.
739static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
John McCallc533cb72011-02-22 06:44:22 +0000740 bool isVolatile, CGBuilderTy &Builder) {
Benjamin Kramer29f9a002012-08-27 22:07:02 +0000741 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
742 "called emitStoresForInitAfterMemset for zero or undef value.");
Eric Christopher31ab1302011-08-23 22:38:00 +0000743
Chris Lattnere6af8862010-12-02 01:58:41 +0000744 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
745 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
746 isa<llvm::ConstantExpr>(Init)) {
Chris Lattner236b3572012-01-31 04:36:19 +0000747 Builder.CreateStore(Init, Loc, isVolatile);
748 return;
749 }
750
751 if (llvm::ConstantDataSequential *CDS =
752 dyn_cast<llvm::ConstantDataSequential>(Init)) {
753 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
754 llvm::Constant *Elt = CDS->getElementAsConstant(i);
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000755
756 // If necessary, get a pointer to the element and emit it.
757 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
758 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
759 isVolatile, Builder);
Chris Lattner236b3572012-01-31 04:36:19 +0000760 }
Chris Lattnere6af8862010-12-02 01:58:41 +0000761 return;
762 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000763
Chris Lattnere6af8862010-12-02 01:58:41 +0000764 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
765 "Unknown value type!");
Eric Christopher31ab1302011-08-23 22:38:00 +0000766
Chris Lattnere6af8862010-12-02 01:58:41 +0000767 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
768 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000769
770 // If necessary, get a pointer to the element and emit it.
771 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
772 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
773 isVolatile, Builder);
Chris Lattnere6af8862010-12-02 01:58:41 +0000774 }
Chris Lattnerb85025f2010-12-01 02:05:19 +0000775}
776
777
778/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
779/// plus some stores to initialize a local variable instead of using a memcpy
780/// from a constant global. It is beneficial to use memset if the global is all
781/// zeros, or mostly zeros and large.
782static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
783 uint64_t GlobalSize) {
784 // If a global is all zeros, always use a memset.
785 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
786
Chris Lattnerb85025f2010-12-01 02:05:19 +0000787 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
788 // do it if it will require 6 or fewer scalar stores.
789 // TODO: Should budget depends on the size? Avoiding a large global warrants
790 // plopping in more stores.
791 unsigned StoreBudget = 6;
792 uint64_t SizeLimit = 32;
Eric Christopher31ab1302011-08-23 22:38:00 +0000793
794 return GlobalSize > SizeLimit &&
Chris Lattnerb85025f2010-12-01 02:05:19 +0000795 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
796}
797
Nadav Rotem1da30942013-03-23 06:43:35 +0000798/// Should we use the LLVM lifetime intrinsics for the given local variable?
799static bool shouldUseLifetimeMarkers(CodeGenFunction &CGF, const VarDecl &D,
800 unsigned Size) {
Alexey Samsonov262f05b2013-04-02 13:19:46 +0000801 // Always emit lifetime markers in -fsanitize=use-after-scope mode.
802 if (CGF.getLangOpts().Sanitize.UseAfterScope)
803 return true;
Nadav Rotem1da30942013-03-23 06:43:35 +0000804 // For now, only in optimized builds.
805 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0)
806 return false;
807
808 // Limit the size of marked objects to 32 bytes. We don't want to increase
809 // compile time by marking tiny objects.
810 unsigned SizeThreshold = 32;
811
812 return Size > SizeThreshold;
813}
814
Chris Lattnerb85025f2010-12-01 02:05:19 +0000815
Nick Lewycky8a7d90b2010-12-30 20:21:55 +0000816/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Chris Lattner03df1222007-06-02 04:53:11 +0000817/// variable declaration with auto, register, or no storage class specifier.
Chris Lattnerb781dc792008-05-08 05:58:21 +0000818/// These turn into simple stack objects, or GlobalValues depending on target.
John McCallc533cb72011-02-22 06:44:22 +0000819void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
820 AutoVarEmission emission = EmitAutoVarAlloca(D);
821 EmitAutoVarInit(emission);
822 EmitAutoVarCleanups(emission);
823}
Chris Lattner03df1222007-06-02 04:53:11 +0000824
John McCallc533cb72011-02-22 06:44:22 +0000825/// EmitAutoVarAlloca - Emit the alloca and debug information for a
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000826/// local variable. Does not emit initialization or destruction.
John McCallc533cb72011-02-22 06:44:22 +0000827CodeGenFunction::AutoVarEmission
828CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
829 QualType Ty = D.getType();
830
831 AutoVarEmission emission(D);
832
833 bool isByRef = D.hasAttr<BlocksAttr>();
834 emission.IsByRef = isByRef;
835
836 CharUnits alignment = getContext().getDeclAlign(&D);
837 emission.Alignment = alignment;
838
John McCall23c29fe2011-06-24 21:55:10 +0000839 // If the type is variably-modified, emit all the VLA sizes for it.
840 if (Ty->isVariablyModifiedType())
841 EmitVariablyModifiedType(Ty);
842
Chris Lattner03df1222007-06-02 04:53:11 +0000843 llvm::Value *DeclPtr;
Eli Friedmana682d392008-02-15 12:20:59 +0000844 if (Ty->isConstantSizeType()) {
Rafael Espindola609f5d92013-03-26 18:41:47 +0000845 bool NRVO = getLangOpts().ElideConstructors &&
846 D.isNRVOVariable();
John McCallc533cb72011-02-22 06:44:22 +0000847
Richard Smith2bcde3a2013-06-02 00:09:52 +0000848 // If this value is an array or struct with a statically determinable
849 // constant initializer, there are optimizations we can do.
Rafael Espindola609f5d92013-03-26 18:41:47 +0000850 //
851 // TODO: We should constant-evaluate the initializer of any variable,
852 // as long as it is initialized by a constant expression. Currently,
853 // isConstantInitializer produces wrong answers for structs with
854 // reference or bitfield members, and a few other cases, and checking
855 // for POD-ness protects us from some of these.
Richard Smith2bcde3a2013-06-02 00:09:52 +0000856 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
857 (D.isConstexpr() ||
858 ((Ty.isPODType(getContext()) ||
859 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
860 D.getInit()->isConstantInitializer(getContext(), false)))) {
John McCallc533cb72011-02-22 06:44:22 +0000861
Rafael Espindola609f5d92013-03-26 18:41:47 +0000862 // If the variable's a const type, and it's neither an NRVO
863 // candidate nor a __block variable and has no mutable members,
864 // emit it as a global instead.
865 if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
866 CGM.isTypeConstant(Ty, true)) {
867 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCallc533cb72011-02-22 06:44:22 +0000868
Rafael Espindola609f5d92013-03-26 18:41:47 +0000869 emission.Address = 0; // signal this condition to later callbacks
870 assert(emission.wasEmittedAsGlobal());
871 return emission;
Tanya Lattnerf9d41df2009-11-04 01:18:09 +0000872 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000873
Rafael Espindola609f5d92013-03-26 18:41:47 +0000874 // Otherwise, tell the initialization code that we're in this case.
875 emission.IsConstantAggregate = true;
876 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000877
Rafael Espindola609f5d92013-03-26 18:41:47 +0000878 // A normal fixed sized variable becomes an alloca in the entry block,
879 // unless it's an NRVO variable.
880 llvm::Type *LTy = ConvertTypeForMem(Ty);
Eric Christopher31ab1302011-08-23 22:38:00 +0000881
Rafael Espindola609f5d92013-03-26 18:41:47 +0000882 if (NRVO) {
883 // The named return value optimization: allocate this variable in the
884 // return slot, so that we can elide the copy when returning this
885 // variable (C++0x [class.copy]p34).
886 DeclPtr = ReturnValue;
Eric Christopher31ab1302011-08-23 22:38:00 +0000887
Rafael Espindola609f5d92013-03-26 18:41:47 +0000888 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
889 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
890 // Create a flag that is used to indicate when the NRVO was applied
891 // to this variable. Set it to zero to indicate that NRVO was not
892 // applied.
893 llvm::Value *Zero = Builder.getFalse();
894 llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
895 EnsureInsertPoint();
896 Builder.CreateStore(Zero, NRVOFlag);
Eric Christopher31ab1302011-08-23 22:38:00 +0000897
Rafael Espindola609f5d92013-03-26 18:41:47 +0000898 // Record the NRVO flag for this variable.
899 NRVOFlags[&D] = NRVOFlag;
900 emission.NRVOFlag = NRVOFlag;
Nadav Rotem1da30942013-03-23 06:43:35 +0000901 }
Douglas Gregor290c93e2010-05-15 06:46:45 +0000902 }
Chris Lattnerb781dc792008-05-08 05:58:21 +0000903 } else {
Rafael Espindola609f5d92013-03-26 18:41:47 +0000904 if (isByRef)
905 LTy = BuildByRefType(&D);
906
907 llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
908 Alloc->setName(D.getName());
909
910 CharUnits allocaAlignment = alignment;
911 if (isByRef)
912 allocaAlignment = std::max(allocaAlignment,
John McCallc8e01702013-04-16 22:48:15 +0000913 getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0)));
Rafael Espindola609f5d92013-03-26 18:41:47 +0000914 Alloc->setAlignment(allocaAlignment.getQuantity());
915 DeclPtr = Alloc;
916
917 // Emit a lifetime intrinsic if meaningful. There's no point
918 // in doing this if we don't have a valid insertion point (?).
919 uint64_t size = CGM.getDataLayout().getTypeAllocSize(LTy);
920 if (HaveInsertPoint() && shouldUseLifetimeMarkers(*this, D, size)) {
921 llvm::Value *sizeV = llvm::ConstantInt::get(Int64Ty, size);
922
923 emission.SizeForLifetimeMarkers = sizeV;
924 llvm::Value *castAddr = Builder.CreateBitCast(Alloc, Int8PtrTy);
925 Builder.CreateCall2(CGM.getLLVMLifetimeStartFn(), sizeV, castAddr)
926 ->setDoesNotThrow();
927 } else {
928 assert(!emission.useLifetimeMarkers());
929 }
Chris Lattnerb781dc792008-05-08 05:58:21 +0000930 }
Chris Lattner03df1222007-06-02 04:53:11 +0000931 } else {
Daniel Dunbarb6adc432009-07-19 06:58:07 +0000932 EnsureInsertPoint();
933
Anders Carlsson15949b32009-02-09 20:41:50 +0000934 if (!DidCallStackSave) {
Anders Carlsson30032882008-12-12 07:38:43 +0000935 // Save the stack.
John McCallad7c5c12011-02-08 08:22:06 +0000936 llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
Mike Stump11289f42009-09-09 15:08:12 +0000937
Anders Carlsson30032882008-12-12 07:38:43 +0000938 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
939 llvm::Value *V = Builder.CreateCall(F);
Mike Stump11289f42009-09-09 15:08:12 +0000940
Anders Carlsson30032882008-12-12 07:38:43 +0000941 Builder.CreateStore(V, Stack);
Anders Carlsson15949b32009-02-09 20:41:50 +0000942
943 DidCallStackSave = true;
Mike Stump11289f42009-09-09 15:08:12 +0000944
John McCalla464ff92010-07-21 06:13:08 +0000945 // Push a cleanup block and restore the stack there.
John McCalle4df6c82011-01-28 08:37:24 +0000946 // FIXME: in general circumstances, this should be an EH cleanup.
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000947 pushStackRestore(NormalCleanup, Stack);
Anders Carlsson30032882008-12-12 07:38:43 +0000948 }
Mike Stump11289f42009-09-09 15:08:12 +0000949
John McCall23c29fe2011-06-24 21:55:10 +0000950 llvm::Value *elementCount;
951 QualType elementType;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000952 std::tie(elementCount, elementType) = getVLASize(Ty);
Anders Carlsson30032882008-12-12 07:38:43 +0000953
Chris Lattner2192fe52011-07-18 04:24:23 +0000954 llvm::Type *llvmTy = ConvertTypeForMem(elementType);
Anders Carlsson30032882008-12-12 07:38:43 +0000955
956 // Allocate memory for the array.
John McCall23c29fe2011-06-24 21:55:10 +0000957 llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
958 vla->setAlignment(alignment.getQuantity());
Anders Carlssone33eed52009-09-26 18:16:06 +0000959
John McCall23c29fe2011-06-24 21:55:10 +0000960 DeclPtr = vla;
Chris Lattner03df1222007-06-02 04:53:11 +0000961 }
Eli Friedmanf4084702008-12-20 23:11:59 +0000962
Chris Lattner03df1222007-06-02 04:53:11 +0000963 llvm::Value *&DMEntry = LocalDeclMap[&D];
964 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
965 DMEntry = DeclPtr;
John McCallc533cb72011-02-22 06:44:22 +0000966 emission.Address = DeclPtr;
Sanjiv Gupta18de6242008-05-30 10:30:31 +0000967
968 // Emit debug info for local var declaration.
Devang Patel887e2152011-06-03 19:21:47 +0000969 if (HaveInsertPoint())
970 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000971 if (CGM.getCodeGenOpts().getDebugInfo()
972 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +0000973 DI->setLocation(D.getLocation());
Rafael Espindola609f5d92013-03-26 18:41:47 +0000974 DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +0000975 }
Devang Patel887e2152011-06-03 19:21:47 +0000976 }
Sanjiv Gupta18de6242008-05-30 10:30:31 +0000977
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000978 if (D.hasAttr<AnnotateAttr>())
979 EmitVarAnnotations(&D, emission.Address);
980
John McCallc533cb72011-02-22 06:44:22 +0000981 return emission;
982}
983
984/// Determines whether the given __block variable is potentially
985/// captured by the given expression.
986static bool isCapturedBy(const VarDecl &var, const Expr *e) {
987 // Skip the most common kinds of expressions that make
988 // hierarchy-walking expensive.
989 e = e->IgnoreParenCasts();
990
991 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
992 const BlockDecl *block = be->getBlockDecl();
993 for (BlockDecl::capture_const_iterator i = block->capture_begin(),
994 e = block->capture_end(); i != e; ++i) {
995 if (i->getVariable() == &var)
996 return true;
997 }
998
999 // No need to walk into the subexpressions.
1000 return false;
1001 }
1002
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001003 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1004 const CompoundStmt *CS = SE->getSubStmt();
Eric Christopherd28d1072011-08-23 23:44:09 +00001005 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1006 BE = CS->body_end(); BI != BE; ++BI)
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001007 if (Expr *E = dyn_cast<Expr>((*BI))) {
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001008 if (isCapturedBy(var, E))
1009 return true;
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001010 }
1011 else if (DeclStmt *DS = dyn_cast<DeclStmt>((*BI))) {
1012 // special case declarations
1013 for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
1014 I != E; ++I) {
1015 if (VarDecl *VD = dyn_cast<VarDecl>((*I))) {
1016 Expr *Init = VD->getInit();
1017 if (Init && isCapturedBy(var, Init))
1018 return true;
1019 }
1020 }
1021 }
1022 else
1023 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1024 // Later, provide code to poke into statements for capture analysis.
1025 return true;
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001026 return false;
1027 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001028
John McCallc533cb72011-02-22 06:44:22 +00001029 for (Stmt::const_child_range children = e->children(); children; ++children)
1030 if (isCapturedBy(var, cast<Expr>(*children)))
1031 return true;
1032
1033 return false;
1034}
1035
Douglas Gregor82e1af22011-07-01 21:08:19 +00001036/// \brief Determine whether the given initializer is trivial in the sense
1037/// that it requires no code to be generated.
1038static bool isTrivialInitializer(const Expr *Init) {
1039 if (!Init)
1040 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001041
Douglas Gregor82e1af22011-07-01 21:08:19 +00001042 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1043 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1044 if (Constructor->isTrivial() &&
1045 Constructor->isDefaultConstructor() &&
1046 !Construct->requiresZeroInitialization())
1047 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001048
Douglas Gregor82e1af22011-07-01 21:08:19 +00001049 return false;
1050}
John McCallc533cb72011-02-22 06:44:22 +00001051void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001052 assert(emission.Variable && "emission was not valid!");
1053
John McCallc533cb72011-02-22 06:44:22 +00001054 // If this was emitted as a global constant, we're done.
1055 if (emission.wasEmittedAsGlobal()) return;
1056
John McCall9e2e22f2011-02-22 07:16:58 +00001057 const VarDecl &D = *emission.Variable;
John McCallc533cb72011-02-22 06:44:22 +00001058 QualType type = D.getType();
1059
Chris Lattner07eb7332007-07-12 00:39:48 +00001060 // If this local has an initializer, emit it now.
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001061 const Expr *Init = D.getInit();
1062
1063 // If we are at an unreachable point, we don't need to emit the initializer
1064 // unless it contains a label.
1065 if (!HaveInsertPoint()) {
John McCallc533cb72011-02-22 06:44:22 +00001066 if (!Init || !ContainsLabel(Init)) return;
1067 EnsureInsertPoint();
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001068 }
1069
John McCall73064872011-03-31 01:59:53 +00001070 // Initialize the structure of a __block variable.
1071 if (emission.IsByRef)
1072 emitByrefStructureInit(emission);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001073
Douglas Gregor82e1af22011-07-01 21:08:19 +00001074 if (isTrivialInitializer(Init))
1075 return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001076
John McCall73064872011-03-31 01:59:53 +00001077 CharUnits alignment = emission.Alignment;
1078
John McCallc533cb72011-02-22 06:44:22 +00001079 // Check whether this is a byref variable that's potentially
1080 // captured and moved by its own initializer. If so, we'll need to
1081 // emit the initializer first, then copy into the variable.
1082 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1083
1084 llvm::Value *Loc =
1085 capturedByInit ? emission.Address : emission.getObjectAddress(*this);
1086
Richard Smithfddd3842011-12-30 21:15:51 +00001087 llvm::Constant *constant = 0;
Richard Smith2bcde3a2013-06-02 00:09:52 +00001088 if (emission.IsConstantAggregate || D.isConstexpr()) {
Richard Smithfddd3842011-12-30 21:15:51 +00001089 assert(!capturedByInit && "constant init contains a capturing block?");
Richard Smithdafff942012-01-14 04:30:29 +00001090 constant = CGM.EmitConstantInit(D, this);
Richard Smithfddd3842011-12-30 21:15:51 +00001091 }
1092
1093 if (!constant) {
Eli Friedmana0544d62011-12-03 04:14:32 +00001094 LValue lv = MakeAddrLValue(Loc, type, alignment);
John McCall1553b192011-06-16 04:16:24 +00001095 lv.setNonGC(true);
1096 return EmitExprAsInit(Init, &D, lv, capturedByInit);
1097 }
John McCall91ca10f2011-03-08 09:11:50 +00001098
Richard Smith2bcde3a2013-06-02 00:09:52 +00001099 if (!emission.IsConstantAggregate) {
1100 // For simple scalar/complex initialization, store the value directly.
1101 LValue lv = MakeAddrLValue(Loc, type, alignment);
1102 lv.setNonGC(true);
1103 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1104 }
1105
John McCallc533cb72011-02-22 06:44:22 +00001106 // If this is a simple aggregate initialization, we can optimize it
1107 // in various ways.
John McCall91ca10f2011-03-08 09:11:50 +00001108 bool isVolatile = type.isVolatileQualified();
John McCallc533cb72011-02-22 06:44:22 +00001109
John McCall91ca10f2011-03-08 09:11:50 +00001110 llvm::Value *SizeVal =
Eric Christopher31ab1302011-08-23 22:38:00 +00001111 llvm::ConstantInt::get(IntPtrTy,
John McCall91ca10f2011-03-08 09:11:50 +00001112 getContext().getTypeSizeInChars(type).getQuantity());
John McCallc533cb72011-02-22 06:44:22 +00001113
Chris Lattner2192fe52011-07-18 04:24:23 +00001114 llvm::Type *BP = Int8PtrTy;
John McCall91ca10f2011-03-08 09:11:50 +00001115 if (Loc->getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001116 Loc = Builder.CreateBitCast(Loc, BP);
Mon P Wangcc2ab0c2010-04-04 03:10:52 +00001117
John McCall91ca10f2011-03-08 09:11:50 +00001118 // If the initializer is all or mostly zeros, codegen with memset then do
1119 // a few stores afterward.
Eric Christopher31ab1302011-08-23 22:38:00 +00001120 if (shouldUseMemSetPlusStoresToInitialize(constant,
Micah Villmowdd31ca12012-10-08 16:25:52 +00001121 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
John McCall91ca10f2011-03-08 09:11:50 +00001122 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1123 alignment.getQuantity(), isVolatile);
Benjamin Kramer29f9a002012-08-27 22:07:02 +00001124 // Zero and undef don't require a stores.
1125 if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
John McCall91ca10f2011-03-08 09:11:50 +00001126 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
1127 emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001128 }
John McCall91ca10f2011-03-08 09:11:50 +00001129 } else {
Eric Christopher31ab1302011-08-23 22:38:00 +00001130 // Otherwise, create a temporary global with the initializer then
John McCall91ca10f2011-03-08 09:11:50 +00001131 // memcpy from the global to the alloca.
1132 std::string Name = GetStaticDeclName(*this, D, ".");
1133 llvm::GlobalVariable *GV =
1134 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
Eric Christopherb58b3e82011-08-24 00:33:55 +00001135 llvm::GlobalValue::PrivateLinkage,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001136 constant, Name);
John McCall91ca10f2011-03-08 09:11:50 +00001137 GV->setAlignment(alignment.getQuantity());
Eli Friedmanb8578422011-05-27 22:32:55 +00001138 GV->setUnnamedAddr(true);
Eric Christopher31ab1302011-08-23 22:38:00 +00001139
John McCall91ca10f2011-03-08 09:11:50 +00001140 llvm::Value *SrcPtr = GV;
1141 if (SrcPtr->getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001142 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
John McCall91ca10f2011-03-08 09:11:50 +00001143
1144 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
1145 isVolatile);
1146 }
1147}
1148
1149/// Emit an expression as an initializer for a variable at the given
1150/// location. The expression is not necessarily the normal
1151/// initializer for the variable, and the address is not necessarily
1152/// its normal location.
1153///
1154/// \param init the initializing expression
1155/// \param var the variable to act as if we're initializing
1156/// \param loc the address to initialize; its type is a pointer
1157/// to the LLVM mapping of the variable's type
1158/// \param alignment the alignment of the address
1159/// \param capturedByInit true if the variable is a __block variable
1160/// whose address is potentially changed by the initializer
1161void CodeGenFunction::EmitExprAsInit(const Expr *init,
John McCall31168b02011-06-15 23:02:42 +00001162 const ValueDecl *D,
John McCall1553b192011-06-16 04:16:24 +00001163 LValue lvalue,
John McCall91ca10f2011-03-08 09:11:50 +00001164 bool capturedByInit) {
John McCall31168b02011-06-15 23:02:42 +00001165 QualType type = D->getType();
John McCall91ca10f2011-03-08 09:11:50 +00001166
1167 if (type->isReferenceType()) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +00001168 RValue rvalue = EmitReferenceBindingToExpr(init);
Eric Christopher31ab1302011-08-23 22:38:00 +00001169 if (capturedByInit)
John McCall1553b192011-06-16 04:16:24 +00001170 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Chisnallfa35df62012-01-16 17:27:18 +00001171 EmitStoreThroughLValue(rvalue, lvalue, true);
John McCall47fb9502013-03-07 21:37:08 +00001172 return;
1173 }
1174 switch (getEvaluationKind(type)) {
1175 case TEK_Scalar:
John McCall1553b192011-06-16 04:16:24 +00001176 EmitScalarInit(init, D, lvalue, capturedByInit);
John McCall47fb9502013-03-07 21:37:08 +00001177 return;
1178 case TEK_Complex: {
John McCall91ca10f2011-03-08 09:11:50 +00001179 ComplexPairTy complex = EmitComplexExpr(init);
John McCall1553b192011-06-16 04:16:24 +00001180 if (capturedByInit)
1181 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall47fb9502013-03-07 21:37:08 +00001182 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
1183 return;
1184 }
1185 case TEK_Aggregate:
John McCalla8ec7eb2013-03-07 21:37:17 +00001186 if (type->isAtomicType()) {
1187 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1188 } else {
1189 // TODO: how can we delay here if D is captured by its initializer?
1190 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001191 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001192 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001193 AggValueSlot::IsNotAliased));
John McCalla8ec7eb2013-03-07 21:37:17 +00001194 }
John McCall47fb9502013-03-07 21:37:08 +00001195 return;
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001196 }
John McCall47fb9502013-03-07 21:37:08 +00001197 llvm_unreachable("bad evaluation kind");
John McCallc533cb72011-02-22 06:44:22 +00001198}
John McCallbd309292010-07-06 01:34:17 +00001199
John McCall82fe67b2011-07-09 01:37:26 +00001200/// Enter a destroy cleanup for the given local variable.
1201void CodeGenFunction::emitAutoVarTypeCleanup(
1202 const CodeGenFunction::AutoVarEmission &emission,
1203 QualType::DestructionKind dtorKind) {
1204 assert(dtorKind != QualType::DK_none);
1205
1206 // Note that for __block variables, we want to destroy the
1207 // original stack object, not the possibly forwarded object.
1208 llvm::Value *addr = emission.getObjectAddress(*this);
1209
1210 const VarDecl *var = emission.Variable;
1211 QualType type = var->getType();
1212
1213 CleanupKind cleanupKind = NormalAndEHCleanup;
1214 CodeGenFunction::Destroyer *destroyer = 0;
1215
1216 switch (dtorKind) {
1217 case QualType::DK_none:
1218 llvm_unreachable("no cleanup for trivially-destructible variable");
1219
1220 case QualType::DK_cxx_destructor:
1221 // If there's an NRVO flag on the emission, we need a different
1222 // cleanup.
1223 if (emission.NRVOFlag) {
1224 assert(!type->isArrayType());
1225 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1226 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor,
1227 emission.NRVOFlag);
1228 return;
1229 }
1230 break;
1231
1232 case QualType::DK_objc_strong_lifetime:
1233 // Suppress cleanups for pseudo-strong variables.
1234 if (var->isARCPseudoStrong()) return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001235
John McCall82fe67b2011-07-09 01:37:26 +00001236 // Otherwise, consider whether to use an EH cleanup or not.
1237 cleanupKind = getARCCleanupKind();
1238
1239 // Use the imprecise destroyer by default.
1240 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1241 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1242 break;
1243
1244 case QualType::DK_objc_weak_lifetime:
1245 break;
1246 }
1247
1248 // If we haven't chosen a more specific destroyer, use the default.
Peter Collingbourne1425b452012-01-26 03:33:36 +00001249 if (!destroyer) destroyer = getDestroyer(dtorKind);
John McCall178360e2011-07-11 08:38:19 +00001250
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001251 // Use an EH cleanup in array destructors iff the destructor itself
John McCall178360e2011-07-11 08:38:19 +00001252 // is being pushed as an EH cleanup.
1253 bool useEHCleanup = (cleanupKind & EHCleanup);
1254 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1255 useEHCleanup);
John McCall82fe67b2011-07-09 01:37:26 +00001256}
1257
John McCallc533cb72011-02-22 06:44:22 +00001258void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001259 assert(emission.Variable && "emission was not valid!");
1260
John McCallc533cb72011-02-22 06:44:22 +00001261 // If this was emitted as a global constant, we're done.
1262 if (emission.wasEmittedAsGlobal()) return;
1263
John McCall8c38d352012-04-13 18:44:05 +00001264 // If we don't have an insertion point, we're done. Sema prevents
1265 // us from jumping into any of these scopes anyway.
1266 if (!HaveInsertPoint()) return;
1267
John McCall9e2e22f2011-02-22 07:16:58 +00001268 const VarDecl &D = *emission.Variable;
John McCallc533cb72011-02-22 06:44:22 +00001269
Nadav Rotem1da30942013-03-23 06:43:35 +00001270 // Make sure we call @llvm.lifetime.end. This needs to happen
1271 // *last*, so the cleanup needs to be pushed *first*.
1272 if (emission.useLifetimeMarkers()) {
1273 EHStack.pushCleanup<CallLifetimeEnd>(NormalCleanup,
1274 emission.getAllocatedAddress(),
1275 emission.getSizeForLifetimeMarkers());
1276 }
1277
John McCall82fe67b2011-07-09 01:37:26 +00001278 // Check the type for a cleanup.
1279 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1280 emitAutoVarTypeCleanup(emission, dtorKind);
John McCall31168b02011-06-15 23:02:42 +00001281
John McCall1bd25562011-06-24 23:21:27 +00001282 // In GC mode, honor objc_precise_lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001283 if (getLangOpts().getGC() != LangOptions::NonGC &&
John McCall1bd25562011-06-24 23:21:27 +00001284 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1285 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1286 }
1287
John McCallc533cb72011-02-22 06:44:22 +00001288 // Handle the cleanup attribute.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001289 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001290 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001291
John McCallc533cb72011-02-22 06:44:22 +00001292 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001293 assert(F && "Could not find function!");
Mike Stump11289f42009-09-09 15:08:12 +00001294
John McCalla729c622012-02-17 03:33:10 +00001295 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
John McCallc533cb72011-02-22 06:44:22 +00001296 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001297 }
Mike Stump626aecc2009-03-05 01:23:13 +00001298
John McCallc533cb72011-02-22 06:44:22 +00001299 // If this is a block variable, call _Block_object_destroy
1300 // (on the unforwarded address).
John McCall73064872011-03-31 01:59:53 +00001301 if (emission.IsByRef)
1302 enterByrefCleanup(emission);
Chris Lattner03df1222007-06-02 04:53:11 +00001303}
Chris Lattner53621a52007-06-13 20:44:40 +00001304
Peter Collingbourne1425b452012-01-26 03:33:36 +00001305CodeGenFunction::Destroyer *
John McCall82fe67b2011-07-09 01:37:26 +00001306CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1307 switch (kind) {
1308 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
John McCallc2f00012011-07-09 09:09:00 +00001309 case QualType::DK_cxx_destructor:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001310 return destroyCXXObject;
John McCallc2f00012011-07-09 09:09:00 +00001311 case QualType::DK_objc_strong_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001312 return destroyARCStrongPrecise;
John McCallc2f00012011-07-09 09:09:00 +00001313 case QualType::DK_objc_weak_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001314 return destroyARCWeak;
John McCall82fe67b2011-07-09 01:37:26 +00001315 }
Matt Beaumont-Gay934bbf52012-01-27 00:46:27 +00001316 llvm_unreachable("Unknown DestructionKind");
John McCall82fe67b2011-07-09 01:37:26 +00001317}
1318
John McCall12cc42a2013-02-01 05:11:40 +00001319/// pushEHDestroy - Push the standard destructor for the given type as
1320/// an EH-only cleanup.
1321void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
1322 llvm::Value *addr, QualType type) {
1323 assert(dtorKind && "cannot push destructor for trivial type");
1324 assert(needsEHCleanup(dtorKind));
1325
1326 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1327}
1328
1329/// pushDestroy - Push the standard destructor for the given type as
1330/// at least a normal cleanup.
John McCall4bd0fb12011-07-12 16:41:08 +00001331void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
1332 llvm::Value *addr, QualType type) {
1333 assert(dtorKind && "cannot push destructor for trivial type");
1334
1335 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1336 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1337 cleanupKind & EHCleanup);
1338}
1339
John McCall82fe67b2011-07-09 01:37:26 +00001340void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *addr,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001341 QualType type, Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001342 bool useEHCleanupForArray) {
John McCall4bd0fb12011-07-12 16:41:08 +00001343 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1344 destroyer, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001345}
1346
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001347void CodeGenFunction::pushStackRestore(CleanupKind Kind, llvm::Value *SPMem) {
1348 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
1349}
1350
Richard Smith736a9472013-06-12 20:42:33 +00001351void CodeGenFunction::pushLifetimeExtendedDestroy(
1352 CleanupKind cleanupKind, llvm::Value *addr, QualType type,
1353 Destroyer *destroyer, bool useEHCleanupForArray) {
1354 assert(!isInConditionalBranch() &&
1355 "performing lifetime extension from within conditional");
1356
1357 // Push an EH-only cleanup for the object now.
1358 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1359 // around in case a temporary's destructor throws an exception.
1360 if (cleanupKind & EHCleanup)
1361 EHStack.pushCleanup<DestroyObject>(
1362 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1363 destroyer, useEHCleanupForArray);
1364
1365 // Remember that we need to push a full cleanup for the object at the
1366 // end of the full-expression.
1367 pushCleanupAfterFullExpr<DestroyObject>(
1368 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1369}
1370
John McCall178360e2011-07-11 08:38:19 +00001371/// emitDestroy - Immediately perform the destruction of the given
1372/// object.
1373///
1374/// \param addr - the address of the object; a type*
1375/// \param type - the type of the object; if an array type, all
1376/// objects are destroyed in reverse order
1377/// \param destroyer - the function to call to destroy individual
1378/// elements
1379/// \param useEHCleanupForArray - whether an EH cleanup should be
1380/// used when destroying array elements, in case one of the
1381/// destructions throws an exception
John McCall82fe67b2011-07-09 01:37:26 +00001382void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001383 Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001384 bool useEHCleanupForArray) {
John McCall82fe67b2011-07-09 01:37:26 +00001385 const ArrayType *arrayType = getContext().getAsArrayType(type);
1386 if (!arrayType)
1387 return destroyer(*this, addr, type);
1388
1389 llvm::Value *begin = addr;
1390 llvm::Value *length = emitArrayLength(arrayType, type, begin);
John McCall97eab0a2011-07-13 08:09:46 +00001391
1392 // Normally we have to check whether the array is zero-length.
1393 bool checkZeroLength = true;
1394
1395 // But if the array length is constant, we can suppress that.
1396 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1397 // ...and if it's constant zero, we can just skip the entire thing.
1398 if (constLength->isZero()) return;
1399 checkZeroLength = false;
1400 }
1401
John McCall82fe67b2011-07-09 01:37:26 +00001402 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
John McCall97eab0a2011-07-13 08:09:46 +00001403 emitArrayDestroy(begin, end, type, destroyer,
1404 checkZeroLength, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001405}
1406
John McCall178360e2011-07-11 08:38:19 +00001407/// emitArrayDestroy - Destroys all the elements of the given array,
1408/// beginning from last to first. The array cannot be zero-length.
1409///
1410/// \param begin - a type* denoting the first element of the array
1411/// \param end - a type* denoting one past the end of the array
1412/// \param type - the element type of the array
1413/// \param destroyer - the function to call to destroy elements
1414/// \param useEHCleanup - whether to push an EH cleanup to destroy
1415/// the remaining elements in case the destruction of a single
1416/// element throws
John McCall82fe67b2011-07-09 01:37:26 +00001417void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1418 llvm::Value *end,
1419 QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001420 Destroyer *destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001421 bool checkZeroLength,
John McCall178360e2011-07-11 08:38:19 +00001422 bool useEHCleanup) {
John McCall82fe67b2011-07-09 01:37:26 +00001423 assert(!type->isArrayType());
1424
1425 // The basic structure here is a do-while loop, because we don't
1426 // need to check for the zero-element case.
1427 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1428 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1429
John McCall97eab0a2011-07-13 08:09:46 +00001430 if (checkZeroLength) {
1431 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1432 "arraydestroy.isempty");
1433 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1434 }
1435
John McCall82fe67b2011-07-09 01:37:26 +00001436 // Enter the loop body, making that address the current address.
1437 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1438 EmitBlock(bodyBB);
1439 llvm::PHINode *elementPast =
1440 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1441 elementPast->addIncoming(end, entryBB);
1442
1443 // Shift the address back by one element.
1444 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1445 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1446 "arraydestroy.element");
1447
John McCall178360e2011-07-11 08:38:19 +00001448 if (useEHCleanup)
1449 pushRegularPartialArrayCleanup(begin, element, type, destroyer);
1450
John McCall82fe67b2011-07-09 01:37:26 +00001451 // Perform the actual destruction there.
1452 destroyer(*this, element, type);
1453
John McCall178360e2011-07-11 08:38:19 +00001454 if (useEHCleanup)
1455 PopCleanupBlock();
1456
John McCall82fe67b2011-07-09 01:37:26 +00001457 // Check whether we've reached the end.
1458 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1459 Builder.CreateCondBr(done, doneBB, bodyBB);
1460 elementPast->addIncoming(element, Builder.GetInsertBlock());
1461
1462 // Done.
1463 EmitBlock(doneBB);
1464}
1465
John McCall178360e2011-07-11 08:38:19 +00001466/// Perform partial array destruction as if in an EH cleanup. Unlike
1467/// emitArrayDestroy, the element type here may still be an array type.
John McCall178360e2011-07-11 08:38:19 +00001468static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1469 llvm::Value *begin, llvm::Value *end,
1470 QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001471 CodeGenFunction::Destroyer *destroyer) {
John McCall178360e2011-07-11 08:38:19 +00001472 // If the element type is itself an array, drill down.
John McCall97eab0a2011-07-13 08:09:46 +00001473 unsigned arrayDepth = 0;
John McCall178360e2011-07-11 08:38:19 +00001474 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1475 // VLAs don't require a GEP index to walk into.
1476 if (!isa<VariableArrayType>(arrayType))
John McCall97eab0a2011-07-13 08:09:46 +00001477 arrayDepth++;
John McCall178360e2011-07-11 08:38:19 +00001478 type = arrayType->getElementType();
1479 }
John McCall97eab0a2011-07-13 08:09:46 +00001480
1481 if (arrayDepth) {
1482 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, arrayDepth+1);
1483
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001484 SmallVector<llvm::Value*,4> gepIndices(arrayDepth, zero);
Jay Foad040dd822011-07-22 08:16:57 +00001485 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1486 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
John McCall178360e2011-07-11 08:38:19 +00001487 }
1488
John McCall97eab0a2011-07-13 08:09:46 +00001489 // Destroy the array. We don't ever need an EH cleanup because we
1490 // assume that we're in an EH cleanup ourselves, so a throwing
1491 // destructor causes an immediate terminate.
1492 CGF.emitArrayDestroy(begin, end, type, destroyer,
1493 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
John McCall178360e2011-07-11 08:38:19 +00001494}
1495
John McCall82fe67b2011-07-09 01:37:26 +00001496namespace {
John McCall178360e2011-07-11 08:38:19 +00001497 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1498 /// array destroy where the end pointer is regularly determined and
1499 /// does not need to be loaded from a local.
1500 class RegularPartialArrayDestroy : public EHScopeStack::Cleanup {
1501 llvm::Value *ArrayBegin;
1502 llvm::Value *ArrayEnd;
1503 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001504 CodeGenFunction::Destroyer *Destroyer;
John McCall178360e2011-07-11 08:38:19 +00001505 public:
1506 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
1507 QualType elementType,
1508 CodeGenFunction::Destroyer *destroyer)
1509 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
Peter Collingbourne1425b452012-01-26 03:33:36 +00001510 ElementType(elementType), Destroyer(destroyer) {}
John McCall178360e2011-07-11 08:38:19 +00001511
John McCall30317fd2011-07-12 20:27:29 +00001512 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall178360e2011-07-11 08:38:19 +00001513 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
1514 ElementType, Destroyer);
1515 }
1516 };
1517
1518 /// IrregularPartialArrayDestroy - a cleanup which performs a
1519 /// partial array destroy where the end pointer is irregularly
1520 /// determined and must be loaded from a local.
1521 class IrregularPartialArrayDestroy : public EHScopeStack::Cleanup {
John McCall82fe67b2011-07-09 01:37:26 +00001522 llvm::Value *ArrayBegin;
1523 llvm::Value *ArrayEndPointer;
1524 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001525 CodeGenFunction::Destroyer *Destroyer;
John McCall82fe67b2011-07-09 01:37:26 +00001526 public:
John McCall178360e2011-07-11 08:38:19 +00001527 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
1528 llvm::Value *arrayEndPointer,
1529 QualType elementType,
1530 CodeGenFunction::Destroyer *destroyer)
John McCall82fe67b2011-07-09 01:37:26 +00001531 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
Peter Collingbourne1425b452012-01-26 03:33:36 +00001532 ElementType(elementType), Destroyer(destroyer) {}
John McCall82fe67b2011-07-09 01:37:26 +00001533
John McCall30317fd2011-07-12 20:27:29 +00001534 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall82fe67b2011-07-09 01:37:26 +00001535 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
John McCall178360e2011-07-11 08:38:19 +00001536 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
1537 ElementType, Destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001538 }
1539 };
1540}
1541
John McCall178360e2011-07-11 08:38:19 +00001542/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
John McCall82fe67b2011-07-09 01:37:26 +00001543/// already-constructed elements of the given array. The cleanup
John McCall178360e2011-07-11 08:38:19 +00001544/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001545///
John McCall82fe67b2011-07-09 01:37:26 +00001546/// \param elementType - the immediate element type of the array;
1547/// possibly still an array type
John McCall4bd0fb12011-07-12 16:41:08 +00001548void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
John McCall178360e2011-07-11 08:38:19 +00001549 llvm::Value *arrayEndPointer,
1550 QualType elementType,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001551 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001552 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1553 arrayBegin, arrayEndPointer,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001554 elementType, destroyer);
John McCall178360e2011-07-11 08:38:19 +00001555}
1556
1557/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1558/// already-constructed elements of the given array. The cleanup
1559/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001560///
John McCall178360e2011-07-11 08:38:19 +00001561/// \param elementType - the immediate element type of the array;
1562/// possibly still an array type
John McCall178360e2011-07-11 08:38:19 +00001563void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1564 llvm::Value *arrayEnd,
1565 QualType elementType,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001566 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001567 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
John McCall178360e2011-07-11 08:38:19 +00001568 arrayBegin, arrayEnd,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001569 elementType, destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001570}
1571
Nadav Rotem1da30942013-03-23 06:43:35 +00001572/// Lazily declare the @llvm.lifetime.start intrinsic.
1573llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
1574 if (LifetimeStartFn) return LifetimeStartFn;
1575 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1576 llvm::Intrinsic::lifetime_start);
1577 return LifetimeStartFn;
1578}
1579
1580/// Lazily declare the @llvm.lifetime.end intrinsic.
1581llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
1582 if (LifetimeEndFn) return LifetimeEndFn;
1583 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1584 llvm::Intrinsic::lifetime_end);
1585 return LifetimeEndFn;
1586}
1587
John McCall31168b02011-06-15 23:02:42 +00001588namespace {
1589 /// A cleanup to perform a release of an object at the end of a
1590 /// function. This is used to balance out the incoming +1 of a
1591 /// ns_consumed argument when we can't reasonably do that just by
1592 /// not doing the initial retain for a __block argument.
1593 struct ConsumeARCParameter : EHScopeStack::Cleanup {
John McCallcdda29c2013-03-13 03:10:54 +00001594 ConsumeARCParameter(llvm::Value *param,
1595 ARCPreciseLifetime_t precise)
1596 : Param(param), Precise(precise) {}
John McCall31168b02011-06-15 23:02:42 +00001597
1598 llvm::Value *Param;
John McCallcdda29c2013-03-13 03:10:54 +00001599 ARCPreciseLifetime_t Precise;
John McCall31168b02011-06-15 23:02:42 +00001600
John McCall30317fd2011-07-12 20:27:29 +00001601 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallcdda29c2013-03-13 03:10:54 +00001602 CGF.EmitARCRelease(Param, Precise);
John McCall31168b02011-06-15 23:02:42 +00001603 }
1604 };
1605}
1606
Mike Stump11289f42009-09-09 15:08:12 +00001607/// Emit an alloca (or GlobalValue depending on target)
Chris Lattnerb781dc792008-05-08 05:58:21 +00001608/// for the specified parameter and set up LocalDeclMap.
Devang Patel68a15252011-03-03 20:13:15 +00001609void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001610 bool ArgIsPointer, unsigned ArgNo) {
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001611 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Guptad7959242008-10-31 09:52:39 +00001612 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001613 "Invalid argument to EmitParmDecl");
John McCall147d0212011-02-22 22:38:33 +00001614
1615 Arg->setName(D.getName());
1616
Adrian Prantl51936dd2013-03-14 17:53:33 +00001617 QualType Ty = D.getType();
1618
John McCall147d0212011-02-22 22:38:33 +00001619 // Use better IR generation for certain implicit parameters.
1620 if (isa<ImplicitParamDecl>(D)) {
1621 // The only implicit argument a block has is its literal.
1622 if (BlockInfo) {
1623 LocalDeclMap[&D] = Arg;
Adrian Prantl51936dd2013-03-14 17:53:33 +00001624 llvm::Value *LocalAddr = 0;
1625 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
Adrian Prantl0f6df002013-03-29 19:20:35 +00001626 // Allocate a stack slot to let the debug info survive the RA.
Adrian Prantl51936dd2013-03-14 17:53:33 +00001627 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1628 D.getName() + ".addr");
1629 Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity());
1630 LValue lv = MakeAddrLValue(Alloc, Ty, getContext().getDeclAlign(&D));
1631 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
1632 LocalAddr = Builder.CreateLoad(Alloc);
1633 }
John McCall147d0212011-02-22 22:38:33 +00001634
1635 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregorb0eea8b2012-10-23 20:05:01 +00001636 if (CGM.getCodeGenOpts().getDebugInfo()
1637 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001638 DI->setLocation(D.getLocation());
Adrian Prantl51936dd2013-03-14 17:53:33 +00001639 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, LocalAddr, Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001640 }
John McCall147d0212011-02-22 22:38:33 +00001641 }
1642
1643 return;
1644 }
1645 }
1646
Chris Lattner53621a52007-06-13 20:44:40 +00001647 llvm::Value *DeclPtr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001648 bool DoStore = false;
1649 bool IsScalar = hasScalarEvaluationKind(Ty);
1650 CharUnits Align = getContext().getDeclAlign(&D);
1651 // If we already have a pointer to the argument, reuse the input pointer.
1652 if (ArgIsPointer) {
1653 assert(isa<llvm::PointerType>(Arg->getType()));
Chris Lattner53621a52007-06-13 20:44:40 +00001654 DeclPtr = Arg;
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001655 // Push a destructor cleanup for this parameter if the ABI requires it.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001656 if (!IsScalar &&
Reid Kleckner739756c2013-12-04 19:23:12 +00001657 getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001658 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
1659 if (RD && RD->hasNonTrivialDestructor())
1660 pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001661 }
Chris Lattner53621a52007-06-13 20:44:40 +00001662 } else {
Daniel Dunbar3d33fab2010-02-08 22:53:07 +00001663 // Otherwise, create a temporary to hold the value.
Eli Friedmaneadd3e82011-11-03 20:31:28 +00001664 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1665 D.getName() + ".addr");
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001666 Alloc->setAlignment(Align.getQuantity());
Eli Friedmaneadd3e82011-11-03 20:31:28 +00001667 DeclPtr = Alloc;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001668 DoStore = true;
1669 }
Mike Stump11289f42009-09-09 15:08:12 +00001670
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001671 LValue lv = MakeAddrLValue(DeclPtr, Ty, Align);
1672 if (IsScalar) {
John McCall31168b02011-06-15 23:02:42 +00001673 Qualifiers qs = Ty.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00001674 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1675 // We honor __attribute__((ns_consumed)) for types with lifetime.
1676 // For __strong, it's handled by just skipping the initial retain;
1677 // otherwise we have to balance out the initial +1 with an extra
1678 // cleanup to do the release at the end of the function.
1679 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1680
1681 // 'self' is always formally __strong, but if this is not an
1682 // init method then we don't want to retain it.
John McCalld4631322011-06-17 06:42:21 +00001683 if (D.isARCPseudoStrong()) {
John McCall31168b02011-06-15 23:02:42 +00001684 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1685 assert(&D == method->getSelfDecl());
John McCalld4631322011-06-17 06:42:21 +00001686 assert(lt == Qualifiers::OCL_Strong);
1687 assert(qs.hasConst());
John McCall31168b02011-06-15 23:02:42 +00001688 assert(method->getMethodFamily() != OMF_init);
John McCall10123692011-06-15 23:40:09 +00001689 (void) method;
John McCall31168b02011-06-15 23:02:42 +00001690 lt = Qualifiers::OCL_ExplicitNone;
1691 }
1692
1693 if (lt == Qualifiers::OCL_Strong) {
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001694 if (!isConsumed) {
1695 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1696 // use objc_storeStrong(&dest, value) for retaining the
1697 // object. But first, store a null into 'dest' because
1698 // objc_storeStrong attempts to release its old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001699 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001700 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
1701 EmitARCStoreStrongCall(lv.getAddress(), Arg, true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001702 DoStore = false;
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001703 }
1704 else
John McCall31168b02011-06-15 23:02:42 +00001705 // Don't use objc_retainBlock for block pointers, because we
1706 // don't want to Block_copy something just because we got it
1707 // as a parameter.
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001708 Arg = EmitARCRetainNonBlock(Arg);
1709 }
John McCall31168b02011-06-15 23:02:42 +00001710 } else {
1711 // Push the cleanup for a consumed parameter.
John McCallcdda29c2013-03-13 03:10:54 +00001712 if (isConsumed) {
1713 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1714 ? ARCPreciseLifetime : ARCImpreciseLifetime);
1715 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg,
1716 precise);
1717 }
John McCall31168b02011-06-15 23:02:42 +00001718
1719 if (lt == Qualifiers::OCL_Weak) {
1720 EmitARCInitWeak(DeclPtr, Arg);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001721 DoStore = false; // The weak init is a store, no need to do two.
John McCall31168b02011-06-15 23:02:42 +00001722 }
1723 }
1724
1725 // Enter the cleanup scope.
1726 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1727 }
Chris Lattner53621a52007-06-13 20:44:40 +00001728 }
1729
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001730 // Store the initial value into the alloca.
1731 if (DoStore)
1732 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
1733
Chris Lattner53621a52007-06-13 20:44:40 +00001734 llvm::Value *&DMEntry = LocalDeclMap[&D];
1735 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
1736 DMEntry = DeclPtr;
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001737
1738 // Emit debug info for param declaration.
Alexey Samsonov74a38682012-05-04 07:39:27 +00001739 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregorb0eea8b2012-10-23 20:05:01 +00001740 if (CGM.getCodeGenOpts().getDebugInfo()
1741 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001742 DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
1743 }
1744 }
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001745
1746 if (D.hasAttr<AnnotateAttr>())
1747 EmitVarAnnotations(&D, DeclPtr);
Chris Lattner53621a52007-06-13 20:44:40 +00001748}