blob: 12c520792fc1be78ee46337d3d78941470c7309c [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 =
David Majnemer27d69db2014-04-28 22:17:59 +0000129 CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000130
David Majnemer27d69db2014-04-28 22:17:59 +0000131 // FIXME: We need to force the emission/use of a guard variable for
132 // some variables even if we can constant-evaluate them because
133 // we can't guarantee every translation unit will constant-evaluate them.
Eric Christopher31ab1302011-08-23 22:38:00 +0000134
John McCall1c9c3fd2010-10-15 04:57:14 +0000135 return EmitStaticVarDecl(D, Linkage);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000136 }
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000137
138 if (D.hasExternalStorage())
Lauro Ramos Venanciobada8d42008-02-16 22:30:38 +0000139 // Don't emit it now, allow it to be emitted lazily on its first use.
140 return;
Daniel Dunbar0ca16602009-04-14 02:25:56 +0000141
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000142 if (D.getStorageClass() == SC_OpenCLWorkGroupLocal)
143 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
144
145 assert(D.hasLocalStorage());
146 return EmitAutoVarDecl(D);
Chris Lattner03df1222007-06-02 04:53:11 +0000147}
148
Chris Lattnere99c1102009-12-05 08:22:11 +0000149static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D,
150 const char *Separator) {
151 CodeGenModule &CGM = CGF.CGM;
Eric Christopher31ab1302011-08-23 22:38:00 +0000152
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000153 if (CGF.getLangOpts().CPlusPlus)
154 return CGM.getMangledName(&D).str();
155
156 StringRef ContextName;
Fariborz Jahanian3a4ea9a2010-11-30 23:07:14 +0000157 if (!CGF.CurFuncDecl) {
158 // Better be in a block declared in global scope.
159 const NamedDecl *ND = cast<NamedDecl>(&D);
160 const DeclContext *DC = ND->getDeclContext();
Alp Toker0e64e0d2014-06-03 02:13:57 +0000161 if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
162 ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
Fariborz Jahanian3a4ea9a2010-11-30 23:07:14 +0000163 else
David Blaikie83d382b2011-09-23 05:06:16 +0000164 llvm_unreachable("Unknown context for block static var decl");
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000165 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl))
166 ContextName = CGM.getMangledName(FD);
167 else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
Chris Lattnere99c1102009-12-05 08:22:11 +0000168 ContextName = CGF.CurFn->getName();
169 else
David Blaikie83d382b2011-09-23 05:06:16 +0000170 llvm_unreachable("Unknown context for static var decl");
Eric Christopher31ab1302011-08-23 22:38:00 +0000171
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000172 return ContextName.str() + Separator + D.getNameAsString();
Chris Lattnere99c1102009-12-05 08:22:11 +0000173}
174
Eli Benderskycb399432014-03-24 22:05:38 +0000175llvm::Constant *
John McCall1c9c3fd2010-10-15 04:57:14 +0000176CodeGenFunction::CreateStaticVarDecl(const VarDecl &D,
177 const char *Separator,
178 llvm::GlobalValue::LinkageTypes Linkage) {
Chris Lattnerfc4379f2008-04-06 23:10:54 +0000179 QualType Ty = D.getType();
Eli Friedmana682d392008-02-15 12:20:59 +0000180 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begemanfaae0812008-04-19 04:17:09 +0000181
Benjamin Kramerddbb2b82011-11-20 21:05:04 +0000182 // Use the label if the variable is renamed with the asm-label extension.
183 std::string Name;
Benjamin Kramer5642e192011-11-21 15:47:23 +0000184 if (D.hasAttr<AsmLabelAttr>())
185 Name = CGM.getMangledName(&D);
186 else
Benjamin Kramerddbb2b82011-11-20 21:05:04 +0000187 Name = GetStaticDeclName(*this, D, Separator);
Nate Begemanfaae0812008-04-19 04:17:09 +0000188
Chris Lattner2192fe52011-07-18 04:24:23 +0000189 llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
Peter Collingbourneee0502d2012-08-28 20:37:10 +0000190 unsigned AddrSpace =
191 CGM.GetGlobalVarAddressSpace(&D, CGM.getContext().getTargetAddressSpace(Ty));
Anders Carlssone33eed52009-09-26 18:16:06 +0000192 llvm::GlobalVariable *GV =
193 new llvm::GlobalVariable(CGM.getModule(), LTy,
194 Ty.isConstant(getContext()), Linkage,
Craig Topper8a13c412014-05-21 05:09:00 +0000195 CGM.EmitNullConstant(D.getType()), Name, nullptr,
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000196 llvm::GlobalVariable::NotThreadLocal,
Peter Collingbourneee0502d2012-08-28 20:37:10 +0000197 AddrSpace);
Ken Dyck160146e2010-01-27 17:10:57 +0000198 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Eli Friedman40a4bec2013-06-17 21:51:45 +0000199 CGM.setGlobalVisibility(GV, &D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000200
Richard Smithfd3834f2013-04-13 02:43:54 +0000201 if (D.getTLSKind())
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000202 CGM.setTLSMode(GV, D);
203
Eli Benderskycb399432014-03-24 22:05:38 +0000204 // Make sure the result is of the correct type.
205 unsigned ExpectedAddrSpace = CGM.getContext().getTargetAddressSpace(Ty);
206 if (AddrSpace != ExpectedAddrSpace) {
207 llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace);
208 return llvm::ConstantExpr::getAddrSpaceCast(GV, PTy);
209 }
210
Anders Carlssone33eed52009-09-26 18:16:06 +0000211 return GV;
Daniel Dunbar22a87f92009-02-25 19:24:29 +0000212}
213
Richard Smith6331c402012-02-13 22:16:19 +0000214/// hasNontrivialDestruction - Determine whether a type's destruction is
215/// non-trivial. If so, and the variable uses static initialization, we must
216/// register its destructor to run on exit.
217static bool hasNontrivialDestruction(QualType T) {
218 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
219 return RD && !RD->hasTrivialDestructor();
220}
221
Chandler Carruth84537952012-03-30 19:44:53 +0000222/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
223/// global variable that has already been created for it. If the initializer
224/// has a different type than GV does, this may free GV and return a different
225/// one. Otherwise it just returns GV.
226llvm::GlobalVariable *
John McCall1c9c3fd2010-10-15 04:57:14 +0000227CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
Chandler Carruth84537952012-03-30 19:44:53 +0000228 llvm::GlobalVariable *GV) {
229 llvm::Constant *Init = CGM.EmitConstantInit(D, this);
John McCall70013b62010-07-15 23:40:35 +0000230
Chris Lattnere99c1102009-12-05 08:22:11 +0000231 // If constant emission failed, then this should be a C++ static
232 // initializer.
Chandler Carruth84537952012-03-30 19:44:53 +0000233 if (!Init) {
Richard Smith9c6890a2012-11-01 22:30:59 +0000234 if (!getLangOpts().CPlusPlus)
Chris Lattnere99c1102009-12-05 08:22:11 +0000235 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
John McCall68ff0372010-09-08 01:44:27 +0000236 else if (Builder.GetInsertBlock()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000237 // Since we have a static initializer, this global variable can't
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000238 // be constant.
Chandler Carruth84537952012-03-30 19:44:53 +0000239 GV->setConstant(false);
John McCall68ff0372010-09-08 01:44:27 +0000240
Chandler Carruth84537952012-03-30 19:44:53 +0000241 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000242 }
Chandler Carruth84537952012-03-30 19:44:53 +0000243 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000244 }
John McCall70013b62010-07-15 23:40:35 +0000245
Chris Lattnere99c1102009-12-05 08:22:11 +0000246 // The initializer may differ in type from the global. Rewrite
247 // the global to match the initializer. (We have to do this
248 // because some types, like unions, can't be completely represented
249 // in the LLVM type system.)
Chandler Carruth84537952012-03-30 19:44:53 +0000250 if (GV->getType()->getElementType() != Init->getType()) {
251 llvm::GlobalVariable *OldGV = GV;
252
253 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
254 OldGV->isConstant(),
255 OldGV->getLinkage(), Init, "",
256 /*InsertBefore*/ OldGV,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +0000257 OldGV->getThreadLocalMode(),
Chandler Carruth84537952012-03-30 19:44:53 +0000258 CGM.getContext().getTargetAddressSpace(D.getType()));
259 GV->setVisibility(OldGV->getVisibility());
Eric Christopher31ab1302011-08-23 22:38:00 +0000260
Chris Lattnere99c1102009-12-05 08:22:11 +0000261 // Steal the name of the old global
Chandler Carruth84537952012-03-30 19:44:53 +0000262 GV->takeName(OldGV);
Eric Christopher31ab1302011-08-23 22:38:00 +0000263
Chris Lattnere99c1102009-12-05 08:22:11 +0000264 // Replace all uses of the old global with the new global
Chandler Carruth84537952012-03-30 19:44:53 +0000265 llvm::Constant *NewPtrForOldDecl =
266 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
267 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eric Christopher31ab1302011-08-23 22:38:00 +0000268
Chris Lattnere99c1102009-12-05 08:22:11 +0000269 // Erase the old global, since it is no longer used.
Chandler Carruth84537952012-03-30 19:44:53 +0000270 OldGV->eraseFromParent();
Chris Lattnere99c1102009-12-05 08:22:11 +0000271 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000272
Chandler Carruth84537952012-03-30 19:44:53 +0000273 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
274 GV->setInitializer(Init);
Richard Smith6331c402012-02-13 22:16:19 +0000275
276 if (hasNontrivialDestruction(D.getType())) {
277 // We have a constant initializer, but a nontrivial destructor. We still
278 // need to perform a guarded "initialization" in order to register the
Richard Smithe070fd22012-02-17 06:48:11 +0000279 // destructor.
Chandler Carruth84537952012-03-30 19:44:53 +0000280 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
Richard Smith6331c402012-02-13 22:16:19 +0000281 }
282
Chandler Carruth84537952012-03-30 19:44:53 +0000283 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000284}
285
John McCall1c9c3fd2010-10-15 04:57:14 +0000286void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000287 llvm::GlobalValue::LinkageTypes Linkage) {
Chandler Carruth84537952012-03-30 19:44:53 +0000288 llvm::Value *&DMEntry = LocalDeclMap[&D];
Craig Topper8a13c412014-05-21 05:09:00 +0000289 assert(!DMEntry && "Decl already exists in localdeclmap!");
Mike Stump11289f42009-09-09 15:08:12 +0000290
John McCallb88a5662012-03-30 21:00:39 +0000291 // Check to see if we already have a global variable for this
292 // declaration. This can happen when double-emitting function
293 // bodies, e.g. with complete and base constructors.
294 llvm::Constant *addr =
295 CGM.getStaticLocalDeclAddress(&D);
296
Eli Benderskycb399432014-03-24 22:05:38 +0000297 if (!addr)
298 addr = CreateStaticVarDecl(D, ".", Linkage);
Daniel Dunbara374e602009-02-25 19:45:19 +0000299
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000300 // Store into LocalDeclMap before generating initializer to handle
301 // circular references.
John McCallb88a5662012-03-30 21:00:39 +0000302 DMEntry = addr;
303 CGM.setStaticLocalDeclAddress(&D, addr);
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000304
John McCall4a39ab82010-05-04 20:45:42 +0000305 // We can't have a VLA here, but we can have a pointer to a VLA,
306 // even though that doesn't really make any sense.
Eli Friedmanbc633be2009-04-20 03:54:15 +0000307 // Make sure to evaluate VLA bounds now so that we have them for later.
308 if (D.getType()->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000309 EmitVariablyModifiedType(D.getType());
Eric Christopher31ab1302011-08-23 22:38:00 +0000310
John McCallb88a5662012-03-30 21:00:39 +0000311 // Save the type in case adding the initializer forces a type change.
312 llvm::Type *expectedType = addr->getType();
Eli Friedmanbc633be2009-04-20 03:54:15 +0000313
Eli Benderskycb399432014-03-24 22:05:38 +0000314 llvm::GlobalVariable *var =
315 cast<llvm::GlobalVariable>(addr->stripPointerCasts());
Chris Lattnere99c1102009-12-05 08:22:11 +0000316 // If this value has an initializer, emit it.
317 if (D.getInit())
John McCallb88a5662012-03-30 21:00:39 +0000318 var = AddInitializerToStaticVarDecl(D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000319
John McCallb88a5662012-03-30 21:00:39 +0000320 var->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Chris Lattner4d941092010-03-10 23:59:59 +0000321
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000322 if (D.hasAttr<AnnotateAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000323 CGM.AddGlobalAnnotations(&D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000324
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000325 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000326 var->setSection(SA->getName());
Mike Stump11289f42009-09-09 15:08:12 +0000327
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000328 if (D.hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +0000329 CGM.addUsedGlobal(var);
Daniel Dunbar128a1382009-02-13 22:08:43 +0000330
Chandler Carruth84537952012-03-30 19:44:53 +0000331 // We may have to cast the constant because of the initializer
332 // mismatch above.
333 //
334 // FIXME: It is really dangerous to store this in the map; if anyone
335 // RAUW's the GV uses of this constant will be invalid.
Eli Benderskycb399432014-03-24 22:05:38 +0000336 llvm::Constant *castedAddr =
337 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
John McCallb88a5662012-03-30 21:00:39 +0000338 DMEntry = castedAddr;
339 CGM.setStaticLocalDeclAddress(&D, castedAddr);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000340
341 // Emit global variable debug descriptor for static vars.
Anders Carlsson63784f42009-02-13 08:11:52 +0000342 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov74a38682012-05-04 07:39:27 +0000343 if (DI &&
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000344 CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
Daniel Dunbarb9fd9022008-10-17 16:15:48 +0000345 DI->setLocation(D.getLocation());
John McCallb88a5662012-03-30 21:00:39 +0000346 DI->EmitGlobalVariable(var, &D);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000347 }
Anders Carlssonf94cd1f2007-10-17 00:52:43 +0000348}
Mike Stump11289f42009-09-09 15:08:12 +0000349
John McCall2b7fc382010-07-13 20:32:21 +0000350namespace {
John McCall82fe67b2011-07-09 01:37:26 +0000351 struct DestroyObject : EHScopeStack::Cleanup {
352 DestroyObject(llvm::Value *addr, QualType type,
John McCall178360e2011-07-11 08:38:19 +0000353 CodeGenFunction::Destroyer *destroyer,
354 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +0000355 : addr(addr), type(type), destroyer(destroyer),
John McCall178360e2011-07-11 08:38:19 +0000356 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall2b7fc382010-07-13 20:32:21 +0000357
John McCall82fe67b2011-07-09 01:37:26 +0000358 llvm::Value *addr;
359 QualType type;
Peter Collingbourne1425b452012-01-26 03:33:36 +0000360 CodeGenFunction::Destroyer *destroyer;
John McCall178360e2011-07-11 08:38:19 +0000361 bool useEHCleanupForArray;
John McCall2b7fc382010-07-13 20:32:21 +0000362
Craig Topper4f12f102014-03-12 06:41:41 +0000363 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +0000364 // Don't use an EH cleanup recursively from an EH cleanup.
John McCall30317fd2011-07-12 20:27:29 +0000365 bool useEHCleanupForArray =
366 flags.isForNormalCleanup() && this->useEHCleanupForArray;
John McCall178360e2011-07-11 08:38:19 +0000367
368 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
John McCall2b7fc382010-07-13 20:32:21 +0000369 }
370 };
371
John McCall82fe67b2011-07-09 01:37:26 +0000372 struct DestroyNRVOVariable : EHScopeStack::Cleanup {
373 DestroyNRVOVariable(llvm::Value *addr,
374 const CXXDestructorDecl *Dtor,
375 llvm::Value *NRVOFlag)
376 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
John McCall2b7fc382010-07-13 20:32:21 +0000377
378 const CXXDestructorDecl *Dtor;
379 llvm::Value *NRVOFlag;
380 llvm::Value *Loc;
381
Craig Topper4f12f102014-03-12 06:41:41 +0000382 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall2b7fc382010-07-13 20:32:21 +0000383 // Along the exceptions path we always execute the dtor.
John McCall30317fd2011-07-12 20:27:29 +0000384 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
John McCall2b7fc382010-07-13 20:32:21 +0000385
Craig Topper8a13c412014-05-21 05:09:00 +0000386 llvm::BasicBlock *SkipDtorBB = nullptr;
John McCall2b7fc382010-07-13 20:32:21 +0000387 if (NRVO) {
388 // If we exited via NRVO, we skip the destructor call.
389 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
390 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
391 llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
392 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
393 CGF.EmitBlock(RunDtorBB);
394 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000395
John McCall2b7fc382010-07-13 20:32:21 +0000396 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +0000397 /*ForVirtualBase=*/false,
398 /*Delegating=*/false,
399 Loc);
John McCall2b7fc382010-07-13 20:32:21 +0000400
401 if (NRVO) CGF.EmitBlock(SkipDtorBB);
402 }
403 };
John McCall2b7fc382010-07-13 20:32:21 +0000404
John McCallcda666c2010-07-21 07:22:38 +0000405 struct CallStackRestore : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000406 llvm::Value *Stack;
407 CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000408 void Emit(CodeGenFunction &CGF, Flags flags) override {
Benjamin Kramer76399eb2011-09-27 21:06:10 +0000409 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
John McCalla464ff92010-07-21 06:13:08 +0000410 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
411 CGF.Builder.CreateCall(F, V);
412 }
413 };
414
John McCall1bd25562011-06-24 23:21:27 +0000415 struct ExtendGCLifetime : EHScopeStack::Cleanup {
416 const VarDecl &Var;
417 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
418
Craig Topper4f12f102014-03-12 06:41:41 +0000419 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1bd25562011-06-24 23:21:27 +0000420 // Compute the address of the local variable, in case it's a
421 // byref or something.
John McCall113bee02012-03-10 09:33:50 +0000422 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
423 Var.getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +0000424 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
425 SourceLocation());
John McCall1bd25562011-06-24 23:21:27 +0000426 CGF.EmitExtendGCLifetime(value);
427 }
428 };
429
John McCallcda666c2010-07-21 07:22:38 +0000430 struct CallCleanupFunction : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000431 llvm::Constant *CleanupFn;
432 const CGFunctionInfo &FnInfo;
John McCalla464ff92010-07-21 06:13:08 +0000433 const VarDecl &Var;
Eric Christopher31ab1302011-08-23 22:38:00 +0000434
John McCalla464ff92010-07-21 06:13:08 +0000435 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCallc533cb72011-02-22 06:44:22 +0000436 const VarDecl *Var)
437 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalla464ff92010-07-21 06:13:08 +0000438
Craig Topper4f12f102014-03-12 06:41:41 +0000439 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall113bee02012-03-10 09:33:50 +0000440 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
441 Var.getType(), VK_LValue, SourceLocation());
John McCallc533cb72011-02-22 06:44:22 +0000442 // Compute the address of the local variable, in case it's a byref
443 // or something.
444 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
445
John McCalla464ff92010-07-21 06:13:08 +0000446 // In some cases, the type of the function argument will be different from
447 // the type of the pointer. An example of this is
448 // void f(void* arg);
449 // __attribute__((cleanup(f))) void *g;
450 //
451 // To fix this we insert a bitcast here.
452 QualType ArgTy = FnInfo.arg_begin()->type;
453 llvm::Value *Arg =
454 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
455
456 CallArgList Args;
Eli Friedman43dca6a2011-05-02 17:57:46 +0000457 Args.add(RValue::get(Arg),
458 CGF.getContext().getPointerType(Var.getType()));
John McCalla464ff92010-07-21 06:13:08 +0000459 CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
460 }
461 };
Nadav Rotem1da30942013-03-23 06:43:35 +0000462
463 /// A cleanup to call @llvm.lifetime.end.
464 class CallLifetimeEnd : public EHScopeStack::Cleanup {
465 llvm::Value *Addr;
466 llvm::Value *Size;
467 public:
468 CallLifetimeEnd(llvm::Value *addr, llvm::Value *size)
469 : Addr(addr), Size(size) {}
470
Craig Topper4f12f102014-03-12 06:41:41 +0000471 void Emit(CodeGenFunction &CGF, Flags flags) override {
Nadav Rotem1da30942013-03-23 06:43:35 +0000472 llvm::Value *castAddr = CGF.Builder.CreateBitCast(Addr, CGF.Int8PtrTy);
473 CGF.Builder.CreateCall2(CGF.CGM.getLLVMLifetimeEndFn(),
474 Size, castAddr)
475 ->setDoesNotThrow();
476 }
477 };
John McCalla464ff92010-07-21 06:13:08 +0000478}
479
John McCall31168b02011-06-15 23:02:42 +0000480/// EmitAutoVarWithLifetime - Does the setup required for an automatic
481/// variable with lifetime.
482static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
483 llvm::Value *addr,
484 Qualifiers::ObjCLifetime lifetime) {
485 switch (lifetime) {
486 case Qualifiers::OCL_None:
487 llvm_unreachable("present but none");
488
489 case Qualifiers::OCL_ExplicitNone:
490 // nothing to do
491 break;
492
493 case Qualifiers::OCL_Strong: {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000494 CodeGenFunction::Destroyer *destroyer =
John McCall4bd0fb12011-07-12 16:41:08 +0000495 (var.hasAttr<ObjCPreciseLifetimeAttr>()
496 ? CodeGenFunction::destroyARCStrongPrecise
497 : CodeGenFunction::destroyARCStrongImprecise);
498
499 CleanupKind cleanupKind = CGF.getARCCleanupKind();
500 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
501 cleanupKind & EHCleanup);
John McCall31168b02011-06-15 23:02:42 +0000502 break;
503 }
504 case Qualifiers::OCL_Autoreleasing:
505 // nothing to do
506 break;
Eric Christopher31ab1302011-08-23 22:38:00 +0000507
John McCall31168b02011-06-15 23:02:42 +0000508 case Qualifiers::OCL_Weak:
509 // __weak objects always get EH cleanups; otherwise, exceptions
510 // could cause really nasty crashes instead of mere leaks.
John McCall4bd0fb12011-07-12 16:41:08 +0000511 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
512 CodeGenFunction::destroyARCWeak,
513 /*useEHCleanup*/ true);
John McCall31168b02011-06-15 23:02:42 +0000514 break;
515 }
516}
517
518static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
519 if (const Expr *e = dyn_cast<Expr>(s)) {
520 // Skip the most common kinds of expressions that make
521 // hierarchy-walking expensive.
522 s = e = e->IgnoreParenCasts();
523
524 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
525 return (ref->getDecl() == &var);
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000526 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
527 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +0000528 for (const auto &I : block->captures()) {
529 if (I.getVariable() == &var)
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000530 return true;
531 }
532 }
John McCall31168b02011-06-15 23:02:42 +0000533 }
534
535 for (Stmt::const_child_range children = s->children(); children; ++children)
Fariborz Jahanian326701e2011-06-29 20:00:16 +0000536 // children might be null; as in missing decl or conditional of an if-stmt.
537 if ((*children) && isAccessedBy(var, *children))
John McCall31168b02011-06-15 23:02:42 +0000538 return true;
539
540 return false;
541}
542
543static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
544 if (!decl) return false;
545 if (!isa<VarDecl>(decl)) return false;
546 const VarDecl *var = cast<VarDecl>(decl);
547 return isAccessedBy(*var, e);
548}
549
John McCall1553b192011-06-16 04:16:24 +0000550static void drillIntoBlockVariable(CodeGenFunction &CGF,
551 LValue &lvalue,
552 const VarDecl *var) {
553 lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var));
554}
555
John McCall31168b02011-06-15 23:02:42 +0000556void CodeGenFunction::EmitScalarInit(const Expr *init,
557 const ValueDecl *D,
John McCall1553b192011-06-16 04:16:24 +0000558 LValue lvalue,
559 bool capturedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000560 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +0000561 if (!lifetime) {
562 llvm::Value *value = EmitScalarExpr(init);
John McCall1553b192011-06-16 04:16:24 +0000563 if (capturedByInit)
564 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Chisnallfa35df62012-01-16 17:27:18 +0000565 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
John McCall31168b02011-06-15 23:02:42 +0000566 return;
567 }
Fariborz Jahaniana5a469e2014-03-14 15:40:54 +0000568
569 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
570 init = DIE->getExpr();
571
John McCall31168b02011-06-15 23:02:42 +0000572 // If we're emitting a value with lifetime, we have to do the
573 // initialization *before* we leave the cleanup scopes.
John McCall08ef4662011-11-10 08:15:53 +0000574 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
575 enterFullExpression(ewc);
John McCall31168b02011-06-15 23:02:42 +0000576 init = ewc->getSubExpr();
John McCall08ef4662011-11-10 08:15:53 +0000577 }
578 CodeGenFunction::RunCleanupsScope Scope(*this);
John McCall31168b02011-06-15 23:02:42 +0000579
580 // We have to maintain the illusion that the variable is
581 // zero-initialized. If the variable might be accessed in its
582 // initializer, zero-initialize before running the initializer, then
583 // actually perform the initialization with an assign.
584 bool accessedByInit = false;
585 if (lifetime != Qualifiers::OCL_ExplicitNone)
John McCallb726a552011-07-28 07:23:35 +0000586 accessedByInit = (capturedByInit || isAccessedBy(D, init));
John McCall31168b02011-06-15 23:02:42 +0000587 if (accessedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000588 LValue tempLV = lvalue;
John McCall31168b02011-06-15 23:02:42 +0000589 // Drill down to the __block object if necessary.
John McCall31168b02011-06-15 23:02:42 +0000590 if (capturedByInit) {
591 // We can use a simple GEP for this because it can't have been
592 // moved yet.
John McCall1553b192011-06-16 04:16:24 +0000593 tempLV.setAddress(Builder.CreateStructGEP(tempLV.getAddress(),
594 getByRefValueLLVMField(cast<VarDecl>(D))));
John McCall31168b02011-06-15 23:02:42 +0000595 }
596
Chris Lattner2192fe52011-07-18 04:24:23 +0000597 llvm::PointerType *ty
John McCall1553b192011-06-16 04:16:24 +0000598 = cast<llvm::PointerType>(tempLV.getAddress()->getType());
John McCall31168b02011-06-15 23:02:42 +0000599 ty = cast<llvm::PointerType>(ty->getElementType());
600
601 llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
Eric Christopher31ab1302011-08-23 22:38:00 +0000602
John McCall31168b02011-06-15 23:02:42 +0000603 // If __weak, we want to use a barrier under certain conditions.
604 if (lifetime == Qualifiers::OCL_Weak)
John McCall1553b192011-06-16 04:16:24 +0000605 EmitARCInitWeak(tempLV.getAddress(), zero);
John McCall31168b02011-06-15 23:02:42 +0000606
607 // Otherwise just do a simple store.
608 else
David Chisnallfa35df62012-01-16 17:27:18 +0000609 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000610 }
611
612 // Emit the initializer.
Craig Topper8a13c412014-05-21 05:09:00 +0000613 llvm::Value *value = nullptr;
John McCall31168b02011-06-15 23:02:42 +0000614
615 switch (lifetime) {
616 case Qualifiers::OCL_None:
617 llvm_unreachable("present but none");
618
619 case Qualifiers::OCL_ExplicitNone:
620 // nothing to do
621 value = EmitScalarExpr(init);
622 break;
623
624 case Qualifiers::OCL_Strong: {
625 value = EmitARCRetainScalarExpr(init);
626 break;
627 }
628
629 case Qualifiers::OCL_Weak: {
630 // No way to optimize a producing initializer into this. It's not
631 // worth optimizing for, because the value will immediately
632 // disappear in the common case.
633 value = EmitScalarExpr(init);
634
John McCall1553b192011-06-16 04:16:24 +0000635 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000636 if (accessedByInit)
John McCall1553b192011-06-16 04:16:24 +0000637 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +0000638 else
John McCall1553b192011-06-16 04:16:24 +0000639 EmitARCInitWeak(lvalue.getAddress(), value);
John McCall31168b02011-06-15 23:02:42 +0000640 return;
641 }
642
643 case Qualifiers::OCL_Autoreleasing:
644 value = EmitARCRetainAutoreleaseScalarExpr(init);
645 break;
646 }
647
John McCall1553b192011-06-16 04:16:24 +0000648 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000649
650 // If the variable might have been accessed by its initializer, we
651 // might have to initialize with a barrier. We have to do this for
652 // both __weak and __strong, but __weak got filtered out above.
653 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000654 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
David Chisnallfa35df62012-01-16 17:27:18 +0000655 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCallcdda29c2013-03-13 03:10:54 +0000656 EmitARCRelease(oldValue, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +0000657 return;
658 }
659
David Chisnallfa35df62012-01-16 17:27:18 +0000660 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000661}
Chris Lattnerb85025f2010-12-01 02:05:19 +0000662
John McCalld4631322011-06-17 06:42:21 +0000663/// EmitScalarInit - Initialize the given lvalue with the given object.
664void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
665 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
666 if (!lifetime)
David Chisnallfa35df62012-01-16 17:27:18 +0000667 return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
John McCalld4631322011-06-17 06:42:21 +0000668
669 switch (lifetime) {
670 case Qualifiers::OCL_None:
671 llvm_unreachable("present but none");
672
673 case Qualifiers::OCL_ExplicitNone:
674 // nothing to do
675 break;
676
677 case Qualifiers::OCL_Strong:
678 init = EmitARCRetain(lvalue.getType(), init);
679 break;
680
681 case Qualifiers::OCL_Weak:
682 // Initialize and then skip the primitive store.
683 EmitARCInitWeak(lvalue.getAddress(), init);
684 return;
685
686 case Qualifiers::OCL_Autoreleasing:
687 init = EmitARCRetainAutorelease(lvalue.getType(), init);
688 break;
689 }
690
David Chisnallfa35df62012-01-16 17:27:18 +0000691 EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
John McCalld4631322011-06-17 06:42:21 +0000692}
693
Chris Lattnerb85025f2010-12-01 02:05:19 +0000694/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
695/// non-zero parts of the specified initializer with equal or fewer than
696/// NumStores scalar stores.
697static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
698 unsigned &NumStores) {
Chris Lattnere6af8862010-12-02 01:58:41 +0000699 // Zero and Undef never requires any extra stores.
700 if (isa<llvm::ConstantAggregateZero>(Init) ||
701 isa<llvm::ConstantPointerNull>(Init) ||
702 isa<llvm::UndefValue>(Init))
703 return true;
704 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
705 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
706 isa<llvm::ConstantExpr>(Init))
707 return Init->isNullValue() || NumStores--;
708
709 // See if we can emit each element.
710 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
711 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
712 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
713 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
714 return false;
715 }
716 return true;
717 }
Chris Lattner236b3572012-01-31 04:36:19 +0000718
719 if (llvm::ConstantDataSequential *CDS =
720 dyn_cast<llvm::ConstantDataSequential>(Init)) {
721 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
722 llvm::Constant *Elt = CDS->getElementAsConstant(i);
723 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
724 return false;
725 }
726 return true;
727 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000728
Chris Lattnerb85025f2010-12-01 02:05:19 +0000729 // Anything else is hard and scary.
730 return false;
731}
732
733/// emitStoresForInitAfterMemset - For inits that
734/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
735/// stores that would be required.
736static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
John McCallc533cb72011-02-22 06:44:22 +0000737 bool isVolatile, CGBuilderTy &Builder) {
Benjamin Kramer29f9a002012-08-27 22:07:02 +0000738 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
739 "called emitStoresForInitAfterMemset for zero or undef value.");
Eric Christopher31ab1302011-08-23 22:38:00 +0000740
Chris Lattnere6af8862010-12-02 01:58:41 +0000741 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
742 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
743 isa<llvm::ConstantExpr>(Init)) {
Chris Lattner236b3572012-01-31 04:36:19 +0000744 Builder.CreateStore(Init, Loc, isVolatile);
745 return;
746 }
747
748 if (llvm::ConstantDataSequential *CDS =
749 dyn_cast<llvm::ConstantDataSequential>(Init)) {
750 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
751 llvm::Constant *Elt = CDS->getElementAsConstant(i);
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000752
753 // If necessary, get a pointer to the element and emit it.
754 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
755 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
756 isVolatile, Builder);
Chris Lattner236b3572012-01-31 04:36:19 +0000757 }
Chris Lattnere6af8862010-12-02 01:58:41 +0000758 return;
759 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000760
Chris Lattnere6af8862010-12-02 01:58:41 +0000761 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
762 "Unknown value type!");
Eric Christopher31ab1302011-08-23 22:38:00 +0000763
Chris Lattnere6af8862010-12-02 01:58:41 +0000764 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
765 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000766
767 // If necessary, get a pointer to the element and emit it.
768 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
769 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
770 isVolatile, Builder);
Chris Lattnere6af8862010-12-02 01:58:41 +0000771 }
Chris Lattnerb85025f2010-12-01 02:05:19 +0000772}
773
774
775/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
776/// plus some stores to initialize a local variable instead of using a memcpy
777/// from a constant global. It is beneficial to use memset if the global is all
778/// zeros, or mostly zeros and large.
779static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
780 uint64_t GlobalSize) {
781 // If a global is all zeros, always use a memset.
782 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
783
Chris Lattnerb85025f2010-12-01 02:05:19 +0000784 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
785 // do it if it will require 6 or fewer scalar stores.
786 // TODO: Should budget depends on the size? Avoiding a large global warrants
787 // plopping in more stores.
788 unsigned StoreBudget = 6;
789 uint64_t SizeLimit = 32;
Eric Christopher31ab1302011-08-23 22:38:00 +0000790
791 return GlobalSize > SizeLimit &&
Chris Lattnerb85025f2010-12-01 02:05:19 +0000792 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
793}
794
Nadav Rotem1da30942013-03-23 06:43:35 +0000795/// Should we use the LLVM lifetime intrinsics for the given local variable?
796static bool shouldUseLifetimeMarkers(CodeGenFunction &CGF, const VarDecl &D,
797 unsigned Size) {
798 // For now, only in optimized builds.
799 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0)
800 return false;
801
802 // Limit the size of marked objects to 32 bytes. We don't want to increase
803 // compile time by marking tiny objects.
804 unsigned SizeThreshold = 32;
805
806 return Size > SizeThreshold;
807}
808
Chris Lattnerb85025f2010-12-01 02:05:19 +0000809
Nick Lewycky8a7d90b2010-12-30 20:21:55 +0000810/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Chris Lattner03df1222007-06-02 04:53:11 +0000811/// variable declaration with auto, register, or no storage class specifier.
Chris Lattnerb781dc792008-05-08 05:58:21 +0000812/// These turn into simple stack objects, or GlobalValues depending on target.
John McCallc533cb72011-02-22 06:44:22 +0000813void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
814 AutoVarEmission emission = EmitAutoVarAlloca(D);
815 EmitAutoVarInit(emission);
816 EmitAutoVarCleanups(emission);
817}
Chris Lattner03df1222007-06-02 04:53:11 +0000818
John McCallc533cb72011-02-22 06:44:22 +0000819/// EmitAutoVarAlloca - Emit the alloca and debug information for a
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000820/// local variable. Does not emit initialization or destruction.
John McCallc533cb72011-02-22 06:44:22 +0000821CodeGenFunction::AutoVarEmission
822CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
823 QualType Ty = D.getType();
824
825 AutoVarEmission emission(D);
826
827 bool isByRef = D.hasAttr<BlocksAttr>();
828 emission.IsByRef = isByRef;
829
830 CharUnits alignment = getContext().getDeclAlign(&D);
831 emission.Alignment = alignment;
832
John McCall23c29fe2011-06-24 21:55:10 +0000833 // If the type is variably-modified, emit all the VLA sizes for it.
834 if (Ty->isVariablyModifiedType())
835 EmitVariablyModifiedType(Ty);
836
Chris Lattner03df1222007-06-02 04:53:11 +0000837 llvm::Value *DeclPtr;
Eli Friedmana682d392008-02-15 12:20:59 +0000838 if (Ty->isConstantSizeType()) {
Rafael Espindola609f5d92013-03-26 18:41:47 +0000839 bool NRVO = getLangOpts().ElideConstructors &&
840 D.isNRVOVariable();
John McCallc533cb72011-02-22 06:44:22 +0000841
Richard Smith2bcde3a2013-06-02 00:09:52 +0000842 // If this value is an array or struct with a statically determinable
843 // constant initializer, there are optimizations we can do.
Rafael Espindola609f5d92013-03-26 18:41:47 +0000844 //
845 // TODO: We should constant-evaluate the initializer of any variable,
846 // as long as it is initialized by a constant expression. Currently,
847 // isConstantInitializer produces wrong answers for structs with
848 // reference or bitfield members, and a few other cases, and checking
849 // for POD-ness protects us from some of these.
Richard Smith2bcde3a2013-06-02 00:09:52 +0000850 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
851 (D.isConstexpr() ||
852 ((Ty.isPODType(getContext()) ||
853 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
854 D.getInit()->isConstantInitializer(getContext(), false)))) {
John McCallc533cb72011-02-22 06:44:22 +0000855
Rafael Espindola609f5d92013-03-26 18:41:47 +0000856 // If the variable's a const type, and it's neither an NRVO
857 // candidate nor a __block variable and has no mutable members,
858 // emit it as a global instead.
859 if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
860 CGM.isTypeConstant(Ty, true)) {
861 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCallc533cb72011-02-22 06:44:22 +0000862
Craig Topper8a13c412014-05-21 05:09:00 +0000863 emission.Address = nullptr; // signal this condition to later callbacks
Rafael Espindola609f5d92013-03-26 18:41:47 +0000864 assert(emission.wasEmittedAsGlobal());
865 return emission;
Tanya Lattnerf9d41df2009-11-04 01:18:09 +0000866 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000867
Rafael Espindola609f5d92013-03-26 18:41:47 +0000868 // Otherwise, tell the initialization code that we're in this case.
869 emission.IsConstantAggregate = true;
870 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000871
Rafael Espindola609f5d92013-03-26 18:41:47 +0000872 // A normal fixed sized variable becomes an alloca in the entry block,
873 // unless it's an NRVO variable.
874 llvm::Type *LTy = ConvertTypeForMem(Ty);
Eric Christopher31ab1302011-08-23 22:38:00 +0000875
Rafael Espindola609f5d92013-03-26 18:41:47 +0000876 if (NRVO) {
877 // The named return value optimization: allocate this variable in the
878 // return slot, so that we can elide the copy when returning this
879 // variable (C++0x [class.copy]p34).
880 DeclPtr = ReturnValue;
Eric Christopher31ab1302011-08-23 22:38:00 +0000881
Rafael Espindola609f5d92013-03-26 18:41:47 +0000882 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
883 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
884 // Create a flag that is used to indicate when the NRVO was applied
885 // to this variable. Set it to zero to indicate that NRVO was not
886 // applied.
887 llvm::Value *Zero = Builder.getFalse();
888 llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
889 EnsureInsertPoint();
890 Builder.CreateStore(Zero, NRVOFlag);
Eric Christopher31ab1302011-08-23 22:38:00 +0000891
Rafael Espindola609f5d92013-03-26 18:41:47 +0000892 // Record the NRVO flag for this variable.
893 NRVOFlags[&D] = NRVOFlag;
894 emission.NRVOFlag = NRVOFlag;
Nadav Rotem1da30942013-03-23 06:43:35 +0000895 }
Douglas Gregor290c93e2010-05-15 06:46:45 +0000896 }
Chris Lattnerb781dc792008-05-08 05:58:21 +0000897 } else {
Rafael Espindola609f5d92013-03-26 18:41:47 +0000898 if (isByRef)
899 LTy = BuildByRefType(&D);
900
901 llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
902 Alloc->setName(D.getName());
903
904 CharUnits allocaAlignment = alignment;
905 if (isByRef)
906 allocaAlignment = std::max(allocaAlignment,
John McCallc8e01702013-04-16 22:48:15 +0000907 getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0)));
Rafael Espindola609f5d92013-03-26 18:41:47 +0000908 Alloc->setAlignment(allocaAlignment.getQuantity());
909 DeclPtr = Alloc;
910
911 // Emit a lifetime intrinsic if meaningful. There's no point
912 // in doing this if we don't have a valid insertion point (?).
913 uint64_t size = CGM.getDataLayout().getTypeAllocSize(LTy);
914 if (HaveInsertPoint() && shouldUseLifetimeMarkers(*this, D, size)) {
915 llvm::Value *sizeV = llvm::ConstantInt::get(Int64Ty, size);
916
917 emission.SizeForLifetimeMarkers = sizeV;
918 llvm::Value *castAddr = Builder.CreateBitCast(Alloc, Int8PtrTy);
919 Builder.CreateCall2(CGM.getLLVMLifetimeStartFn(), sizeV, castAddr)
920 ->setDoesNotThrow();
921 } else {
922 assert(!emission.useLifetimeMarkers());
923 }
Chris Lattnerb781dc792008-05-08 05:58:21 +0000924 }
Chris Lattner03df1222007-06-02 04:53:11 +0000925 } else {
Daniel Dunbarb6adc432009-07-19 06:58:07 +0000926 EnsureInsertPoint();
927
Anders Carlsson15949b32009-02-09 20:41:50 +0000928 if (!DidCallStackSave) {
Anders Carlsson30032882008-12-12 07:38:43 +0000929 // Save the stack.
John McCallad7c5c12011-02-08 08:22:06 +0000930 llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
Mike Stump11289f42009-09-09 15:08:12 +0000931
Anders Carlsson30032882008-12-12 07:38:43 +0000932 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
933 llvm::Value *V = Builder.CreateCall(F);
Mike Stump11289f42009-09-09 15:08:12 +0000934
Anders Carlsson30032882008-12-12 07:38:43 +0000935 Builder.CreateStore(V, Stack);
Anders Carlsson15949b32009-02-09 20:41:50 +0000936
937 DidCallStackSave = true;
Mike Stump11289f42009-09-09 15:08:12 +0000938
John McCalla464ff92010-07-21 06:13:08 +0000939 // Push a cleanup block and restore the stack there.
John McCalle4df6c82011-01-28 08:37:24 +0000940 // FIXME: in general circumstances, this should be an EH cleanup.
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000941 pushStackRestore(NormalCleanup, Stack);
Anders Carlsson30032882008-12-12 07:38:43 +0000942 }
Mike Stump11289f42009-09-09 15:08:12 +0000943
John McCall23c29fe2011-06-24 21:55:10 +0000944 llvm::Value *elementCount;
945 QualType elementType;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000946 std::tie(elementCount, elementType) = getVLASize(Ty);
Anders Carlsson30032882008-12-12 07:38:43 +0000947
Chris Lattner2192fe52011-07-18 04:24:23 +0000948 llvm::Type *llvmTy = ConvertTypeForMem(elementType);
Anders Carlsson30032882008-12-12 07:38:43 +0000949
950 // Allocate memory for the array.
John McCall23c29fe2011-06-24 21:55:10 +0000951 llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
952 vla->setAlignment(alignment.getQuantity());
Anders Carlssone33eed52009-09-26 18:16:06 +0000953
John McCall23c29fe2011-06-24 21:55:10 +0000954 DeclPtr = vla;
Chris Lattner03df1222007-06-02 04:53:11 +0000955 }
Eli Friedmanf4084702008-12-20 23:11:59 +0000956
Chris Lattner03df1222007-06-02 04:53:11 +0000957 llvm::Value *&DMEntry = LocalDeclMap[&D];
Craig Topper8a13c412014-05-21 05:09:00 +0000958 assert(!DMEntry && "Decl already exists in localdeclmap!");
Chris Lattner03df1222007-06-02 04:53:11 +0000959 DMEntry = DeclPtr;
John McCallc533cb72011-02-22 06:44:22 +0000960 emission.Address = DeclPtr;
Sanjiv Gupta18de6242008-05-30 10:30:31 +0000961
962 // Emit debug info for local var declaration.
Devang Patel887e2152011-06-03 19:21:47 +0000963 if (HaveInsertPoint())
964 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000965 if (CGM.getCodeGenOpts().getDebugInfo()
966 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +0000967 DI->setLocation(D.getLocation());
Rafael Espindola609f5d92013-03-26 18:41:47 +0000968 DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +0000969 }
Devang Patel887e2152011-06-03 19:21:47 +0000970 }
Sanjiv Gupta18de6242008-05-30 10:30:31 +0000971
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000972 if (D.hasAttr<AnnotateAttr>())
973 EmitVarAnnotations(&D, emission.Address);
974
John McCallc533cb72011-02-22 06:44:22 +0000975 return emission;
976}
977
978/// Determines whether the given __block variable is potentially
979/// captured by the given expression.
980static bool isCapturedBy(const VarDecl &var, const Expr *e) {
981 // Skip the most common kinds of expressions that make
982 // hierarchy-walking expensive.
983 e = e->IgnoreParenCasts();
984
985 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
986 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +0000987 for (const auto &I : block->captures()) {
988 if (I.getVariable() == &var)
John McCallc533cb72011-02-22 06:44:22 +0000989 return true;
990 }
991
992 // No need to walk into the subexpressions.
993 return false;
994 }
995
Fariborz Jahanian797f1e22011-08-23 16:47:15 +0000996 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
997 const CompoundStmt *CS = SE->getSubStmt();
Aaron Ballmanc7e4e212014-03-17 14:19:37 +0000998 for (const auto *BI : CS->body())
999 if (const auto *E = dyn_cast<Expr>(BI)) {
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001000 if (isCapturedBy(var, E))
1001 return true;
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001002 }
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001003 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001004 // special case declarations
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001005 for (const auto *I : DS->decls()) {
1006 if (const auto *VD = dyn_cast<VarDecl>((I))) {
1007 const Expr *Init = VD->getInit();
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001008 if (Init && isCapturedBy(var, Init))
1009 return true;
1010 }
1011 }
1012 }
1013 else
1014 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1015 // Later, provide code to poke into statements for capture analysis.
1016 return true;
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001017 return false;
1018 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001019
John McCallc533cb72011-02-22 06:44:22 +00001020 for (Stmt::const_child_range children = e->children(); children; ++children)
1021 if (isCapturedBy(var, cast<Expr>(*children)))
1022 return true;
1023
1024 return false;
1025}
1026
Douglas Gregor82e1af22011-07-01 21:08:19 +00001027/// \brief Determine whether the given initializer is trivial in the sense
1028/// that it requires no code to be generated.
1029static bool isTrivialInitializer(const Expr *Init) {
1030 if (!Init)
1031 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001032
Douglas Gregor82e1af22011-07-01 21:08:19 +00001033 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1034 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1035 if (Constructor->isTrivial() &&
1036 Constructor->isDefaultConstructor() &&
1037 !Construct->requiresZeroInitialization())
1038 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001039
Douglas Gregor82e1af22011-07-01 21:08:19 +00001040 return false;
1041}
John McCallc533cb72011-02-22 06:44:22 +00001042void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001043 assert(emission.Variable && "emission was not valid!");
1044
John McCallc533cb72011-02-22 06:44:22 +00001045 // If this was emitted as a global constant, we're done.
1046 if (emission.wasEmittedAsGlobal()) return;
1047
John McCall9e2e22f2011-02-22 07:16:58 +00001048 const VarDecl &D = *emission.Variable;
John McCallc533cb72011-02-22 06:44:22 +00001049 QualType type = D.getType();
1050
Chris Lattner07eb7332007-07-12 00:39:48 +00001051 // If this local has an initializer, emit it now.
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001052 const Expr *Init = D.getInit();
1053
1054 // If we are at an unreachable point, we don't need to emit the initializer
1055 // unless it contains a label.
1056 if (!HaveInsertPoint()) {
John McCallc533cb72011-02-22 06:44:22 +00001057 if (!Init || !ContainsLabel(Init)) return;
1058 EnsureInsertPoint();
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001059 }
1060
John McCall73064872011-03-31 01:59:53 +00001061 // Initialize the structure of a __block variable.
1062 if (emission.IsByRef)
1063 emitByrefStructureInit(emission);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001064
Douglas Gregor82e1af22011-07-01 21:08:19 +00001065 if (isTrivialInitializer(Init))
1066 return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001067
John McCall73064872011-03-31 01:59:53 +00001068 CharUnits alignment = emission.Alignment;
1069
John McCallc533cb72011-02-22 06:44:22 +00001070 // Check whether this is a byref variable that's potentially
1071 // captured and moved by its own initializer. If so, we'll need to
1072 // emit the initializer first, then copy into the variable.
1073 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1074
1075 llvm::Value *Loc =
1076 capturedByInit ? emission.Address : emission.getObjectAddress(*this);
1077
Craig Topper8a13c412014-05-21 05:09:00 +00001078 llvm::Constant *constant = nullptr;
Richard Smith2bcde3a2013-06-02 00:09:52 +00001079 if (emission.IsConstantAggregate || D.isConstexpr()) {
Richard Smithfddd3842011-12-30 21:15:51 +00001080 assert(!capturedByInit && "constant init contains a capturing block?");
Richard Smithdafff942012-01-14 04:30:29 +00001081 constant = CGM.EmitConstantInit(D, this);
Richard Smithfddd3842011-12-30 21:15:51 +00001082 }
1083
1084 if (!constant) {
Eli Friedmana0544d62011-12-03 04:14:32 +00001085 LValue lv = MakeAddrLValue(Loc, type, alignment);
John McCall1553b192011-06-16 04:16:24 +00001086 lv.setNonGC(true);
1087 return EmitExprAsInit(Init, &D, lv, capturedByInit);
1088 }
John McCall91ca10f2011-03-08 09:11:50 +00001089
Richard Smith2bcde3a2013-06-02 00:09:52 +00001090 if (!emission.IsConstantAggregate) {
1091 // For simple scalar/complex initialization, store the value directly.
1092 LValue lv = MakeAddrLValue(Loc, type, alignment);
1093 lv.setNonGC(true);
1094 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1095 }
1096
John McCallc533cb72011-02-22 06:44:22 +00001097 // If this is a simple aggregate initialization, we can optimize it
1098 // in various ways.
John McCall91ca10f2011-03-08 09:11:50 +00001099 bool isVolatile = type.isVolatileQualified();
John McCallc533cb72011-02-22 06:44:22 +00001100
John McCall91ca10f2011-03-08 09:11:50 +00001101 llvm::Value *SizeVal =
Eric Christopher31ab1302011-08-23 22:38:00 +00001102 llvm::ConstantInt::get(IntPtrTy,
John McCall91ca10f2011-03-08 09:11:50 +00001103 getContext().getTypeSizeInChars(type).getQuantity());
John McCallc533cb72011-02-22 06:44:22 +00001104
Chris Lattner2192fe52011-07-18 04:24:23 +00001105 llvm::Type *BP = Int8PtrTy;
John McCall91ca10f2011-03-08 09:11:50 +00001106 if (Loc->getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001107 Loc = Builder.CreateBitCast(Loc, BP);
Mon P Wangcc2ab0c2010-04-04 03:10:52 +00001108
John McCall91ca10f2011-03-08 09:11:50 +00001109 // If the initializer is all or mostly zeros, codegen with memset then do
1110 // a few stores afterward.
Eric Christopher31ab1302011-08-23 22:38:00 +00001111 if (shouldUseMemSetPlusStoresToInitialize(constant,
Micah Villmowdd31ca12012-10-08 16:25:52 +00001112 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
John McCall91ca10f2011-03-08 09:11:50 +00001113 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1114 alignment.getQuantity(), isVolatile);
Benjamin Kramer29f9a002012-08-27 22:07:02 +00001115 // Zero and undef don't require a stores.
1116 if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
John McCall91ca10f2011-03-08 09:11:50 +00001117 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
1118 emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001119 }
John McCall91ca10f2011-03-08 09:11:50 +00001120 } else {
Eric Christopher31ab1302011-08-23 22:38:00 +00001121 // Otherwise, create a temporary global with the initializer then
John McCall91ca10f2011-03-08 09:11:50 +00001122 // memcpy from the global to the alloca.
1123 std::string Name = GetStaticDeclName(*this, D, ".");
1124 llvm::GlobalVariable *GV =
1125 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
Eric Christopherb58b3e82011-08-24 00:33:55 +00001126 llvm::GlobalValue::PrivateLinkage,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001127 constant, Name);
John McCall91ca10f2011-03-08 09:11:50 +00001128 GV->setAlignment(alignment.getQuantity());
Eli Friedmanb8578422011-05-27 22:32:55 +00001129 GV->setUnnamedAddr(true);
Eric Christopher31ab1302011-08-23 22:38:00 +00001130
John McCall91ca10f2011-03-08 09:11:50 +00001131 llvm::Value *SrcPtr = GV;
1132 if (SrcPtr->getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001133 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
John McCall91ca10f2011-03-08 09:11:50 +00001134
1135 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
1136 isVolatile);
1137 }
1138}
1139
1140/// Emit an expression as an initializer for a variable at the given
1141/// location. The expression is not necessarily the normal
1142/// initializer for the variable, and the address is not necessarily
1143/// its normal location.
1144///
1145/// \param init the initializing expression
1146/// \param var the variable to act as if we're initializing
1147/// \param loc the address to initialize; its type is a pointer
1148/// to the LLVM mapping of the variable's type
1149/// \param alignment the alignment of the address
1150/// \param capturedByInit true if the variable is a __block variable
1151/// whose address is potentially changed by the initializer
1152void CodeGenFunction::EmitExprAsInit(const Expr *init,
John McCall31168b02011-06-15 23:02:42 +00001153 const ValueDecl *D,
John McCall1553b192011-06-16 04:16:24 +00001154 LValue lvalue,
John McCall91ca10f2011-03-08 09:11:50 +00001155 bool capturedByInit) {
John McCall31168b02011-06-15 23:02:42 +00001156 QualType type = D->getType();
John McCall91ca10f2011-03-08 09:11:50 +00001157
1158 if (type->isReferenceType()) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +00001159 RValue rvalue = EmitReferenceBindingToExpr(init);
Eric Christopher31ab1302011-08-23 22:38:00 +00001160 if (capturedByInit)
John McCall1553b192011-06-16 04:16:24 +00001161 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Chisnallfa35df62012-01-16 17:27:18 +00001162 EmitStoreThroughLValue(rvalue, lvalue, true);
John McCall47fb9502013-03-07 21:37:08 +00001163 return;
1164 }
1165 switch (getEvaluationKind(type)) {
1166 case TEK_Scalar:
John McCall1553b192011-06-16 04:16:24 +00001167 EmitScalarInit(init, D, lvalue, capturedByInit);
John McCall47fb9502013-03-07 21:37:08 +00001168 return;
1169 case TEK_Complex: {
John McCall91ca10f2011-03-08 09:11:50 +00001170 ComplexPairTy complex = EmitComplexExpr(init);
John McCall1553b192011-06-16 04:16:24 +00001171 if (capturedByInit)
1172 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall47fb9502013-03-07 21:37:08 +00001173 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
1174 return;
1175 }
1176 case TEK_Aggregate:
John McCalla8ec7eb2013-03-07 21:37:17 +00001177 if (type->isAtomicType()) {
1178 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1179 } else {
1180 // TODO: how can we delay here if D is captured by its initializer?
1181 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001182 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001183 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001184 AggValueSlot::IsNotAliased));
John McCalla8ec7eb2013-03-07 21:37:17 +00001185 }
John McCall47fb9502013-03-07 21:37:08 +00001186 return;
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001187 }
John McCall47fb9502013-03-07 21:37:08 +00001188 llvm_unreachable("bad evaluation kind");
John McCallc533cb72011-02-22 06:44:22 +00001189}
John McCallbd309292010-07-06 01:34:17 +00001190
John McCall82fe67b2011-07-09 01:37:26 +00001191/// Enter a destroy cleanup for the given local variable.
1192void CodeGenFunction::emitAutoVarTypeCleanup(
1193 const CodeGenFunction::AutoVarEmission &emission,
1194 QualType::DestructionKind dtorKind) {
1195 assert(dtorKind != QualType::DK_none);
1196
1197 // Note that for __block variables, we want to destroy the
1198 // original stack object, not the possibly forwarded object.
1199 llvm::Value *addr = emission.getObjectAddress(*this);
1200
1201 const VarDecl *var = emission.Variable;
1202 QualType type = var->getType();
1203
1204 CleanupKind cleanupKind = NormalAndEHCleanup;
Craig Topper8a13c412014-05-21 05:09:00 +00001205 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall82fe67b2011-07-09 01:37:26 +00001206
1207 switch (dtorKind) {
1208 case QualType::DK_none:
1209 llvm_unreachable("no cleanup for trivially-destructible variable");
1210
1211 case QualType::DK_cxx_destructor:
1212 // If there's an NRVO flag on the emission, we need a different
1213 // cleanup.
1214 if (emission.NRVOFlag) {
1215 assert(!type->isArrayType());
1216 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1217 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor,
1218 emission.NRVOFlag);
1219 return;
1220 }
1221 break;
1222
1223 case QualType::DK_objc_strong_lifetime:
1224 // Suppress cleanups for pseudo-strong variables.
1225 if (var->isARCPseudoStrong()) return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001226
John McCall82fe67b2011-07-09 01:37:26 +00001227 // Otherwise, consider whether to use an EH cleanup or not.
1228 cleanupKind = getARCCleanupKind();
1229
1230 // Use the imprecise destroyer by default.
1231 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1232 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1233 break;
1234
1235 case QualType::DK_objc_weak_lifetime:
1236 break;
1237 }
1238
1239 // If we haven't chosen a more specific destroyer, use the default.
Peter Collingbourne1425b452012-01-26 03:33:36 +00001240 if (!destroyer) destroyer = getDestroyer(dtorKind);
John McCall178360e2011-07-11 08:38:19 +00001241
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001242 // Use an EH cleanup in array destructors iff the destructor itself
John McCall178360e2011-07-11 08:38:19 +00001243 // is being pushed as an EH cleanup.
1244 bool useEHCleanup = (cleanupKind & EHCleanup);
1245 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1246 useEHCleanup);
John McCall82fe67b2011-07-09 01:37:26 +00001247}
1248
John McCallc533cb72011-02-22 06:44:22 +00001249void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001250 assert(emission.Variable && "emission was not valid!");
1251
John McCallc533cb72011-02-22 06:44:22 +00001252 // If this was emitted as a global constant, we're done.
1253 if (emission.wasEmittedAsGlobal()) return;
1254
John McCall8c38d352012-04-13 18:44:05 +00001255 // If we don't have an insertion point, we're done. Sema prevents
1256 // us from jumping into any of these scopes anyway.
1257 if (!HaveInsertPoint()) return;
1258
John McCall9e2e22f2011-02-22 07:16:58 +00001259 const VarDecl &D = *emission.Variable;
John McCallc533cb72011-02-22 06:44:22 +00001260
Nadav Rotem1da30942013-03-23 06:43:35 +00001261 // Make sure we call @llvm.lifetime.end. This needs to happen
1262 // *last*, so the cleanup needs to be pushed *first*.
1263 if (emission.useLifetimeMarkers()) {
1264 EHStack.pushCleanup<CallLifetimeEnd>(NormalCleanup,
1265 emission.getAllocatedAddress(),
1266 emission.getSizeForLifetimeMarkers());
1267 }
1268
John McCall82fe67b2011-07-09 01:37:26 +00001269 // Check the type for a cleanup.
1270 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1271 emitAutoVarTypeCleanup(emission, dtorKind);
John McCall31168b02011-06-15 23:02:42 +00001272
John McCall1bd25562011-06-24 23:21:27 +00001273 // In GC mode, honor objc_precise_lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001274 if (getLangOpts().getGC() != LangOptions::NonGC &&
John McCall1bd25562011-06-24 23:21:27 +00001275 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1276 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1277 }
1278
John McCallc533cb72011-02-22 06:44:22 +00001279 // Handle the cleanup attribute.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001280 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001281 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001282
John McCallc533cb72011-02-22 06:44:22 +00001283 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001284 assert(F && "Could not find function!");
Mike Stump11289f42009-09-09 15:08:12 +00001285
John McCalla729c622012-02-17 03:33:10 +00001286 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
John McCallc533cb72011-02-22 06:44:22 +00001287 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001288 }
Mike Stump626aecc2009-03-05 01:23:13 +00001289
John McCallc533cb72011-02-22 06:44:22 +00001290 // If this is a block variable, call _Block_object_destroy
1291 // (on the unforwarded address).
John McCall73064872011-03-31 01:59:53 +00001292 if (emission.IsByRef)
1293 enterByrefCleanup(emission);
Chris Lattner03df1222007-06-02 04:53:11 +00001294}
Chris Lattner53621a52007-06-13 20:44:40 +00001295
Peter Collingbourne1425b452012-01-26 03:33:36 +00001296CodeGenFunction::Destroyer *
John McCall82fe67b2011-07-09 01:37:26 +00001297CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1298 switch (kind) {
1299 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
John McCallc2f00012011-07-09 09:09:00 +00001300 case QualType::DK_cxx_destructor:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001301 return destroyCXXObject;
John McCallc2f00012011-07-09 09:09:00 +00001302 case QualType::DK_objc_strong_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001303 return destroyARCStrongPrecise;
John McCallc2f00012011-07-09 09:09:00 +00001304 case QualType::DK_objc_weak_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001305 return destroyARCWeak;
John McCall82fe67b2011-07-09 01:37:26 +00001306 }
Matt Beaumont-Gay934bbf52012-01-27 00:46:27 +00001307 llvm_unreachable("Unknown DestructionKind");
John McCall82fe67b2011-07-09 01:37:26 +00001308}
1309
John McCall12cc42a2013-02-01 05:11:40 +00001310/// pushEHDestroy - Push the standard destructor for the given type as
1311/// an EH-only cleanup.
1312void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
1313 llvm::Value *addr, QualType type) {
1314 assert(dtorKind && "cannot push destructor for trivial type");
1315 assert(needsEHCleanup(dtorKind));
1316
1317 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1318}
1319
1320/// pushDestroy - Push the standard destructor for the given type as
1321/// at least a normal cleanup.
John McCall4bd0fb12011-07-12 16:41:08 +00001322void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
1323 llvm::Value *addr, QualType type) {
1324 assert(dtorKind && "cannot push destructor for trivial type");
1325
1326 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1327 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1328 cleanupKind & EHCleanup);
1329}
1330
John McCall82fe67b2011-07-09 01:37:26 +00001331void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *addr,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001332 QualType type, Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001333 bool useEHCleanupForArray) {
John McCall4bd0fb12011-07-12 16:41:08 +00001334 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1335 destroyer, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001336}
1337
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001338void CodeGenFunction::pushStackRestore(CleanupKind Kind, llvm::Value *SPMem) {
1339 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
1340}
1341
Richard Smith736a9472013-06-12 20:42:33 +00001342void CodeGenFunction::pushLifetimeExtendedDestroy(
1343 CleanupKind cleanupKind, llvm::Value *addr, QualType type,
1344 Destroyer *destroyer, bool useEHCleanupForArray) {
1345 assert(!isInConditionalBranch() &&
1346 "performing lifetime extension from within conditional");
1347
1348 // Push an EH-only cleanup for the object now.
1349 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1350 // around in case a temporary's destructor throws an exception.
1351 if (cleanupKind & EHCleanup)
1352 EHStack.pushCleanup<DestroyObject>(
1353 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1354 destroyer, useEHCleanupForArray);
1355
1356 // Remember that we need to push a full cleanup for the object at the
1357 // end of the full-expression.
1358 pushCleanupAfterFullExpr<DestroyObject>(
1359 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1360}
1361
John McCall178360e2011-07-11 08:38:19 +00001362/// emitDestroy - Immediately perform the destruction of the given
1363/// object.
1364///
1365/// \param addr - the address of the object; a type*
1366/// \param type - the type of the object; if an array type, all
1367/// objects are destroyed in reverse order
1368/// \param destroyer - the function to call to destroy individual
1369/// elements
1370/// \param useEHCleanupForArray - whether an EH cleanup should be
1371/// used when destroying array elements, in case one of the
1372/// destructions throws an exception
John McCall82fe67b2011-07-09 01:37:26 +00001373void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001374 Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001375 bool useEHCleanupForArray) {
John McCall82fe67b2011-07-09 01:37:26 +00001376 const ArrayType *arrayType = getContext().getAsArrayType(type);
1377 if (!arrayType)
1378 return destroyer(*this, addr, type);
1379
1380 llvm::Value *begin = addr;
1381 llvm::Value *length = emitArrayLength(arrayType, type, begin);
John McCall97eab0a2011-07-13 08:09:46 +00001382
1383 // Normally we have to check whether the array is zero-length.
1384 bool checkZeroLength = true;
1385
1386 // But if the array length is constant, we can suppress that.
1387 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1388 // ...and if it's constant zero, we can just skip the entire thing.
1389 if (constLength->isZero()) return;
1390 checkZeroLength = false;
1391 }
1392
John McCall82fe67b2011-07-09 01:37:26 +00001393 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
John McCall97eab0a2011-07-13 08:09:46 +00001394 emitArrayDestroy(begin, end, type, destroyer,
1395 checkZeroLength, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001396}
1397
John McCall178360e2011-07-11 08:38:19 +00001398/// emitArrayDestroy - Destroys all the elements of the given array,
1399/// beginning from last to first. The array cannot be zero-length.
1400///
1401/// \param begin - a type* denoting the first element of the array
1402/// \param end - a type* denoting one past the end of the array
1403/// \param type - the element type of the array
1404/// \param destroyer - the function to call to destroy elements
1405/// \param useEHCleanup - whether to push an EH cleanup to destroy
1406/// the remaining elements in case the destruction of a single
1407/// element throws
John McCall82fe67b2011-07-09 01:37:26 +00001408void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1409 llvm::Value *end,
1410 QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001411 Destroyer *destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001412 bool checkZeroLength,
John McCall178360e2011-07-11 08:38:19 +00001413 bool useEHCleanup) {
John McCall82fe67b2011-07-09 01:37:26 +00001414 assert(!type->isArrayType());
1415
1416 // The basic structure here is a do-while loop, because we don't
1417 // need to check for the zero-element case.
1418 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1419 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1420
John McCall97eab0a2011-07-13 08:09:46 +00001421 if (checkZeroLength) {
1422 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1423 "arraydestroy.isempty");
1424 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1425 }
1426
John McCall82fe67b2011-07-09 01:37:26 +00001427 // Enter the loop body, making that address the current address.
1428 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1429 EmitBlock(bodyBB);
1430 llvm::PHINode *elementPast =
1431 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1432 elementPast->addIncoming(end, entryBB);
1433
1434 // Shift the address back by one element.
1435 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1436 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1437 "arraydestroy.element");
1438
John McCall178360e2011-07-11 08:38:19 +00001439 if (useEHCleanup)
1440 pushRegularPartialArrayCleanup(begin, element, type, destroyer);
1441
John McCall82fe67b2011-07-09 01:37:26 +00001442 // Perform the actual destruction there.
1443 destroyer(*this, element, type);
1444
John McCall178360e2011-07-11 08:38:19 +00001445 if (useEHCleanup)
1446 PopCleanupBlock();
1447
John McCall82fe67b2011-07-09 01:37:26 +00001448 // Check whether we've reached the end.
1449 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1450 Builder.CreateCondBr(done, doneBB, bodyBB);
1451 elementPast->addIncoming(element, Builder.GetInsertBlock());
1452
1453 // Done.
1454 EmitBlock(doneBB);
1455}
1456
John McCall178360e2011-07-11 08:38:19 +00001457/// Perform partial array destruction as if in an EH cleanup. Unlike
1458/// emitArrayDestroy, the element type here may still be an array type.
John McCall178360e2011-07-11 08:38:19 +00001459static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1460 llvm::Value *begin, llvm::Value *end,
1461 QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001462 CodeGenFunction::Destroyer *destroyer) {
John McCall178360e2011-07-11 08:38:19 +00001463 // If the element type is itself an array, drill down.
John McCall97eab0a2011-07-13 08:09:46 +00001464 unsigned arrayDepth = 0;
John McCall178360e2011-07-11 08:38:19 +00001465 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1466 // VLAs don't require a GEP index to walk into.
1467 if (!isa<VariableArrayType>(arrayType))
John McCall97eab0a2011-07-13 08:09:46 +00001468 arrayDepth++;
John McCall178360e2011-07-11 08:38:19 +00001469 type = arrayType->getElementType();
1470 }
John McCall97eab0a2011-07-13 08:09:46 +00001471
1472 if (arrayDepth) {
1473 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, arrayDepth+1);
1474
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001475 SmallVector<llvm::Value*,4> gepIndices(arrayDepth, zero);
Jay Foad040dd822011-07-22 08:16:57 +00001476 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1477 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
John McCall178360e2011-07-11 08:38:19 +00001478 }
1479
John McCall97eab0a2011-07-13 08:09:46 +00001480 // Destroy the array. We don't ever need an EH cleanup because we
1481 // assume that we're in an EH cleanup ourselves, so a throwing
1482 // destructor causes an immediate terminate.
1483 CGF.emitArrayDestroy(begin, end, type, destroyer,
1484 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
John McCall178360e2011-07-11 08:38:19 +00001485}
1486
John McCall82fe67b2011-07-09 01:37:26 +00001487namespace {
John McCall178360e2011-07-11 08:38:19 +00001488 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1489 /// array destroy where the end pointer is regularly determined and
1490 /// does not need to be loaded from a local.
1491 class RegularPartialArrayDestroy : public EHScopeStack::Cleanup {
1492 llvm::Value *ArrayBegin;
1493 llvm::Value *ArrayEnd;
1494 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001495 CodeGenFunction::Destroyer *Destroyer;
John McCall178360e2011-07-11 08:38:19 +00001496 public:
1497 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
1498 QualType elementType,
1499 CodeGenFunction::Destroyer *destroyer)
1500 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
Peter Collingbourne1425b452012-01-26 03:33:36 +00001501 ElementType(elementType), Destroyer(destroyer) {}
John McCall178360e2011-07-11 08:38:19 +00001502
Craig Topper4f12f102014-03-12 06:41:41 +00001503 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +00001504 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
1505 ElementType, Destroyer);
1506 }
1507 };
1508
1509 /// IrregularPartialArrayDestroy - a cleanup which performs a
1510 /// partial array destroy where the end pointer is irregularly
1511 /// determined and must be loaded from a local.
1512 class IrregularPartialArrayDestroy : public EHScopeStack::Cleanup {
John McCall82fe67b2011-07-09 01:37:26 +00001513 llvm::Value *ArrayBegin;
1514 llvm::Value *ArrayEndPointer;
1515 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001516 CodeGenFunction::Destroyer *Destroyer;
John McCall82fe67b2011-07-09 01:37:26 +00001517 public:
John McCall178360e2011-07-11 08:38:19 +00001518 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
1519 llvm::Value *arrayEndPointer,
1520 QualType elementType,
1521 CodeGenFunction::Destroyer *destroyer)
John McCall82fe67b2011-07-09 01:37:26 +00001522 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
Peter Collingbourne1425b452012-01-26 03:33:36 +00001523 ElementType(elementType), Destroyer(destroyer) {}
John McCall82fe67b2011-07-09 01:37:26 +00001524
Craig Topper4f12f102014-03-12 06:41:41 +00001525 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall82fe67b2011-07-09 01:37:26 +00001526 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
John McCall178360e2011-07-11 08:38:19 +00001527 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
1528 ElementType, Destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001529 }
1530 };
1531}
1532
John McCall178360e2011-07-11 08:38:19 +00001533/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
John McCall82fe67b2011-07-09 01:37:26 +00001534/// already-constructed elements of the given array. The cleanup
John McCall178360e2011-07-11 08:38:19 +00001535/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001536///
John McCall82fe67b2011-07-09 01:37:26 +00001537/// \param elementType - the immediate element type of the array;
1538/// possibly still an array type
John McCall4bd0fb12011-07-12 16:41:08 +00001539void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
John McCall178360e2011-07-11 08:38:19 +00001540 llvm::Value *arrayEndPointer,
1541 QualType elementType,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001542 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001543 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1544 arrayBegin, arrayEndPointer,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001545 elementType, destroyer);
John McCall178360e2011-07-11 08:38:19 +00001546}
1547
1548/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1549/// already-constructed elements of the given array. The cleanup
1550/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001551///
John McCall178360e2011-07-11 08:38:19 +00001552/// \param elementType - the immediate element type of the array;
1553/// possibly still an array type
John McCall178360e2011-07-11 08:38:19 +00001554void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1555 llvm::Value *arrayEnd,
1556 QualType elementType,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001557 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001558 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
John McCall178360e2011-07-11 08:38:19 +00001559 arrayBegin, arrayEnd,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001560 elementType, destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001561}
1562
Nadav Rotem1da30942013-03-23 06:43:35 +00001563/// Lazily declare the @llvm.lifetime.start intrinsic.
1564llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
1565 if (LifetimeStartFn) return LifetimeStartFn;
1566 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1567 llvm::Intrinsic::lifetime_start);
1568 return LifetimeStartFn;
1569}
1570
1571/// Lazily declare the @llvm.lifetime.end intrinsic.
1572llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
1573 if (LifetimeEndFn) return LifetimeEndFn;
1574 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1575 llvm::Intrinsic::lifetime_end);
1576 return LifetimeEndFn;
1577}
1578
John McCall31168b02011-06-15 23:02:42 +00001579namespace {
1580 /// A cleanup to perform a release of an object at the end of a
1581 /// function. This is used to balance out the incoming +1 of a
1582 /// ns_consumed argument when we can't reasonably do that just by
1583 /// not doing the initial retain for a __block argument.
1584 struct ConsumeARCParameter : EHScopeStack::Cleanup {
John McCallcdda29c2013-03-13 03:10:54 +00001585 ConsumeARCParameter(llvm::Value *param,
1586 ARCPreciseLifetime_t precise)
1587 : Param(param), Precise(precise) {}
John McCall31168b02011-06-15 23:02:42 +00001588
1589 llvm::Value *Param;
John McCallcdda29c2013-03-13 03:10:54 +00001590 ARCPreciseLifetime_t Precise;
John McCall31168b02011-06-15 23:02:42 +00001591
Craig Topper4f12f102014-03-12 06:41:41 +00001592 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001593 CGF.EmitARCRelease(Param, Precise);
John McCall31168b02011-06-15 23:02:42 +00001594 }
1595 };
1596}
1597
Mike Stump11289f42009-09-09 15:08:12 +00001598/// Emit an alloca (or GlobalValue depending on target)
Chris Lattnerb781dc792008-05-08 05:58:21 +00001599/// for the specified parameter and set up LocalDeclMap.
Devang Patel68a15252011-03-03 20:13:15 +00001600void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001601 bool ArgIsPointer, unsigned ArgNo) {
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001602 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Guptad7959242008-10-31 09:52:39 +00001603 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001604 "Invalid argument to EmitParmDecl");
John McCall147d0212011-02-22 22:38:33 +00001605
1606 Arg->setName(D.getName());
1607
Adrian Prantl51936dd2013-03-14 17:53:33 +00001608 QualType Ty = D.getType();
1609
John McCall147d0212011-02-22 22:38:33 +00001610 // Use better IR generation for certain implicit parameters.
1611 if (isa<ImplicitParamDecl>(D)) {
1612 // The only implicit argument a block has is its literal.
1613 if (BlockInfo) {
1614 LocalDeclMap[&D] = Arg;
Craig Topper8a13c412014-05-21 05:09:00 +00001615 llvm::Value *LocalAddr = nullptr;
Adrian Prantl51936dd2013-03-14 17:53:33 +00001616 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
Adrian Prantl0f6df002013-03-29 19:20:35 +00001617 // Allocate a stack slot to let the debug info survive the RA.
Adrian Prantl51936dd2013-03-14 17:53:33 +00001618 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1619 D.getName() + ".addr");
1620 Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity());
1621 LValue lv = MakeAddrLValue(Alloc, Ty, getContext().getDeclAlign(&D));
1622 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
1623 LocalAddr = Builder.CreateLoad(Alloc);
1624 }
John McCall147d0212011-02-22 22:38:33 +00001625
1626 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregorb0eea8b2012-10-23 20:05:01 +00001627 if (CGM.getCodeGenOpts().getDebugInfo()
1628 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001629 DI->setLocation(D.getLocation());
Adrian Prantl51936dd2013-03-14 17:53:33 +00001630 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, LocalAddr, Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001631 }
John McCall147d0212011-02-22 22:38:33 +00001632 }
1633
1634 return;
1635 }
1636 }
1637
Chris Lattner53621a52007-06-13 20:44:40 +00001638 llvm::Value *DeclPtr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001639 bool DoStore = false;
1640 bool IsScalar = hasScalarEvaluationKind(Ty);
1641 CharUnits Align = getContext().getDeclAlign(&D);
1642 // If we already have a pointer to the argument, reuse the input pointer.
1643 if (ArgIsPointer) {
Reid Kleckner5e8edba2014-04-02 00:16:53 +00001644 // If we have a prettier pointer type at this point, bitcast to that.
1645 unsigned AS = cast<llvm::PointerType>(Arg->getType())->getAddressSpace();
1646 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
1647 DeclPtr = Arg->getType() == IRTy ? Arg : Builder.CreateBitCast(Arg, IRTy,
1648 D.getName());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001649 // Push a destructor cleanup for this parameter if the ABI requires it.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001650 if (!IsScalar &&
Reid Kleckner739756c2013-12-04 19:23:12 +00001651 getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001652 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
1653 if (RD && RD->hasNonTrivialDestructor())
1654 pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001655 }
Chris Lattner53621a52007-06-13 20:44:40 +00001656 } else {
Daniel Dunbar3d33fab2010-02-08 22:53:07 +00001657 // Otherwise, create a temporary to hold the value.
Eli Friedmaneadd3e82011-11-03 20:31:28 +00001658 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1659 D.getName() + ".addr");
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001660 Alloc->setAlignment(Align.getQuantity());
Eli Friedmaneadd3e82011-11-03 20:31:28 +00001661 DeclPtr = Alloc;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001662 DoStore = true;
1663 }
Mike Stump11289f42009-09-09 15:08:12 +00001664
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001665 LValue lv = MakeAddrLValue(DeclPtr, Ty, Align);
1666 if (IsScalar) {
John McCall31168b02011-06-15 23:02:42 +00001667 Qualifiers qs = Ty.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00001668 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1669 // We honor __attribute__((ns_consumed)) for types with lifetime.
1670 // For __strong, it's handled by just skipping the initial retain;
1671 // otherwise we have to balance out the initial +1 with an extra
1672 // cleanup to do the release at the end of the function.
1673 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1674
1675 // 'self' is always formally __strong, but if this is not an
1676 // init method then we don't want to retain it.
John McCalld4631322011-06-17 06:42:21 +00001677 if (D.isARCPseudoStrong()) {
John McCall31168b02011-06-15 23:02:42 +00001678 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1679 assert(&D == method->getSelfDecl());
John McCalld4631322011-06-17 06:42:21 +00001680 assert(lt == Qualifiers::OCL_Strong);
1681 assert(qs.hasConst());
John McCall31168b02011-06-15 23:02:42 +00001682 assert(method->getMethodFamily() != OMF_init);
John McCall10123692011-06-15 23:40:09 +00001683 (void) method;
John McCall31168b02011-06-15 23:02:42 +00001684 lt = Qualifiers::OCL_ExplicitNone;
1685 }
1686
1687 if (lt == Qualifiers::OCL_Strong) {
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001688 if (!isConsumed) {
1689 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1690 // use objc_storeStrong(&dest, value) for retaining the
1691 // object. But first, store a null into 'dest' because
1692 // objc_storeStrong attempts to release its old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001693 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001694 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
1695 EmitARCStoreStrongCall(lv.getAddress(), Arg, true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001696 DoStore = false;
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001697 }
1698 else
John McCall31168b02011-06-15 23:02:42 +00001699 // Don't use objc_retainBlock for block pointers, because we
1700 // don't want to Block_copy something just because we got it
1701 // as a parameter.
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001702 Arg = EmitARCRetainNonBlock(Arg);
1703 }
John McCall31168b02011-06-15 23:02:42 +00001704 } else {
1705 // Push the cleanup for a consumed parameter.
John McCallcdda29c2013-03-13 03:10:54 +00001706 if (isConsumed) {
1707 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1708 ? ARCPreciseLifetime : ARCImpreciseLifetime);
1709 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg,
1710 precise);
1711 }
John McCall31168b02011-06-15 23:02:42 +00001712
1713 if (lt == Qualifiers::OCL_Weak) {
1714 EmitARCInitWeak(DeclPtr, Arg);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001715 DoStore = false; // The weak init is a store, no need to do two.
John McCall31168b02011-06-15 23:02:42 +00001716 }
1717 }
1718
1719 // Enter the cleanup scope.
1720 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1721 }
Chris Lattner53621a52007-06-13 20:44:40 +00001722 }
1723
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001724 // Store the initial value into the alloca.
1725 if (DoStore)
1726 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
1727
Chris Lattner53621a52007-06-13 20:44:40 +00001728 llvm::Value *&DMEntry = LocalDeclMap[&D];
Craig Topper8a13c412014-05-21 05:09:00 +00001729 assert(!DMEntry && "Decl already exists in localdeclmap!");
Chris Lattner53621a52007-06-13 20:44:40 +00001730 DMEntry = DeclPtr;
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001731
1732 // Emit debug info for param declaration.
Alexey Samsonov74a38682012-05-04 07:39:27 +00001733 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregorb0eea8b2012-10-23 20:05:01 +00001734 if (CGM.getCodeGenOpts().getDebugInfo()
1735 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001736 DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
1737 }
1738 }
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001739
1740 if (D.hasAttr<AnnotateAttr>())
1741 EmitVarAnnotations(&D, DeclPtr);
Chris Lattner53621a52007-06-13 20:44:40 +00001742}