blob: 614eaab3f373e631af589ca943116ca2619fb606 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Decl nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000015#include "CGDebugInfo.h"
Peter Collingbourne8c25fc52011-09-19 21:14:35 +000016#include "CGOpenCLRuntime.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000017#include "CodeGenModule.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000018#include "clang/AST/ASTContext.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000019#include "clang/AST/CharUnits.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000020#include "clang/AST/Decl.h"
Anders Carlsson19567ee2008-08-25 01:38:19 +000021#include "clang/AST/DeclObjC.h"
Nate Begeman8bd4afe2008-04-19 04:17:09 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner2621fd12008-05-08 05:58:21 +000023#include "clang/Basic/TargetInfo.h"
Chandler Carruth06057ce2010-06-15 23:19:56 +000024#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000025#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/GlobalVariable.h"
27#include "llvm/IR/Intrinsics.h"
28#include "llvm/IR/Type.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029using namespace clang;
30using namespace CodeGen;
31
32
33void CodeGenFunction::EmitDecl(const Decl &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +000034 switch (D.getKind()) {
Douglas Gregor08688ac2010-04-23 02:02:43 +000035 case Decl::TranslationUnit:
36 case Decl::Namespace:
37 case Decl::UnresolvedUsingTypename:
38 case Decl::ClassTemplateSpecialization:
39 case Decl::ClassTemplatePartialSpecialization:
40 case Decl::TemplateTypeParm:
41 case Decl::UnresolvedUsingValue:
Sean Hunt9a555912010-05-30 07:21:58 +000042 case Decl::NonTypeTemplateParm:
Douglas Gregor08688ac2010-04-23 02:02:43 +000043 case Decl::CXXMethod:
44 case Decl::CXXConstructor:
45 case Decl::CXXDestructor:
46 case Decl::CXXConversion:
47 case Decl::Field:
John McCall76da55d2013-04-16 07:28:30 +000048 case Decl::MSProperty:
Francois Pichet41f5e662010-11-21 06:49:41 +000049 case Decl::IndirectField:
Douglas Gregor08688ac2010-04-23 02:02:43 +000050 case Decl::ObjCIvar:
Eric Christophere1f54902011-08-23 22:38:00 +000051 case Decl::ObjCAtDefsField:
Chris Lattneraa9fc462007-10-08 21:37:32 +000052 case Decl::ParmVar:
Douglas Gregor08688ac2010-04-23 02:02:43 +000053 case Decl::ImplicitParam:
54 case Decl::ClassTemplate:
55 case Decl::FunctionTemplate:
Richard Smith3e4c6c42011-05-05 21:57:07 +000056 case Decl::TypeAliasTemplate:
Douglas Gregor08688ac2010-04-23 02:02:43 +000057 case Decl::TemplateTemplateParm:
58 case Decl::ObjCMethod:
59 case Decl::ObjCCategory:
60 case Decl::ObjCProtocol:
61 case Decl::ObjCInterface:
62 case Decl::ObjCCategoryImpl:
63 case Decl::ObjCImplementation:
64 case Decl::ObjCProperty:
65 case Decl::ObjCCompatibleAlias:
Abramo Bagnara6206d532010-06-05 05:09:32 +000066 case Decl::AccessSpec:
Douglas Gregor08688ac2010-04-23 02:02:43 +000067 case Decl::LinkageSpec:
68 case Decl::ObjCPropertyImpl:
Douglas Gregor08688ac2010-04-23 02:02:43 +000069 case Decl::FileScopeAsm:
70 case Decl::Friend:
71 case Decl::FriendTemplate:
72 case Decl::Block:
Tareq A. Siraj6afcf882013-04-16 19:37:38 +000073 case Decl::Captured:
Francois Pichetaf0f4d02011-08-14 03:52:19 +000074 case Decl::ClassScopeFunctionSpecialization:
David Blaikie9faebd22013-05-20 04:58:53 +000075 case Decl::UsingShadow:
David Blaikieb219cfc2011-09-23 05:06:16 +000076 llvm_unreachable("Declaration should not be in declstmts!");
Reid Spencer5f016e22007-07-11 17:01:13 +000077 case Decl::Function: // void X();
Argyrios Kyrtzidis35bc0822008-10-15 00:42:39 +000078 case Decl::Record: // struct/union/class X;
Reid Spencer5f016e22007-07-11 17:01:13 +000079 case Decl::Enum: // enum X;
Mike Stump1eb44332009-09-09 15:08:12 +000080 case Decl::EnumConstant: // enum ? { X = ? }
Argyrios Kyrtzidis35bc0822008-10-15 00:42:39 +000081 case Decl::CXXRecord: // struct/union/class X; [C++]
Anders Carlsson7b0ca3f2009-12-03 17:26:31 +000082 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
Chris Lattner4ae493c2011-02-18 02:08:43 +000083 case Decl::Label: // __label__ x;
Douglas Gregor15de72c2011-12-02 23:23:56 +000084 case Decl::Import:
Alexey Bataevc6400582013-03-22 06:34:35 +000085 case Decl::OMPThreadPrivate:
Michael Han684aa732013-02-22 17:15:32 +000086 case Decl::Empty:
Reid Spencer5f016e22007-07-11 17:01:13 +000087 // None of these decls require codegen support.
88 return;
David Blaikiec8c24272013-02-02 00:39:32 +000089
David Blaikiefc46ebc2013-05-20 22:50:41 +000090 case Decl::NamespaceAlias:
91 if (CGDebugInfo *DI = getDebugInfo())
92 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
93 return;
David Blaikie9faebd22013-05-20 04:58:53 +000094 case Decl::Using: // using X; [C++]
95 if (CGDebugInfo *DI = getDebugInfo())
96 DI->EmitUsingDecl(cast<UsingDecl>(D));
97 return;
David Blaikie957dac52013-04-22 06:13:21 +000098 case Decl::UsingDirective: // using namespace X; [C++]
99 if (CGDebugInfo *DI = getDebugInfo())
100 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
101 return;
Daniel Dunbar662174c82008-08-29 17:28:43 +0000102 case Decl::Var: {
103 const VarDecl &VD = cast<VarDecl>(D);
John McCallb6bbcc92010-10-15 04:57:14 +0000104 assert(VD.isLocalVarDecl() &&
Daniel Dunbar662174c82008-08-29 17:28:43 +0000105 "Should not see file-scope variables inside a function!");
John McCallb6bbcc92010-10-15 04:57:14 +0000106 return EmitVarDecl(VD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000107 }
Mike Stump1eb44332009-09-09 15:08:12 +0000108
Richard Smith162e1c12011-04-15 14:24:37 +0000109 case Decl::Typedef: // typedef int X;
110 case Decl::TypeAlias: { // using X = int; [C++0x]
111 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000112 QualType Ty = TD.getUnderlyingType();
Mike Stump1eb44332009-09-09 15:08:12 +0000113
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000114 if (Ty->isVariablyModifiedType())
John McCallbc8d40d2011-06-24 21:55:10 +0000115 EmitVariablyModifiedType(Ty);
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000116 }
Daniel Dunbar662174c82008-08-29 17:28:43 +0000117 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000118}
119
John McCallb6bbcc92010-10-15 04:57:14 +0000120/// EmitVarDecl - This method handles emission of any variable declaration
Reid Spencer5f016e22007-07-11 17:01:13 +0000121/// inside a function, including static vars etc.
John McCallb6bbcc92010-10-15 04:57:14 +0000122void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Enea Zaffanella713e3f22013-05-16 11:27:56 +0000123 if (D.isStaticLocal()) {
Eric Christophere1f54902011-08-23 22:38:00 +0000124 llvm::GlobalValue::LinkageTypes Linkage =
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000125 llvm::GlobalValue::InternalLinkage;
126
John McCall8b242332010-05-25 04:30:21 +0000127 // If the function definition has some sort of weak linkage, its
128 // static variables should also be weak so that they get properly
Rafael Espindola9610d772013-06-17 20:04:51 +0000129 // uniqued.
130 if (D.isExternallyVisible()) {
Eli Friedman678eca42013-06-13 21:50:44 +0000131 const Decl *D = CurCodeDecl;
132 while (true) {
133 if (isa<BlockDecl>(D)) {
134 // FIXME: Handle this case properly! (Should be similar to the
135 // way we handle lambdas in computeLVForDecl in Decl.cpp.)
136 break;
137 } else if (isa<CapturedDecl>(D)) {
138 D = cast<Decl>(cast<CapturedDecl>(D)->getParent());
139 } else {
140 break;
141 }
142 }
143 // FIXME: Do we really only care about FunctionDecls here?
Rafael Espindola9610d772013-06-17 20:04:51 +0000144 if (isa<FunctionDecl>(D)) {
Eli Friedman678eca42013-06-13 21:50:44 +0000145 llvm::GlobalValue::LinkageTypes ParentLinkage =
146 CGM.getFunctionLinkage(cast<FunctionDecl>(D));
147 if (llvm::GlobalValue::isWeakForLinker(ParentLinkage))
148 Linkage = ParentLinkage;
149 }
150 }
Eric Christophere1f54902011-08-23 22:38:00 +0000151
John McCallb6bbcc92010-10-15 04:57:14 +0000152 return EmitStaticVarDecl(D, Linkage);
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000153 }
Enea Zaffanella713e3f22013-05-16 11:27:56 +0000154
155 if (D.hasExternalStorage())
Lauro Ramos Venanciofea90b82008-02-16 22:30:38 +0000156 // Don't emit it now, allow it to be emitted lazily on its first use.
157 return;
Daniel Dunbar5466c7b2009-04-14 02:25:56 +0000158
Enea Zaffanella713e3f22013-05-16 11:27:56 +0000159 if (D.getStorageClass() == SC_OpenCLWorkGroupLocal)
160 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
161
162 assert(D.hasLocalStorage());
163 return EmitAutoVarDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000164}
165
Chris Lattner761acc12009-12-05 08:22:11 +0000166static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D,
167 const char *Separator) {
168 CodeGenModule &CGM = CGF.CGM;
Richard Smith7edf9e32012-11-01 22:30:59 +0000169 if (CGF.getLangOpts().CPlusPlus) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000170 StringRef Name = CGM.getMangledName(&D);
Anders Carlsson9a20d552010-06-22 16:16:50 +0000171 return Name.str();
John McCallf746aa62010-03-19 23:29:14 +0000172 }
Eric Christophere1f54902011-08-23 22:38:00 +0000173
Chris Lattner761acc12009-12-05 08:22:11 +0000174 std::string ContextName;
Fariborz Jahanianfaa5bfc2010-11-30 23:07:14 +0000175 if (!CGF.CurFuncDecl) {
176 // Better be in a block declared in global scope.
177 const NamedDecl *ND = cast<NamedDecl>(&D);
178 const DeclContext *DC = ND->getDeclContext();
179 if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
180 MangleBuffer Name;
Peter Collingbourne14110472011-01-13 18:57:25 +0000181 CGM.getBlockMangledName(GlobalDecl(), Name, BD);
Fariborz Jahanianfaa5bfc2010-11-30 23:07:14 +0000182 ContextName = Name.getString();
183 }
184 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000185 llvm_unreachable("Unknown context for block static var decl");
Fariborz Jahanianfaa5bfc2010-11-30 23:07:14 +0000186 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000187 StringRef Name = CGM.getMangledName(FD);
Anders Carlsson9a20d552010-06-22 16:16:50 +0000188 ContextName = Name.str();
John McCallf746aa62010-03-19 23:29:14 +0000189 } else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
Chris Lattner761acc12009-12-05 08:22:11 +0000190 ContextName = CGF.CurFn->getName();
191 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000192 llvm_unreachable("Unknown context for static var decl");
Eric Christophere1f54902011-08-23 22:38:00 +0000193
Chris Lattner761acc12009-12-05 08:22:11 +0000194 return ContextName + Separator + D.getNameAsString();
195}
196
Chandler Carruth0f30a122012-03-30 19:44:53 +0000197llvm::GlobalVariable *
John McCallb6bbcc92010-10-15 04:57:14 +0000198CodeGenFunction::CreateStaticVarDecl(const VarDecl &D,
199 const char *Separator,
200 llvm::GlobalValue::LinkageTypes Linkage) {
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000201 QualType Ty = D.getType();
Eli Friedman3c2b3172008-02-15 12:20:59 +0000202 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000203
Benjamin Kramer5c247db2011-11-20 21:05:04 +0000204 // Use the label if the variable is renamed with the asm-label extension.
205 std::string Name;
Benjamin Kramerc3c8f222011-11-21 15:47:23 +0000206 if (D.hasAttr<AsmLabelAttr>())
207 Name = CGM.getMangledName(&D);
208 else
Benjamin Kramer5c247db2011-11-20 21:05:04 +0000209 Name = GetStaticDeclName(*this, D, Separator);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000210
Chris Lattner2acc6e32011-07-18 04:24:23 +0000211 llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
Peter Collingbourne1aba7782012-08-28 20:37:10 +0000212 unsigned AddrSpace =
213 CGM.GetGlobalVarAddressSpace(&D, CGM.getContext().getTargetAddressSpace(Ty));
Anders Carlsson41f8a132009-09-26 18:16:06 +0000214 llvm::GlobalVariable *GV =
215 new llvm::GlobalVariable(CGM.getModule(), LTy,
216 Ty.isConstant(getContext()), Linkage,
Hans Wennborgde981f32012-06-28 08:01:44 +0000217 CGM.EmitNullConstant(D.getType()), Name, 0,
218 llvm::GlobalVariable::NotThreadLocal,
Peter Collingbourne1aba7782012-08-28 20:37:10 +0000219 AddrSpace);
Ken Dyck8b752f12010-01-27 17:10:57 +0000220 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
John McCall112c9672010-11-02 21:04:24 +0000221 if (Linkage != llvm::GlobalValue::InternalLinkage)
222 GV->setVisibility(CurFn->getVisibility());
Hans Wennborgde981f32012-06-28 08:01:44 +0000223
Richard Smith38afbc72013-04-13 02:43:54 +0000224 if (D.getTLSKind())
Hans Wennborgde981f32012-06-28 08:01:44 +0000225 CGM.setTLSMode(GV, D);
226
Anders Carlsson41f8a132009-09-26 18:16:06 +0000227 return GV;
Daniel Dunbar0096acf2009-02-25 19:24:29 +0000228}
229
Richard Smith7ca48502012-02-13 22:16:19 +0000230/// hasNontrivialDestruction - Determine whether a type's destruction is
231/// non-trivial. If so, and the variable uses static initialization, we must
232/// register its destructor to run on exit.
233static bool hasNontrivialDestruction(QualType T) {
234 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
235 return RD && !RD->hasTrivialDestructor();
236}
237
Chandler Carruth0f30a122012-03-30 19:44:53 +0000238/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
239/// global variable that has already been created for it. If the initializer
240/// has a different type than GV does, this may free GV and return a different
241/// one. Otherwise it just returns GV.
242llvm::GlobalVariable *
John McCallb6bbcc92010-10-15 04:57:14 +0000243CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
Chandler Carruth0f30a122012-03-30 19:44:53 +0000244 llvm::GlobalVariable *GV) {
245 llvm::Constant *Init = CGM.EmitConstantInit(D, this);
John McCallbf40cb52010-07-15 23:40:35 +0000246
Chris Lattner761acc12009-12-05 08:22:11 +0000247 // If constant emission failed, then this should be a C++ static
248 // initializer.
Chandler Carruth0f30a122012-03-30 19:44:53 +0000249 if (!Init) {
Richard Smith7edf9e32012-11-01 22:30:59 +0000250 if (!getLangOpts().CPlusPlus)
Chris Lattner761acc12009-12-05 08:22:11 +0000251 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
John McCall5cd91b52010-09-08 01:44:27 +0000252 else if (Builder.GetInsertBlock()) {
Eric Christophere1f54902011-08-23 22:38:00 +0000253 // Since we have a static initializer, this global variable can't
Anders Carlsson071c8102010-01-26 04:02:23 +0000254 // be constant.
Chandler Carruth0f30a122012-03-30 19:44:53 +0000255 GV->setConstant(false);
John McCall5cd91b52010-09-08 01:44:27 +0000256
Chandler Carruth0f30a122012-03-30 19:44:53 +0000257 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
Anders Carlsson071c8102010-01-26 04:02:23 +0000258 }
Chandler Carruth0f30a122012-03-30 19:44:53 +0000259 return GV;
Chris Lattner761acc12009-12-05 08:22:11 +0000260 }
John McCallbf40cb52010-07-15 23:40:35 +0000261
Chris Lattner761acc12009-12-05 08:22:11 +0000262 // The initializer may differ in type from the global. Rewrite
263 // the global to match the initializer. (We have to do this
264 // because some types, like unions, can't be completely represented
265 // in the LLVM type system.)
Chandler Carruth0f30a122012-03-30 19:44:53 +0000266 if (GV->getType()->getElementType() != Init->getType()) {
267 llvm::GlobalVariable *OldGV = GV;
268
269 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
270 OldGV->isConstant(),
271 OldGV->getLinkage(), Init, "",
272 /*InsertBefore*/ OldGV,
Hans Wennborg5e2d5de2012-06-23 11:51:46 +0000273 OldGV->getThreadLocalMode(),
Chandler Carruth0f30a122012-03-30 19:44:53 +0000274 CGM.getContext().getTargetAddressSpace(D.getType()));
275 GV->setVisibility(OldGV->getVisibility());
Eric Christophere1f54902011-08-23 22:38:00 +0000276
Chris Lattner761acc12009-12-05 08:22:11 +0000277 // Steal the name of the old global
Chandler Carruth0f30a122012-03-30 19:44:53 +0000278 GV->takeName(OldGV);
Eric Christophere1f54902011-08-23 22:38:00 +0000279
Chris Lattner761acc12009-12-05 08:22:11 +0000280 // Replace all uses of the old global with the new global
Chandler Carruth0f30a122012-03-30 19:44:53 +0000281 llvm::Constant *NewPtrForOldDecl =
282 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
283 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eric Christophere1f54902011-08-23 22:38:00 +0000284
Chris Lattner761acc12009-12-05 08:22:11 +0000285 // Erase the old global, since it is no longer used.
Chandler Carruth0f30a122012-03-30 19:44:53 +0000286 OldGV->eraseFromParent();
Chris Lattner761acc12009-12-05 08:22:11 +0000287 }
Eric Christophere1f54902011-08-23 22:38:00 +0000288
Chandler Carruth0f30a122012-03-30 19:44:53 +0000289 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
290 GV->setInitializer(Init);
Richard Smith7ca48502012-02-13 22:16:19 +0000291
292 if (hasNontrivialDestruction(D.getType())) {
293 // We have a constant initializer, but a nontrivial destructor. We still
294 // need to perform a guarded "initialization" in order to register the
Richard Smitha9b21d22012-02-17 06:48:11 +0000295 // destructor.
Chandler Carruth0f30a122012-03-30 19:44:53 +0000296 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
Richard Smith7ca48502012-02-13 22:16:19 +0000297 }
298
Chandler Carruth0f30a122012-03-30 19:44:53 +0000299 return GV;
Chris Lattner761acc12009-12-05 08:22:11 +0000300}
301
John McCallb6bbcc92010-10-15 04:57:14 +0000302void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000303 llvm::GlobalValue::LinkageTypes Linkage) {
Chandler Carruth0f30a122012-03-30 19:44:53 +0000304 llvm::Value *&DMEntry = LocalDeclMap[&D];
305 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
Mike Stump1eb44332009-09-09 15:08:12 +0000306
John McCall355bba72012-03-30 21:00:39 +0000307 // Check to see if we already have a global variable for this
308 // declaration. This can happen when double-emitting function
309 // bodies, e.g. with complete and base constructors.
310 llvm::Constant *addr =
311 CGM.getStaticLocalDeclAddress(&D);
312
313 llvm::GlobalVariable *var;
314 if (addr) {
315 var = cast<llvm::GlobalVariable>(addr->stripPointerCasts());
316 } else {
317 addr = var = CreateStaticVarDecl(D, ".", Linkage);
318 }
Daniel Dunbara985b312009-02-25 19:45:19 +0000319
Daniel Dunbare5731f82009-02-25 20:08:33 +0000320 // Store into LocalDeclMap before generating initializer to handle
321 // circular references.
John McCall355bba72012-03-30 21:00:39 +0000322 DMEntry = addr;
323 CGM.setStaticLocalDeclAddress(&D, addr);
Daniel Dunbare5731f82009-02-25 20:08:33 +0000324
John McCallfe67f3b2010-05-04 20:45:42 +0000325 // We can't have a VLA here, but we can have a pointer to a VLA,
326 // even though that doesn't really make any sense.
Eli Friedmanc62aad82009-04-20 03:54:15 +0000327 // Make sure to evaluate VLA bounds now so that we have them for later.
328 if (D.getType()->isVariablyModifiedType())
John McCallbc8d40d2011-06-24 21:55:10 +0000329 EmitVariablyModifiedType(D.getType());
Eric Christophere1f54902011-08-23 22:38:00 +0000330
John McCall355bba72012-03-30 21:00:39 +0000331 // Save the type in case adding the initializer forces a type change.
332 llvm::Type *expectedType = addr->getType();
Eli Friedmanc62aad82009-04-20 03:54:15 +0000333
Chris Lattner761acc12009-12-05 08:22:11 +0000334 // If this value has an initializer, emit it.
335 if (D.getInit())
John McCall355bba72012-03-30 21:00:39 +0000336 var = AddInitializerToStaticVarDecl(D, var);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000337
John McCall355bba72012-03-30 21:00:39 +0000338 var->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Chris Lattner0af95232010-03-10 23:59:59 +0000339
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000340 if (D.hasAttr<AnnotateAttr>())
John McCall355bba72012-03-30 21:00:39 +0000341 CGM.AddGlobalAnnotations(&D, var);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000342
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000343 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
John McCall355bba72012-03-30 21:00:39 +0000344 var->setSection(SA->getName());
Mike Stump1eb44332009-09-09 15:08:12 +0000345
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000346 if (D.hasAttr<UsedAttr>())
John McCall355bba72012-03-30 21:00:39 +0000347 CGM.AddUsedGlobal(var);
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000348
Chandler Carruth0f30a122012-03-30 19:44:53 +0000349 // We may have to cast the constant because of the initializer
350 // mismatch above.
351 //
352 // FIXME: It is really dangerous to store this in the map; if anyone
353 // RAUW's the GV uses of this constant will be invalid.
John McCall355bba72012-03-30 21:00:39 +0000354 llvm::Constant *castedAddr = llvm::ConstantExpr::getBitCast(var, expectedType);
355 DMEntry = castedAddr;
356 CGM.setStaticLocalDeclAddress(&D, castedAddr);
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000357
358 // Emit global variable debug descriptor for static vars.
Anders Carlssone896d982009-02-13 08:11:52 +0000359 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonovfd00eec2012-05-04 07:39:27 +0000360 if (DI &&
Douglas Gregor4cdad312012-10-23 20:05:01 +0000361 CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000362 DI->setLocation(D.getLocation());
John McCall355bba72012-03-30 21:00:39 +0000363 DI->EmitGlobalVariable(var, &D);
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000364 }
Anders Carlsson1a86b332007-10-17 00:52:43 +0000365}
Mike Stump1eb44332009-09-09 15:08:12 +0000366
John McCallda65ea82010-07-13 20:32:21 +0000367namespace {
John McCallbdc4d802011-07-09 01:37:26 +0000368 struct DestroyObject : EHScopeStack::Cleanup {
369 DestroyObject(llvm::Value *addr, QualType type,
John McCall2673c682011-07-11 08:38:19 +0000370 CodeGenFunction::Destroyer *destroyer,
371 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000372 : addr(addr), type(type), destroyer(destroyer),
John McCall2673c682011-07-11 08:38:19 +0000373 useEHCleanupForArray(useEHCleanupForArray) {}
John McCallda65ea82010-07-13 20:32:21 +0000374
John McCallbdc4d802011-07-09 01:37:26 +0000375 llvm::Value *addr;
376 QualType type;
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000377 CodeGenFunction::Destroyer *destroyer;
John McCall2673c682011-07-11 08:38:19 +0000378 bool useEHCleanupForArray;
John McCallda65ea82010-07-13 20:32:21 +0000379
John McCallad346f42011-07-12 20:27:29 +0000380 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall2673c682011-07-11 08:38:19 +0000381 // Don't use an EH cleanup recursively from an EH cleanup.
John McCallad346f42011-07-12 20:27:29 +0000382 bool useEHCleanupForArray =
383 flags.isForNormalCleanup() && this->useEHCleanupForArray;
John McCall2673c682011-07-11 08:38:19 +0000384
385 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
John McCallda65ea82010-07-13 20:32:21 +0000386 }
387 };
388
John McCallbdc4d802011-07-09 01:37:26 +0000389 struct DestroyNRVOVariable : EHScopeStack::Cleanup {
390 DestroyNRVOVariable(llvm::Value *addr,
391 const CXXDestructorDecl *Dtor,
392 llvm::Value *NRVOFlag)
393 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
John McCallda65ea82010-07-13 20:32:21 +0000394
395 const CXXDestructorDecl *Dtor;
396 llvm::Value *NRVOFlag;
397 llvm::Value *Loc;
398
John McCallad346f42011-07-12 20:27:29 +0000399 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallda65ea82010-07-13 20:32:21 +0000400 // Along the exceptions path we always execute the dtor.
John McCallad346f42011-07-12 20:27:29 +0000401 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
John McCallda65ea82010-07-13 20:32:21 +0000402
403 llvm::BasicBlock *SkipDtorBB = 0;
404 if (NRVO) {
405 // If we exited via NRVO, we skip the destructor call.
406 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
407 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
408 llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
409 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
410 CGF.EmitBlock(RunDtorBB);
411 }
Eric Christophere1f54902011-08-23 22:38:00 +0000412
John McCallda65ea82010-07-13 20:32:21 +0000413 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor378e1e72013-01-31 05:50:40 +0000414 /*ForVirtualBase=*/false,
415 /*Delegating=*/false,
416 Loc);
John McCallda65ea82010-07-13 20:32:21 +0000417
418 if (NRVO) CGF.EmitBlock(SkipDtorBB);
419 }
420 };
John McCallda65ea82010-07-13 20:32:21 +0000421
John McCall1f0fca52010-07-21 07:22:38 +0000422 struct CallStackRestore : EHScopeStack::Cleanup {
John McCalld8715092010-07-21 06:13:08 +0000423 llvm::Value *Stack;
424 CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
John McCallad346f42011-07-12 20:27:29 +0000425 void Emit(CodeGenFunction &CGF, Flags flags) {
Benjamin Kramer578faa82011-09-27 21:06:10 +0000426 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
John McCalld8715092010-07-21 06:13:08 +0000427 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
428 CGF.Builder.CreateCall(F, V);
429 }
430 };
431
John McCall0c24c802011-06-24 23:21:27 +0000432 struct ExtendGCLifetime : EHScopeStack::Cleanup {
433 const VarDecl &Var;
434 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
435
John McCallad346f42011-07-12 20:27:29 +0000436 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall0c24c802011-06-24 23:21:27 +0000437 // Compute the address of the local variable, in case it's a
438 // byref or something.
John McCallf4b88a42012-03-10 09:33:50 +0000439 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
440 Var.getType(), VK_LValue, SourceLocation());
John McCall0c24c802011-06-24 23:21:27 +0000441 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE));
442 CGF.EmitExtendGCLifetime(value);
443 }
444 };
445
John McCall1f0fca52010-07-21 07:22:38 +0000446 struct CallCleanupFunction : EHScopeStack::Cleanup {
John McCalld8715092010-07-21 06:13:08 +0000447 llvm::Constant *CleanupFn;
448 const CGFunctionInfo &FnInfo;
John McCalld8715092010-07-21 06:13:08 +0000449 const VarDecl &Var;
Eric Christophere1f54902011-08-23 22:38:00 +0000450
John McCalld8715092010-07-21 06:13:08 +0000451 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCall34695852011-02-22 06:44:22 +0000452 const VarDecl *Var)
453 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalld8715092010-07-21 06:13:08 +0000454
John McCallad346f42011-07-12 20:27:29 +0000455 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf4b88a42012-03-10 09:33:50 +0000456 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
457 Var.getType(), VK_LValue, SourceLocation());
John McCall34695852011-02-22 06:44:22 +0000458 // Compute the address of the local variable, in case it's a byref
459 // or something.
460 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
461
John McCalld8715092010-07-21 06:13:08 +0000462 // In some cases, the type of the function argument will be different from
463 // the type of the pointer. An example of this is
464 // void f(void* arg);
465 // __attribute__((cleanup(f))) void *g;
466 //
467 // To fix this we insert a bitcast here.
468 QualType ArgTy = FnInfo.arg_begin()->type;
469 llvm::Value *Arg =
470 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
471
472 CallArgList Args;
Eli Friedman04c9a492011-05-02 17:57:46 +0000473 Args.add(RValue::get(Arg),
474 CGF.getContext().getPointerType(Var.getType()));
John McCalld8715092010-07-21 06:13:08 +0000475 CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
476 }
477 };
Nadav Rotem495cfa42013-03-23 06:43:35 +0000478
479 /// A cleanup to call @llvm.lifetime.end.
480 class CallLifetimeEnd : public EHScopeStack::Cleanup {
481 llvm::Value *Addr;
482 llvm::Value *Size;
483 public:
484 CallLifetimeEnd(llvm::Value *addr, llvm::Value *size)
485 : Addr(addr), Size(size) {}
486
487 void Emit(CodeGenFunction &CGF, Flags flags) {
488 llvm::Value *castAddr = CGF.Builder.CreateBitCast(Addr, CGF.Int8PtrTy);
489 CGF.Builder.CreateCall2(CGF.CGM.getLLVMLifetimeEndFn(),
490 Size, castAddr)
491 ->setDoesNotThrow();
492 }
493 };
John McCalld8715092010-07-21 06:13:08 +0000494}
495
John McCallf85e1932011-06-15 23:02:42 +0000496/// EmitAutoVarWithLifetime - Does the setup required for an automatic
497/// variable with lifetime.
498static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
499 llvm::Value *addr,
500 Qualifiers::ObjCLifetime lifetime) {
501 switch (lifetime) {
502 case Qualifiers::OCL_None:
503 llvm_unreachable("present but none");
504
505 case Qualifiers::OCL_ExplicitNone:
506 // nothing to do
507 break;
508
509 case Qualifiers::OCL_Strong: {
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000510 CodeGenFunction::Destroyer *destroyer =
John McCall9928c482011-07-12 16:41:08 +0000511 (var.hasAttr<ObjCPreciseLifetimeAttr>()
512 ? CodeGenFunction::destroyARCStrongPrecise
513 : CodeGenFunction::destroyARCStrongImprecise);
514
515 CleanupKind cleanupKind = CGF.getARCCleanupKind();
516 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
517 cleanupKind & EHCleanup);
John McCallf85e1932011-06-15 23:02:42 +0000518 break;
519 }
520 case Qualifiers::OCL_Autoreleasing:
521 // nothing to do
522 break;
Eric Christophere1f54902011-08-23 22:38:00 +0000523
John McCallf85e1932011-06-15 23:02:42 +0000524 case Qualifiers::OCL_Weak:
525 // __weak objects always get EH cleanups; otherwise, exceptions
526 // could cause really nasty crashes instead of mere leaks.
John McCall9928c482011-07-12 16:41:08 +0000527 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
528 CodeGenFunction::destroyARCWeak,
529 /*useEHCleanup*/ true);
John McCallf85e1932011-06-15 23:02:42 +0000530 break;
531 }
532}
533
534static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
535 if (const Expr *e = dyn_cast<Expr>(s)) {
536 // Skip the most common kinds of expressions that make
537 // hierarchy-walking expensive.
538 s = e = e->IgnoreParenCasts();
539
540 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
541 return (ref->getDecl() == &var);
Fariborz Jahanianddfc8a12012-06-19 20:53:26 +0000542 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
543 const BlockDecl *block = be->getBlockDecl();
544 for (BlockDecl::capture_const_iterator i = block->capture_begin(),
545 e = block->capture_end(); i != e; ++i) {
546 if (i->getVariable() == &var)
547 return true;
548 }
549 }
John McCallf85e1932011-06-15 23:02:42 +0000550 }
551
552 for (Stmt::const_child_range children = s->children(); children; ++children)
Fariborz Jahanian8fefc8e2011-06-29 20:00:16 +0000553 // children might be null; as in missing decl or conditional of an if-stmt.
554 if ((*children) && isAccessedBy(var, *children))
John McCallf85e1932011-06-15 23:02:42 +0000555 return true;
556
557 return false;
558}
559
560static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
561 if (!decl) return false;
562 if (!isa<VarDecl>(decl)) return false;
563 const VarDecl *var = cast<VarDecl>(decl);
564 return isAccessedBy(*var, e);
565}
566
John McCalla07398e2011-06-16 04:16:24 +0000567static void drillIntoBlockVariable(CodeGenFunction &CGF,
568 LValue &lvalue,
569 const VarDecl *var) {
570 lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var));
571}
572
John McCallf85e1932011-06-15 23:02:42 +0000573void CodeGenFunction::EmitScalarInit(const Expr *init,
574 const ValueDecl *D,
John McCalla07398e2011-06-16 04:16:24 +0000575 LValue lvalue,
576 bool capturedByInit) {
John McCalla07398e2011-06-16 04:16:24 +0000577 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
John McCallf85e1932011-06-15 23:02:42 +0000578 if (!lifetime) {
579 llvm::Value *value = EmitScalarExpr(init);
John McCalla07398e2011-06-16 04:16:24 +0000580 if (capturedByInit)
581 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Chisnall7a7ee302012-01-16 17:27:18 +0000582 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
John McCallf85e1932011-06-15 23:02:42 +0000583 return;
584 }
585
586 // If we're emitting a value with lifetime, we have to do the
587 // initialization *before* we leave the cleanup scopes.
John McCall1a343eb2011-11-10 08:15:53 +0000588 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
589 enterFullExpression(ewc);
John McCallf85e1932011-06-15 23:02:42 +0000590 init = ewc->getSubExpr();
John McCall1a343eb2011-11-10 08:15:53 +0000591 }
592 CodeGenFunction::RunCleanupsScope Scope(*this);
John McCallf85e1932011-06-15 23:02:42 +0000593
594 // We have to maintain the illusion that the variable is
595 // zero-initialized. If the variable might be accessed in its
596 // initializer, zero-initialize before running the initializer, then
597 // actually perform the initialization with an assign.
598 bool accessedByInit = false;
599 if (lifetime != Qualifiers::OCL_ExplicitNone)
John McCallfb720812011-07-28 07:23:35 +0000600 accessedByInit = (capturedByInit || isAccessedBy(D, init));
John McCallf85e1932011-06-15 23:02:42 +0000601 if (accessedByInit) {
John McCalla07398e2011-06-16 04:16:24 +0000602 LValue tempLV = lvalue;
John McCallf85e1932011-06-15 23:02:42 +0000603 // Drill down to the __block object if necessary.
John McCallf85e1932011-06-15 23:02:42 +0000604 if (capturedByInit) {
605 // We can use a simple GEP for this because it can't have been
606 // moved yet.
John McCalla07398e2011-06-16 04:16:24 +0000607 tempLV.setAddress(Builder.CreateStructGEP(tempLV.getAddress(),
608 getByRefValueLLVMField(cast<VarDecl>(D))));
John McCallf85e1932011-06-15 23:02:42 +0000609 }
610
Chris Lattner2acc6e32011-07-18 04:24:23 +0000611 llvm::PointerType *ty
John McCalla07398e2011-06-16 04:16:24 +0000612 = cast<llvm::PointerType>(tempLV.getAddress()->getType());
John McCallf85e1932011-06-15 23:02:42 +0000613 ty = cast<llvm::PointerType>(ty->getElementType());
614
615 llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
Eric Christophere1f54902011-08-23 22:38:00 +0000616
John McCallf85e1932011-06-15 23:02:42 +0000617 // If __weak, we want to use a barrier under certain conditions.
618 if (lifetime == Qualifiers::OCL_Weak)
John McCalla07398e2011-06-16 04:16:24 +0000619 EmitARCInitWeak(tempLV.getAddress(), zero);
John McCallf85e1932011-06-15 23:02:42 +0000620
621 // Otherwise just do a simple store.
622 else
David Chisnall7a7ee302012-01-16 17:27:18 +0000623 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
John McCallf85e1932011-06-15 23:02:42 +0000624 }
625
626 // Emit the initializer.
627 llvm::Value *value = 0;
628
629 switch (lifetime) {
630 case Qualifiers::OCL_None:
631 llvm_unreachable("present but none");
632
633 case Qualifiers::OCL_ExplicitNone:
634 // nothing to do
635 value = EmitScalarExpr(init);
636 break;
637
638 case Qualifiers::OCL_Strong: {
639 value = EmitARCRetainScalarExpr(init);
640 break;
641 }
642
643 case Qualifiers::OCL_Weak: {
644 // No way to optimize a producing initializer into this. It's not
645 // worth optimizing for, because the value will immediately
646 // disappear in the common case.
647 value = EmitScalarExpr(init);
648
John McCalla07398e2011-06-16 04:16:24 +0000649 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCallf85e1932011-06-15 23:02:42 +0000650 if (accessedByInit)
John McCalla07398e2011-06-16 04:16:24 +0000651 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
John McCallf85e1932011-06-15 23:02:42 +0000652 else
John McCalla07398e2011-06-16 04:16:24 +0000653 EmitARCInitWeak(lvalue.getAddress(), value);
John McCallf85e1932011-06-15 23:02:42 +0000654 return;
655 }
656
657 case Qualifiers::OCL_Autoreleasing:
658 value = EmitARCRetainAutoreleaseScalarExpr(init);
659 break;
660 }
661
John McCalla07398e2011-06-16 04:16:24 +0000662 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCallf85e1932011-06-15 23:02:42 +0000663
664 // If the variable might have been accessed by its initializer, we
665 // might have to initialize with a barrier. We have to do this for
666 // both __weak and __strong, but __weak got filtered out above.
667 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
John McCalla07398e2011-06-16 04:16:24 +0000668 llvm::Value *oldValue = EmitLoadOfScalar(lvalue);
David Chisnall7a7ee302012-01-16 17:27:18 +0000669 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCall5b07e802013-03-13 03:10:54 +0000670 EmitARCRelease(oldValue, ARCImpreciseLifetime);
John McCallf85e1932011-06-15 23:02:42 +0000671 return;
672 }
673
David Chisnall7a7ee302012-01-16 17:27:18 +0000674 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCallf85e1932011-06-15 23:02:42 +0000675}
Chris Lattner94cd0112010-12-01 02:05:19 +0000676
John McCall7acddac2011-06-17 06:42:21 +0000677/// EmitScalarInit - Initialize the given lvalue with the given object.
678void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
679 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
680 if (!lifetime)
David Chisnall7a7ee302012-01-16 17:27:18 +0000681 return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
John McCall7acddac2011-06-17 06:42:21 +0000682
683 switch (lifetime) {
684 case Qualifiers::OCL_None:
685 llvm_unreachable("present but none");
686
687 case Qualifiers::OCL_ExplicitNone:
688 // nothing to do
689 break;
690
691 case Qualifiers::OCL_Strong:
692 init = EmitARCRetain(lvalue.getType(), init);
693 break;
694
695 case Qualifiers::OCL_Weak:
696 // Initialize and then skip the primitive store.
697 EmitARCInitWeak(lvalue.getAddress(), init);
698 return;
699
700 case Qualifiers::OCL_Autoreleasing:
701 init = EmitARCRetainAutorelease(lvalue.getType(), init);
702 break;
703 }
704
David Chisnall7a7ee302012-01-16 17:27:18 +0000705 EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
John McCall7acddac2011-06-17 06:42:21 +0000706}
707
Chris Lattner94cd0112010-12-01 02:05:19 +0000708/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
709/// non-zero parts of the specified initializer with equal or fewer than
710/// NumStores scalar stores.
711static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
712 unsigned &NumStores) {
Chris Lattner70b02942010-12-02 01:58:41 +0000713 // Zero and Undef never requires any extra stores.
714 if (isa<llvm::ConstantAggregateZero>(Init) ||
715 isa<llvm::ConstantPointerNull>(Init) ||
716 isa<llvm::UndefValue>(Init))
717 return true;
718 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
719 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
720 isa<llvm::ConstantExpr>(Init))
721 return Init->isNullValue() || NumStores--;
722
723 // See if we can emit each element.
724 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
725 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
726 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
727 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
728 return false;
729 }
730 return true;
731 }
Chris Lattnerf492cb12012-01-31 04:36:19 +0000732
733 if (llvm::ConstantDataSequential *CDS =
734 dyn_cast<llvm::ConstantDataSequential>(Init)) {
735 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
736 llvm::Constant *Elt = CDS->getElementAsConstant(i);
737 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
738 return false;
739 }
740 return true;
741 }
Eric Christophere1f54902011-08-23 22:38:00 +0000742
Chris Lattner94cd0112010-12-01 02:05:19 +0000743 // Anything else is hard and scary.
744 return false;
745}
746
747/// emitStoresForInitAfterMemset - For inits that
748/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
749/// stores that would be required.
750static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
John McCall34695852011-02-22 06:44:22 +0000751 bool isVolatile, CGBuilderTy &Builder) {
Benjamin Kramer06d43682012-08-27 22:07:02 +0000752 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
753 "called emitStoresForInitAfterMemset for zero or undef value.");
Eric Christophere1f54902011-08-23 22:38:00 +0000754
Chris Lattner70b02942010-12-02 01:58:41 +0000755 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
756 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
757 isa<llvm::ConstantExpr>(Init)) {
Chris Lattnerf492cb12012-01-31 04:36:19 +0000758 Builder.CreateStore(Init, Loc, isVolatile);
759 return;
760 }
761
762 if (llvm::ConstantDataSequential *CDS =
763 dyn_cast<llvm::ConstantDataSequential>(Init)) {
764 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
765 llvm::Constant *Elt = CDS->getElementAsConstant(i);
Benjamin Kramercfa07e32012-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 Lattnerf492cb12012-01-31 04:36:19 +0000771 }
Chris Lattner70b02942010-12-02 01:58:41 +0000772 return;
773 }
Eric Christophere1f54902011-08-23 22:38:00 +0000774
Chris Lattner70b02942010-12-02 01:58:41 +0000775 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
776 "Unknown value type!");
Eric Christophere1f54902011-08-23 22:38:00 +0000777
Chris Lattner70b02942010-12-02 01:58:41 +0000778 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
779 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
Benjamin Kramercfa07e32012-08-27 21:35:58 +0000780
781 // If necessary, get a pointer to the element and emit it.
782 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
783 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
784 isVolatile, Builder);
Chris Lattner70b02942010-12-02 01:58:41 +0000785 }
Chris Lattner94cd0112010-12-01 02:05:19 +0000786}
787
788
789/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
790/// plus some stores to initialize a local variable instead of using a memcpy
791/// from a constant global. It is beneficial to use memset if the global is all
792/// zeros, or mostly zeros and large.
793static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
794 uint64_t GlobalSize) {
795 // If a global is all zeros, always use a memset.
796 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
797
Chris Lattner94cd0112010-12-01 02:05:19 +0000798 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
799 // do it if it will require 6 or fewer scalar stores.
800 // TODO: Should budget depends on the size? Avoiding a large global warrants
801 // plopping in more stores.
802 unsigned StoreBudget = 6;
803 uint64_t SizeLimit = 32;
Eric Christophere1f54902011-08-23 22:38:00 +0000804
805 return GlobalSize > SizeLimit &&
Chris Lattner94cd0112010-12-01 02:05:19 +0000806 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
807}
808
Nadav Rotem495cfa42013-03-23 06:43:35 +0000809/// Should we use the LLVM lifetime intrinsics for the given local variable?
810static bool shouldUseLifetimeMarkers(CodeGenFunction &CGF, const VarDecl &D,
811 unsigned Size) {
Alexey Samsonov4f01ed42013-04-02 13:19:46 +0000812 // Always emit lifetime markers in -fsanitize=use-after-scope mode.
813 if (CGF.getLangOpts().Sanitize.UseAfterScope)
814 return true;
Nadav Rotem495cfa42013-03-23 06:43:35 +0000815 // For now, only in optimized builds.
816 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0)
817 return false;
818
819 // Limit the size of marked objects to 32 bytes. We don't want to increase
820 // compile time by marking tiny objects.
821 unsigned SizeThreshold = 32;
822
823 return Size > SizeThreshold;
824}
825
Chris Lattner94cd0112010-12-01 02:05:19 +0000826
Nick Lewyckya9de3fa2010-12-30 20:21:55 +0000827/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Reid Spencer5f016e22007-07-11 17:01:13 +0000828/// variable declaration with auto, register, or no storage class specifier.
Chris Lattner2621fd12008-05-08 05:58:21 +0000829/// These turn into simple stack objects, or GlobalValues depending on target.
John McCall34695852011-02-22 06:44:22 +0000830void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
831 AutoVarEmission emission = EmitAutoVarAlloca(D);
832 EmitAutoVarInit(emission);
833 EmitAutoVarCleanups(emission);
834}
Reid Spencer5f016e22007-07-11 17:01:13 +0000835
John McCall34695852011-02-22 06:44:22 +0000836/// EmitAutoVarAlloca - Emit the alloca and debug information for a
837/// local variable. Does not emit initalization or destruction.
838CodeGenFunction::AutoVarEmission
839CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
840 QualType Ty = D.getType();
841
842 AutoVarEmission emission(D);
843
844 bool isByRef = D.hasAttr<BlocksAttr>();
845 emission.IsByRef = isByRef;
846
847 CharUnits alignment = getContext().getDeclAlign(&D);
848 emission.Alignment = alignment;
849
John McCallbc8d40d2011-06-24 21:55:10 +0000850 // If the type is variably-modified, emit all the VLA sizes for it.
851 if (Ty->isVariablyModifiedType())
852 EmitVariablyModifiedType(Ty);
853
Reid Spencer5f016e22007-07-11 17:01:13 +0000854 llvm::Value *DeclPtr;
Eli Friedman3c2b3172008-02-15 12:20:59 +0000855 if (Ty->isConstantSizeType()) {
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000856 bool NRVO = getLangOpts().ElideConstructors &&
857 D.isNRVOVariable();
John McCall34695852011-02-22 06:44:22 +0000858
Richard Smithe67ca582013-06-02 00:09:52 +0000859 // If this value is an array or struct with a statically determinable
860 // constant initializer, there are optimizations we can do.
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000861 //
862 // TODO: We should constant-evaluate the initializer of any variable,
863 // as long as it is initialized by a constant expression. Currently,
864 // isConstantInitializer produces wrong answers for structs with
865 // reference or bitfield members, and a few other cases, and checking
866 // for POD-ness protects us from some of these.
Richard Smithe67ca582013-06-02 00:09:52 +0000867 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
868 (D.isConstexpr() ||
869 ((Ty.isPODType(getContext()) ||
870 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
871 D.getInit()->isConstantInitializer(getContext(), false)))) {
John McCall34695852011-02-22 06:44:22 +0000872
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000873 // If the variable's a const type, and it's neither an NRVO
874 // candidate nor a __block variable and has no mutable members,
875 // emit it as a global instead.
876 if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
877 CGM.isTypeConstant(Ty, true)) {
878 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCall34695852011-02-22 06:44:22 +0000879
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000880 emission.Address = 0; // signal this condition to later callbacks
881 assert(emission.wasEmittedAsGlobal());
882 return emission;
Tanya Lattner59876c22009-11-04 01:18:09 +0000883 }
Eric Christophere1f54902011-08-23 22:38:00 +0000884
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000885 // Otherwise, tell the initialization code that we're in this case.
886 emission.IsConstantAggregate = true;
887 }
Eric Christophere1f54902011-08-23 22:38:00 +0000888
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000889 // A normal fixed sized variable becomes an alloca in the entry block,
890 // unless it's an NRVO variable.
891 llvm::Type *LTy = ConvertTypeForMem(Ty);
Eric Christophere1f54902011-08-23 22:38:00 +0000892
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000893 if (NRVO) {
894 // The named return value optimization: allocate this variable in the
895 // return slot, so that we can elide the copy when returning this
896 // variable (C++0x [class.copy]p34).
897 DeclPtr = ReturnValue;
Eric Christophere1f54902011-08-23 22:38:00 +0000898
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000899 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
900 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
901 // Create a flag that is used to indicate when the NRVO was applied
902 // to this variable. Set it to zero to indicate that NRVO was not
903 // applied.
904 llvm::Value *Zero = Builder.getFalse();
905 llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
906 EnsureInsertPoint();
907 Builder.CreateStore(Zero, NRVOFlag);
Eric Christophere1f54902011-08-23 22:38:00 +0000908
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000909 // Record the NRVO flag for this variable.
910 NRVOFlags[&D] = NRVOFlag;
911 emission.NRVOFlag = NRVOFlag;
Nadav Rotem495cfa42013-03-23 06:43:35 +0000912 }
Douglas Gregord86c4772010-05-15 06:46:45 +0000913 }
Chris Lattner2621fd12008-05-08 05:58:21 +0000914 } else {
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000915 if (isByRef)
916 LTy = BuildByRefType(&D);
917
918 llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
919 Alloc->setName(D.getName());
920
921 CharUnits allocaAlignment = alignment;
922 if (isByRef)
923 allocaAlignment = std::max(allocaAlignment,
John McCall64aa4b32013-04-16 22:48:15 +0000924 getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0)));
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000925 Alloc->setAlignment(allocaAlignment.getQuantity());
926 DeclPtr = Alloc;
927
928 // Emit a lifetime intrinsic if meaningful. There's no point
929 // in doing this if we don't have a valid insertion point (?).
930 uint64_t size = CGM.getDataLayout().getTypeAllocSize(LTy);
931 if (HaveInsertPoint() && shouldUseLifetimeMarkers(*this, D, size)) {
932 llvm::Value *sizeV = llvm::ConstantInt::get(Int64Ty, size);
933
934 emission.SizeForLifetimeMarkers = sizeV;
935 llvm::Value *castAddr = Builder.CreateBitCast(Alloc, Int8PtrTy);
936 Builder.CreateCall2(CGM.getLLVMLifetimeStartFn(), sizeV, castAddr)
937 ->setDoesNotThrow();
938 } else {
939 assert(!emission.useLifetimeMarkers());
940 }
Chris Lattner2621fd12008-05-08 05:58:21 +0000941 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000942 } else {
Daniel Dunbard286f052009-07-19 06:58:07 +0000943 EnsureInsertPoint();
944
Anders Carlsson5ecb1b92009-02-09 20:41:50 +0000945 if (!DidCallStackSave) {
Anders Carlsson5d463152008-12-12 07:38:43 +0000946 // Save the stack.
John McCalld16c2cf2011-02-08 08:22:06 +0000947 llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
Mike Stump1eb44332009-09-09 15:08:12 +0000948
Anders Carlsson5d463152008-12-12 07:38:43 +0000949 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
950 llvm::Value *V = Builder.CreateCall(F);
Mike Stump1eb44332009-09-09 15:08:12 +0000951
Anders Carlsson5d463152008-12-12 07:38:43 +0000952 Builder.CreateStore(V, Stack);
Anders Carlsson5ecb1b92009-02-09 20:41:50 +0000953
954 DidCallStackSave = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000955
John McCalld8715092010-07-21 06:13:08 +0000956 // Push a cleanup block and restore the stack there.
John McCall3ad32c82011-01-28 08:37:24 +0000957 // FIXME: in general circumstances, this should be an EH cleanup.
John McCall1f0fca52010-07-21 07:22:38 +0000958 EHStack.pushCleanup<CallStackRestore>(NormalCleanup, Stack);
Anders Carlsson5d463152008-12-12 07:38:43 +0000959 }
Mike Stump1eb44332009-09-09 15:08:12 +0000960
John McCallbc8d40d2011-06-24 21:55:10 +0000961 llvm::Value *elementCount;
962 QualType elementType;
963 llvm::tie(elementCount, elementType) = getVLASize(Ty);
Anders Carlsson5d463152008-12-12 07:38:43 +0000964
Chris Lattner2acc6e32011-07-18 04:24:23 +0000965 llvm::Type *llvmTy = ConvertTypeForMem(elementType);
Anders Carlsson5d463152008-12-12 07:38:43 +0000966
967 // Allocate memory for the array.
John McCallbc8d40d2011-06-24 21:55:10 +0000968 llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
969 vla->setAlignment(alignment.getQuantity());
Anders Carlsson41f8a132009-09-26 18:16:06 +0000970
John McCallbc8d40d2011-06-24 21:55:10 +0000971 DeclPtr = vla;
Reid Spencer5f016e22007-07-11 17:01:13 +0000972 }
Eli Friedman8f39f5e2008-12-20 23:11:59 +0000973
Reid Spencer5f016e22007-07-11 17:01:13 +0000974 llvm::Value *&DMEntry = LocalDeclMap[&D];
975 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
976 DMEntry = DeclPtr;
John McCall34695852011-02-22 06:44:22 +0000977 emission.Address = DeclPtr;
Sanjiv Guptacc9b1632008-05-30 10:30:31 +0000978
979 // Emit debug info for local var declaration.
Devang Patelc594abd2011-06-03 19:21:47 +0000980 if (HaveInsertPoint())
981 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregor4cdad312012-10-23 20:05:01 +0000982 if (CGM.getCodeGenOpts().getDebugInfo()
983 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonovfd00eec2012-05-04 07:39:27 +0000984 DI->setLocation(D.getLocation());
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000985 DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
Alexey Samsonovfd00eec2012-05-04 07:39:27 +0000986 }
Devang Patelc594abd2011-06-03 19:21:47 +0000987 }
Sanjiv Guptacc9b1632008-05-30 10:30:31 +0000988
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000989 if (D.hasAttr<AnnotateAttr>())
990 EmitVarAnnotations(&D, emission.Address);
991
John McCall34695852011-02-22 06:44:22 +0000992 return emission;
993}
994
995/// Determines whether the given __block variable is potentially
996/// captured by the given expression.
997static bool isCapturedBy(const VarDecl &var, const Expr *e) {
998 // Skip the most common kinds of expressions that make
999 // hierarchy-walking expensive.
1000 e = e->IgnoreParenCasts();
1001
1002 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
1003 const BlockDecl *block = be->getBlockDecl();
1004 for (BlockDecl::capture_const_iterator i = block->capture_begin(),
1005 e = block->capture_end(); i != e; ++i) {
1006 if (i->getVariable() == &var)
1007 return true;
1008 }
1009
1010 // No need to walk into the subexpressions.
1011 return false;
1012 }
1013
Fariborz Jahanian5033be12011-08-23 16:47:15 +00001014 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1015 const CompoundStmt *CS = SE->getSubStmt();
Eric Christopherc6fad602011-08-23 23:44:09 +00001016 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1017 BE = CS->body_end(); BI != BE; ++BI)
Fariborz Jahanian045c8422011-08-25 00:06:26 +00001018 if (Expr *E = dyn_cast<Expr>((*BI))) {
Fariborz Jahanian5033be12011-08-23 16:47:15 +00001019 if (isCapturedBy(var, E))
1020 return true;
Fariborz Jahanian045c8422011-08-25 00:06:26 +00001021 }
1022 else if (DeclStmt *DS = dyn_cast<DeclStmt>((*BI))) {
1023 // special case declarations
1024 for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
1025 I != E; ++I) {
1026 if (VarDecl *VD = dyn_cast<VarDecl>((*I))) {
1027 Expr *Init = VD->getInit();
1028 if (Init && isCapturedBy(var, Init))
1029 return true;
1030 }
1031 }
1032 }
1033 else
1034 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1035 // Later, provide code to poke into statements for capture analysis.
1036 return true;
Fariborz Jahanian5033be12011-08-23 16:47:15 +00001037 return false;
1038 }
Eric Christophere1f54902011-08-23 22:38:00 +00001039
John McCall34695852011-02-22 06:44:22 +00001040 for (Stmt::const_child_range children = e->children(); children; ++children)
1041 if (isCapturedBy(var, cast<Expr>(*children)))
1042 return true;
1043
1044 return false;
1045}
1046
Douglas Gregorbcc3e662011-07-01 21:08:19 +00001047/// \brief Determine whether the given initializer is trivial in the sense
1048/// that it requires no code to be generated.
1049static bool isTrivialInitializer(const Expr *Init) {
1050 if (!Init)
1051 return true;
Eric Christophere1f54902011-08-23 22:38:00 +00001052
Douglas Gregorbcc3e662011-07-01 21:08:19 +00001053 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1054 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1055 if (Constructor->isTrivial() &&
1056 Constructor->isDefaultConstructor() &&
1057 !Construct->requiresZeroInitialization())
1058 return true;
Eric Christophere1f54902011-08-23 22:38:00 +00001059
Douglas Gregorbcc3e662011-07-01 21:08:19 +00001060 return false;
1061}
John McCall34695852011-02-22 06:44:22 +00001062void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall57b3b6a2011-02-22 07:16:58 +00001063 assert(emission.Variable && "emission was not valid!");
1064
John McCall34695852011-02-22 06:44:22 +00001065 // If this was emitted as a global constant, we're done.
1066 if (emission.wasEmittedAsGlobal()) return;
1067
John McCall57b3b6a2011-02-22 07:16:58 +00001068 const VarDecl &D = *emission.Variable;
John McCall34695852011-02-22 06:44:22 +00001069 QualType type = D.getType();
1070
Chris Lattner19785962007-07-12 00:39:48 +00001071 // If this local has an initializer, emit it now.
Daniel Dunbard286f052009-07-19 06:58:07 +00001072 const Expr *Init = D.getInit();
1073
1074 // If we are at an unreachable point, we don't need to emit the initializer
1075 // unless it contains a label.
1076 if (!HaveInsertPoint()) {
John McCall34695852011-02-22 06:44:22 +00001077 if (!Init || !ContainsLabel(Init)) return;
1078 EnsureInsertPoint();
Daniel Dunbard286f052009-07-19 06:58:07 +00001079 }
1080
John McCall5af02db2011-03-31 01:59:53 +00001081 // Initialize the structure of a __block variable.
1082 if (emission.IsByRef)
1083 emitByrefStructureInit(emission);
Anders Carlsson69c68b72009-02-07 23:51:38 +00001084
Douglas Gregorbcc3e662011-07-01 21:08:19 +00001085 if (isTrivialInitializer(Init))
1086 return;
Eric Christophere1f54902011-08-23 22:38:00 +00001087
John McCall5af02db2011-03-31 01:59:53 +00001088 CharUnits alignment = emission.Alignment;
1089
John McCall34695852011-02-22 06:44:22 +00001090 // Check whether this is a byref variable that's potentially
1091 // captured and moved by its own initializer. If so, we'll need to
1092 // emit the initializer first, then copy into the variable.
1093 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1094
1095 llvm::Value *Loc =
1096 capturedByInit ? emission.Address : emission.getObjectAddress(*this);
1097
Richard Smith51201882011-12-30 21:15:51 +00001098 llvm::Constant *constant = 0;
Richard Smithe67ca582013-06-02 00:09:52 +00001099 if (emission.IsConstantAggregate || D.isConstexpr()) {
Richard Smith51201882011-12-30 21:15:51 +00001100 assert(!capturedByInit && "constant init contains a capturing block?");
Richard Smith2d6a5672012-01-14 04:30:29 +00001101 constant = CGM.EmitConstantInit(D, this);
Richard Smith51201882011-12-30 21:15:51 +00001102 }
1103
1104 if (!constant) {
Eli Friedman6da2c712011-12-03 04:14:32 +00001105 LValue lv = MakeAddrLValue(Loc, type, alignment);
John McCalla07398e2011-06-16 04:16:24 +00001106 lv.setNonGC(true);
1107 return EmitExprAsInit(Init, &D, lv, capturedByInit);
1108 }
John McCall60d33652011-03-08 09:11:50 +00001109
Richard Smithe67ca582013-06-02 00:09:52 +00001110 if (!emission.IsConstantAggregate) {
1111 // For simple scalar/complex initialization, store the value directly.
1112 LValue lv = MakeAddrLValue(Loc, type, alignment);
1113 lv.setNonGC(true);
1114 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1115 }
1116
John McCall34695852011-02-22 06:44:22 +00001117 // If this is a simple aggregate initialization, we can optimize it
1118 // in various ways.
John McCall60d33652011-03-08 09:11:50 +00001119 bool isVolatile = type.isVolatileQualified();
John McCall34695852011-02-22 06:44:22 +00001120
John McCall60d33652011-03-08 09:11:50 +00001121 llvm::Value *SizeVal =
Eric Christophere1f54902011-08-23 22:38:00 +00001122 llvm::ConstantInt::get(IntPtrTy,
John McCall60d33652011-03-08 09:11:50 +00001123 getContext().getTypeSizeInChars(type).getQuantity());
John McCall34695852011-02-22 06:44:22 +00001124
Chris Lattner2acc6e32011-07-18 04:24:23 +00001125 llvm::Type *BP = Int8PtrTy;
John McCall60d33652011-03-08 09:11:50 +00001126 if (Loc->getType() != BP)
Benjamin Kramer578faa82011-09-27 21:06:10 +00001127 Loc = Builder.CreateBitCast(Loc, BP);
Mon P Wang3ecd7852010-04-04 03:10:52 +00001128
John McCall60d33652011-03-08 09:11:50 +00001129 // If the initializer is all or mostly zeros, codegen with memset then do
1130 // a few stores afterward.
Eric Christophere1f54902011-08-23 22:38:00 +00001131 if (shouldUseMemSetPlusStoresToInitialize(constant,
Micah Villmow25a6a842012-10-08 16:25:52 +00001132 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
John McCall60d33652011-03-08 09:11:50 +00001133 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1134 alignment.getQuantity(), isVolatile);
Benjamin Kramer06d43682012-08-27 22:07:02 +00001135 // Zero and undef don't require a stores.
1136 if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
John McCall60d33652011-03-08 09:11:50 +00001137 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
1138 emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +00001139 }
John McCall60d33652011-03-08 09:11:50 +00001140 } else {
Eric Christophere1f54902011-08-23 22:38:00 +00001141 // Otherwise, create a temporary global with the initializer then
John McCall60d33652011-03-08 09:11:50 +00001142 // memcpy from the global to the alloca.
1143 std::string Name = GetStaticDeclName(*this, D, ".");
1144 llvm::GlobalVariable *GV =
1145 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
Eric Christopher736a9c22011-08-24 00:33:55 +00001146 llvm::GlobalValue::PrivateLinkage,
Hans Wennborg5e2d5de2012-06-23 11:51:46 +00001147 constant, Name);
John McCall60d33652011-03-08 09:11:50 +00001148 GV->setAlignment(alignment.getQuantity());
Eli Friedman460980d2011-05-27 22:32:55 +00001149 GV->setUnnamedAddr(true);
Eric Christophere1f54902011-08-23 22:38:00 +00001150
John McCall60d33652011-03-08 09:11:50 +00001151 llvm::Value *SrcPtr = GV;
1152 if (SrcPtr->getType() != BP)
Benjamin Kramer578faa82011-09-27 21:06:10 +00001153 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
John McCall60d33652011-03-08 09:11:50 +00001154
1155 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
1156 isVolatile);
1157 }
1158}
1159
1160/// Emit an expression as an initializer for a variable at the given
1161/// location. The expression is not necessarily the normal
1162/// initializer for the variable, and the address is not necessarily
1163/// its normal location.
1164///
1165/// \param init the initializing expression
1166/// \param var the variable to act as if we're initializing
1167/// \param loc the address to initialize; its type is a pointer
1168/// to the LLVM mapping of the variable's type
1169/// \param alignment the alignment of the address
1170/// \param capturedByInit true if the variable is a __block variable
1171/// whose address is potentially changed by the initializer
1172void CodeGenFunction::EmitExprAsInit(const Expr *init,
John McCallf85e1932011-06-15 23:02:42 +00001173 const ValueDecl *D,
John McCalla07398e2011-06-16 04:16:24 +00001174 LValue lvalue,
John McCall60d33652011-03-08 09:11:50 +00001175 bool capturedByInit) {
John McCallf85e1932011-06-15 23:02:42 +00001176 QualType type = D->getType();
John McCall60d33652011-03-08 09:11:50 +00001177
1178 if (type->isReferenceType()) {
Richard Smithd4ec5622013-06-12 23:38:09 +00001179 RValue rvalue = EmitReferenceBindingToExpr(init);
Eric Christophere1f54902011-08-23 22:38:00 +00001180 if (capturedByInit)
John McCalla07398e2011-06-16 04:16:24 +00001181 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Chisnall7a7ee302012-01-16 17:27:18 +00001182 EmitStoreThroughLValue(rvalue, lvalue, true);
John McCall9d232c82013-03-07 21:37:08 +00001183 return;
1184 }
1185 switch (getEvaluationKind(type)) {
1186 case TEK_Scalar:
John McCalla07398e2011-06-16 04:16:24 +00001187 EmitScalarInit(init, D, lvalue, capturedByInit);
John McCall9d232c82013-03-07 21:37:08 +00001188 return;
1189 case TEK_Complex: {
John McCall60d33652011-03-08 09:11:50 +00001190 ComplexPairTy complex = EmitComplexExpr(init);
John McCalla07398e2011-06-16 04:16:24 +00001191 if (capturedByInit)
1192 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall9d232c82013-03-07 21:37:08 +00001193 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
1194 return;
1195 }
1196 case TEK_Aggregate:
John McCall9eda3ab2013-03-07 21:37:17 +00001197 if (type->isAtomicType()) {
1198 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1199 } else {
1200 // TODO: how can we delay here if D is captured by its initializer?
1201 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
Chad Rosier649b4a12012-03-29 17:37:10 +00001202 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001203 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001204 AggValueSlot::IsNotAliased));
John McCall9eda3ab2013-03-07 21:37:17 +00001205 }
John McCall9d232c82013-03-07 21:37:08 +00001206 return;
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +00001207 }
John McCall9d232c82013-03-07 21:37:08 +00001208 llvm_unreachable("bad evaluation kind");
John McCall34695852011-02-22 06:44:22 +00001209}
John McCallf1549f62010-07-06 01:34:17 +00001210
John McCallbdc4d802011-07-09 01:37:26 +00001211/// Enter a destroy cleanup for the given local variable.
1212void CodeGenFunction::emitAutoVarTypeCleanup(
1213 const CodeGenFunction::AutoVarEmission &emission,
1214 QualType::DestructionKind dtorKind) {
1215 assert(dtorKind != QualType::DK_none);
1216
1217 // Note that for __block variables, we want to destroy the
1218 // original stack object, not the possibly forwarded object.
1219 llvm::Value *addr = emission.getObjectAddress(*this);
1220
1221 const VarDecl *var = emission.Variable;
1222 QualType type = var->getType();
1223
1224 CleanupKind cleanupKind = NormalAndEHCleanup;
1225 CodeGenFunction::Destroyer *destroyer = 0;
1226
1227 switch (dtorKind) {
1228 case QualType::DK_none:
1229 llvm_unreachable("no cleanup for trivially-destructible variable");
1230
1231 case QualType::DK_cxx_destructor:
1232 // If there's an NRVO flag on the emission, we need a different
1233 // cleanup.
1234 if (emission.NRVOFlag) {
1235 assert(!type->isArrayType());
1236 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1237 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor,
1238 emission.NRVOFlag);
1239 return;
1240 }
1241 break;
1242
1243 case QualType::DK_objc_strong_lifetime:
1244 // Suppress cleanups for pseudo-strong variables.
1245 if (var->isARCPseudoStrong()) return;
Eric Christophere1f54902011-08-23 22:38:00 +00001246
John McCallbdc4d802011-07-09 01:37:26 +00001247 // Otherwise, consider whether to use an EH cleanup or not.
1248 cleanupKind = getARCCleanupKind();
1249
1250 // Use the imprecise destroyer by default.
1251 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1252 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1253 break;
1254
1255 case QualType::DK_objc_weak_lifetime:
1256 break;
1257 }
1258
1259 // If we haven't chosen a more specific destroyer, use the default.
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001260 if (!destroyer) destroyer = getDestroyer(dtorKind);
John McCall2673c682011-07-11 08:38:19 +00001261
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00001262 // Use an EH cleanup in array destructors iff the destructor itself
John McCall2673c682011-07-11 08:38:19 +00001263 // is being pushed as an EH cleanup.
1264 bool useEHCleanup = (cleanupKind & EHCleanup);
1265 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1266 useEHCleanup);
John McCallbdc4d802011-07-09 01:37:26 +00001267}
1268
John McCall34695852011-02-22 06:44:22 +00001269void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall57b3b6a2011-02-22 07:16:58 +00001270 assert(emission.Variable && "emission was not valid!");
1271
John McCall34695852011-02-22 06:44:22 +00001272 // If this was emitted as a global constant, we're done.
1273 if (emission.wasEmittedAsGlobal()) return;
1274
John McCall38baeab2012-04-13 18:44:05 +00001275 // If we don't have an insertion point, we're done. Sema prevents
1276 // us from jumping into any of these scopes anyway.
1277 if (!HaveInsertPoint()) return;
1278
John McCall57b3b6a2011-02-22 07:16:58 +00001279 const VarDecl &D = *emission.Variable;
John McCall34695852011-02-22 06:44:22 +00001280
Nadav Rotem495cfa42013-03-23 06:43:35 +00001281 // Make sure we call @llvm.lifetime.end. This needs to happen
1282 // *last*, so the cleanup needs to be pushed *first*.
1283 if (emission.useLifetimeMarkers()) {
1284 EHStack.pushCleanup<CallLifetimeEnd>(NormalCleanup,
1285 emission.getAllocatedAddress(),
1286 emission.getSizeForLifetimeMarkers());
1287 }
1288
John McCallbdc4d802011-07-09 01:37:26 +00001289 // Check the type for a cleanup.
1290 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1291 emitAutoVarTypeCleanup(emission, dtorKind);
John McCallf85e1932011-06-15 23:02:42 +00001292
John McCall0c24c802011-06-24 23:21:27 +00001293 // In GC mode, honor objc_precise_lifetime.
David Blaikie4e4d0842012-03-11 07:00:24 +00001294 if (getLangOpts().getGC() != LangOptions::NonGC &&
John McCall0c24c802011-06-24 23:21:27 +00001295 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1296 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1297 }
1298
John McCall34695852011-02-22 06:44:22 +00001299 // Handle the cleanup attribute.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001300 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlsson69c68b72009-02-07 23:51:38 +00001301 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001302
John McCall34695852011-02-22 06:44:22 +00001303 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlsson69c68b72009-02-07 23:51:38 +00001304 assert(F && "Could not find function!");
Mike Stump1eb44332009-09-09 15:08:12 +00001305
John McCallde5d3c72012-02-17 03:33:10 +00001306 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
John McCall34695852011-02-22 06:44:22 +00001307 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlsson69c68b72009-02-07 23:51:38 +00001308 }
Mike Stump797b6322009-03-05 01:23:13 +00001309
John McCall34695852011-02-22 06:44:22 +00001310 // If this is a block variable, call _Block_object_destroy
1311 // (on the unforwarded address).
John McCall5af02db2011-03-31 01:59:53 +00001312 if (emission.IsByRef)
1313 enterByrefCleanup(emission);
Reid Spencer5f016e22007-07-11 17:01:13 +00001314}
1315
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001316CodeGenFunction::Destroyer *
John McCallbdc4d802011-07-09 01:37:26 +00001317CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1318 switch (kind) {
1319 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
John McCall0850e8d2011-07-09 09:09:00 +00001320 case QualType::DK_cxx_destructor:
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001321 return destroyCXXObject;
John McCall0850e8d2011-07-09 09:09:00 +00001322 case QualType::DK_objc_strong_lifetime:
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001323 return destroyARCStrongPrecise;
John McCall0850e8d2011-07-09 09:09:00 +00001324 case QualType::DK_objc_weak_lifetime:
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001325 return destroyARCWeak;
John McCallbdc4d802011-07-09 01:37:26 +00001326 }
Matt Beaumont-Gayba4be252012-01-27 00:46:27 +00001327 llvm_unreachable("Unknown DestructionKind");
John McCallbdc4d802011-07-09 01:37:26 +00001328}
1329
John McCall074cae02013-02-01 05:11:40 +00001330/// pushEHDestroy - Push the standard destructor for the given type as
1331/// an EH-only cleanup.
1332void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
1333 llvm::Value *addr, QualType type) {
1334 assert(dtorKind && "cannot push destructor for trivial type");
1335 assert(needsEHCleanup(dtorKind));
1336
1337 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1338}
1339
1340/// pushDestroy - Push the standard destructor for the given type as
1341/// at least a normal cleanup.
John McCall9928c482011-07-12 16:41:08 +00001342void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
1343 llvm::Value *addr, QualType type) {
1344 assert(dtorKind && "cannot push destructor for trivial type");
1345
1346 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1347 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1348 cleanupKind & EHCleanup);
1349}
1350
John McCallbdc4d802011-07-09 01:37:26 +00001351void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *addr,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001352 QualType type, Destroyer *destroyer,
John McCall2673c682011-07-11 08:38:19 +00001353 bool useEHCleanupForArray) {
John McCall9928c482011-07-12 16:41:08 +00001354 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1355 destroyer, useEHCleanupForArray);
John McCallbdc4d802011-07-09 01:37:26 +00001356}
1357
Richard Smith8a07cd32013-06-12 20:42:33 +00001358void CodeGenFunction::pushLifetimeExtendedDestroy(
1359 CleanupKind cleanupKind, llvm::Value *addr, QualType type,
1360 Destroyer *destroyer, bool useEHCleanupForArray) {
1361 assert(!isInConditionalBranch() &&
1362 "performing lifetime extension from within conditional");
1363
1364 // Push an EH-only cleanup for the object now.
1365 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1366 // around in case a temporary's destructor throws an exception.
1367 if (cleanupKind & EHCleanup)
1368 EHStack.pushCleanup<DestroyObject>(
1369 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1370 destroyer, useEHCleanupForArray);
1371
1372 // Remember that we need to push a full cleanup for the object at the
1373 // end of the full-expression.
1374 pushCleanupAfterFullExpr<DestroyObject>(
1375 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1376}
1377
John McCall2673c682011-07-11 08:38:19 +00001378/// emitDestroy - Immediately perform the destruction of the given
1379/// object.
1380///
1381/// \param addr - the address of the object; a type*
1382/// \param type - the type of the object; if an array type, all
1383/// objects are destroyed in reverse order
1384/// \param destroyer - the function to call to destroy individual
1385/// elements
1386/// \param useEHCleanupForArray - whether an EH cleanup should be
1387/// used when destroying array elements, in case one of the
1388/// destructions throws an exception
John McCallbdc4d802011-07-09 01:37:26 +00001389void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001390 Destroyer *destroyer,
John McCall2673c682011-07-11 08:38:19 +00001391 bool useEHCleanupForArray) {
John McCallbdc4d802011-07-09 01:37:26 +00001392 const ArrayType *arrayType = getContext().getAsArrayType(type);
1393 if (!arrayType)
1394 return destroyer(*this, addr, type);
1395
1396 llvm::Value *begin = addr;
1397 llvm::Value *length = emitArrayLength(arrayType, type, begin);
John McCallfbf780a2011-07-13 08:09:46 +00001398
1399 // Normally we have to check whether the array is zero-length.
1400 bool checkZeroLength = true;
1401
1402 // But if the array length is constant, we can suppress that.
1403 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1404 // ...and if it's constant zero, we can just skip the entire thing.
1405 if (constLength->isZero()) return;
1406 checkZeroLength = false;
1407 }
1408
John McCallbdc4d802011-07-09 01:37:26 +00001409 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
John McCallfbf780a2011-07-13 08:09:46 +00001410 emitArrayDestroy(begin, end, type, destroyer,
1411 checkZeroLength, useEHCleanupForArray);
John McCallbdc4d802011-07-09 01:37:26 +00001412}
1413
John McCall2673c682011-07-11 08:38:19 +00001414/// emitArrayDestroy - Destroys all the elements of the given array,
1415/// beginning from last to first. The array cannot be zero-length.
1416///
1417/// \param begin - a type* denoting the first element of the array
1418/// \param end - a type* denoting one past the end of the array
1419/// \param type - the element type of the array
1420/// \param destroyer - the function to call to destroy elements
1421/// \param useEHCleanup - whether to push an EH cleanup to destroy
1422/// the remaining elements in case the destruction of a single
1423/// element throws
John McCallbdc4d802011-07-09 01:37:26 +00001424void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1425 llvm::Value *end,
1426 QualType type,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001427 Destroyer *destroyer,
John McCallfbf780a2011-07-13 08:09:46 +00001428 bool checkZeroLength,
John McCall2673c682011-07-11 08:38:19 +00001429 bool useEHCleanup) {
John McCallbdc4d802011-07-09 01:37:26 +00001430 assert(!type->isArrayType());
1431
1432 // The basic structure here is a do-while loop, because we don't
1433 // need to check for the zero-element case.
1434 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1435 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1436
John McCallfbf780a2011-07-13 08:09:46 +00001437 if (checkZeroLength) {
1438 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1439 "arraydestroy.isempty");
1440 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1441 }
1442
John McCallbdc4d802011-07-09 01:37:26 +00001443 // Enter the loop body, making that address the current address.
1444 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1445 EmitBlock(bodyBB);
1446 llvm::PHINode *elementPast =
1447 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1448 elementPast->addIncoming(end, entryBB);
1449
1450 // Shift the address back by one element.
1451 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1452 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1453 "arraydestroy.element");
1454
John McCall2673c682011-07-11 08:38:19 +00001455 if (useEHCleanup)
1456 pushRegularPartialArrayCleanup(begin, element, type, destroyer);
1457
John McCallbdc4d802011-07-09 01:37:26 +00001458 // Perform the actual destruction there.
1459 destroyer(*this, element, type);
1460
John McCall2673c682011-07-11 08:38:19 +00001461 if (useEHCleanup)
1462 PopCleanupBlock();
1463
John McCallbdc4d802011-07-09 01:37:26 +00001464 // Check whether we've reached the end.
1465 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1466 Builder.CreateCondBr(done, doneBB, bodyBB);
1467 elementPast->addIncoming(element, Builder.GetInsertBlock());
1468
1469 // Done.
1470 EmitBlock(doneBB);
1471}
1472
John McCall2673c682011-07-11 08:38:19 +00001473/// Perform partial array destruction as if in an EH cleanup. Unlike
1474/// emitArrayDestroy, the element type here may still be an array type.
John McCall2673c682011-07-11 08:38:19 +00001475static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1476 llvm::Value *begin, llvm::Value *end,
1477 QualType type,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001478 CodeGenFunction::Destroyer *destroyer) {
John McCall2673c682011-07-11 08:38:19 +00001479 // If the element type is itself an array, drill down.
John McCallfbf780a2011-07-13 08:09:46 +00001480 unsigned arrayDepth = 0;
John McCall2673c682011-07-11 08:38:19 +00001481 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1482 // VLAs don't require a GEP index to walk into.
1483 if (!isa<VariableArrayType>(arrayType))
John McCallfbf780a2011-07-13 08:09:46 +00001484 arrayDepth++;
John McCall2673c682011-07-11 08:38:19 +00001485 type = arrayType->getElementType();
1486 }
John McCallfbf780a2011-07-13 08:09:46 +00001487
1488 if (arrayDepth) {
1489 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, arrayDepth+1);
1490
Chris Lattner5f9e2722011-07-23 10:55:15 +00001491 SmallVector<llvm::Value*,4> gepIndices(arrayDepth, zero);
Jay Foad0f6ac7c2011-07-22 08:16:57 +00001492 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1493 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
John McCall2673c682011-07-11 08:38:19 +00001494 }
1495
John McCallfbf780a2011-07-13 08:09:46 +00001496 // Destroy the array. We don't ever need an EH cleanup because we
1497 // assume that we're in an EH cleanup ourselves, so a throwing
1498 // destructor causes an immediate terminate.
1499 CGF.emitArrayDestroy(begin, end, type, destroyer,
1500 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
John McCall2673c682011-07-11 08:38:19 +00001501}
1502
John McCallbdc4d802011-07-09 01:37:26 +00001503namespace {
John McCall2673c682011-07-11 08:38:19 +00001504 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1505 /// array destroy where the end pointer is regularly determined and
1506 /// does not need to be loaded from a local.
1507 class RegularPartialArrayDestroy : public EHScopeStack::Cleanup {
1508 llvm::Value *ArrayBegin;
1509 llvm::Value *ArrayEnd;
1510 QualType ElementType;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001511 CodeGenFunction::Destroyer *Destroyer;
John McCall2673c682011-07-11 08:38:19 +00001512 public:
1513 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
1514 QualType elementType,
1515 CodeGenFunction::Destroyer *destroyer)
1516 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001517 ElementType(elementType), Destroyer(destroyer) {}
John McCall2673c682011-07-11 08:38:19 +00001518
John McCallad346f42011-07-12 20:27:29 +00001519 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall2673c682011-07-11 08:38:19 +00001520 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
1521 ElementType, Destroyer);
1522 }
1523 };
1524
1525 /// IrregularPartialArrayDestroy - a cleanup which performs a
1526 /// partial array destroy where the end pointer is irregularly
1527 /// determined and must be loaded from a local.
1528 class IrregularPartialArrayDestroy : public EHScopeStack::Cleanup {
John McCallbdc4d802011-07-09 01:37:26 +00001529 llvm::Value *ArrayBegin;
1530 llvm::Value *ArrayEndPointer;
1531 QualType ElementType;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001532 CodeGenFunction::Destroyer *Destroyer;
John McCallbdc4d802011-07-09 01:37:26 +00001533 public:
John McCall2673c682011-07-11 08:38:19 +00001534 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
1535 llvm::Value *arrayEndPointer,
1536 QualType elementType,
1537 CodeGenFunction::Destroyer *destroyer)
John McCallbdc4d802011-07-09 01:37:26 +00001538 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001539 ElementType(elementType), Destroyer(destroyer) {}
John McCallbdc4d802011-07-09 01:37:26 +00001540
John McCallad346f42011-07-12 20:27:29 +00001541 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallbdc4d802011-07-09 01:37:26 +00001542 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
John McCall2673c682011-07-11 08:38:19 +00001543 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
1544 ElementType, Destroyer);
John McCallbdc4d802011-07-09 01:37:26 +00001545 }
1546 };
1547}
1548
John McCall2673c682011-07-11 08:38:19 +00001549/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
John McCallbdc4d802011-07-09 01:37:26 +00001550/// already-constructed elements of the given array. The cleanup
John McCall2673c682011-07-11 08:38:19 +00001551/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christophere1f54902011-08-23 22:38:00 +00001552///
John McCallbdc4d802011-07-09 01:37:26 +00001553/// \param elementType - the immediate element type of the array;
1554/// possibly still an array type
John McCall9928c482011-07-12 16:41:08 +00001555void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
John McCall2673c682011-07-11 08:38:19 +00001556 llvm::Value *arrayEndPointer,
1557 QualType elementType,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001558 Destroyer *destroyer) {
John McCall9928c482011-07-12 16:41:08 +00001559 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1560 arrayBegin, arrayEndPointer,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001561 elementType, destroyer);
John McCall2673c682011-07-11 08:38:19 +00001562}
1563
1564/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1565/// already-constructed elements of the given array. The cleanup
1566/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christophere1f54902011-08-23 22:38:00 +00001567///
John McCall2673c682011-07-11 08:38:19 +00001568/// \param elementType - the immediate element type of the array;
1569/// possibly still an array type
John McCall2673c682011-07-11 08:38:19 +00001570void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1571 llvm::Value *arrayEnd,
1572 QualType elementType,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001573 Destroyer *destroyer) {
John McCall9928c482011-07-12 16:41:08 +00001574 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
John McCall2673c682011-07-11 08:38:19 +00001575 arrayBegin, arrayEnd,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001576 elementType, destroyer);
John McCallbdc4d802011-07-09 01:37:26 +00001577}
1578
Nadav Rotem495cfa42013-03-23 06:43:35 +00001579/// Lazily declare the @llvm.lifetime.start intrinsic.
1580llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
1581 if (LifetimeStartFn) return LifetimeStartFn;
1582 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1583 llvm::Intrinsic::lifetime_start);
1584 return LifetimeStartFn;
1585}
1586
1587/// Lazily declare the @llvm.lifetime.end intrinsic.
1588llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
1589 if (LifetimeEndFn) return LifetimeEndFn;
1590 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1591 llvm::Intrinsic::lifetime_end);
1592 return LifetimeEndFn;
1593}
1594
John McCallf85e1932011-06-15 23:02:42 +00001595namespace {
1596 /// A cleanup to perform a release of an object at the end of a
1597 /// function. This is used to balance out the incoming +1 of a
1598 /// ns_consumed argument when we can't reasonably do that just by
1599 /// not doing the initial retain for a __block argument.
1600 struct ConsumeARCParameter : EHScopeStack::Cleanup {
John McCall5b07e802013-03-13 03:10:54 +00001601 ConsumeARCParameter(llvm::Value *param,
1602 ARCPreciseLifetime_t precise)
1603 : Param(param), Precise(precise) {}
John McCallf85e1932011-06-15 23:02:42 +00001604
1605 llvm::Value *Param;
John McCall5b07e802013-03-13 03:10:54 +00001606 ARCPreciseLifetime_t Precise;
John McCallf85e1932011-06-15 23:02:42 +00001607
John McCallad346f42011-07-12 20:27:29 +00001608 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall5b07e802013-03-13 03:10:54 +00001609 CGF.EmitARCRelease(Param, Precise);
John McCallf85e1932011-06-15 23:02:42 +00001610 }
1611 };
1612}
1613
Mike Stump1eb44332009-09-09 15:08:12 +00001614/// Emit an alloca (or GlobalValue depending on target)
Chris Lattner2621fd12008-05-08 05:58:21 +00001615/// for the specified parameter and set up LocalDeclMap.
Devang Patel093ac462011-03-03 20:13:15 +00001616void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
1617 unsigned ArgNo) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001618 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Gupta31fc07d2008-10-31 09:52:39 +00001619 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001620 "Invalid argument to EmitParmDecl");
John McCall8178df32011-02-22 22:38:33 +00001621
1622 Arg->setName(D.getName());
1623
Adrian Prantl836e7c92013-03-14 17:53:33 +00001624 QualType Ty = D.getType();
1625
John McCall8178df32011-02-22 22:38:33 +00001626 // Use better IR generation for certain implicit parameters.
1627 if (isa<ImplicitParamDecl>(D)) {
1628 // The only implicit argument a block has is its literal.
1629 if (BlockInfo) {
1630 LocalDeclMap[&D] = Arg;
Adrian Prantl836e7c92013-03-14 17:53:33 +00001631 llvm::Value *LocalAddr = 0;
1632 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
Adrian Prantl9b97adf2013-03-29 19:20:35 +00001633 // Allocate a stack slot to let the debug info survive the RA.
Adrian Prantl836e7c92013-03-14 17:53:33 +00001634 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1635 D.getName() + ".addr");
1636 Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity());
1637 LValue lv = MakeAddrLValue(Alloc, Ty, getContext().getDeclAlign(&D));
1638 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
1639 LocalAddr = Builder.CreateLoad(Alloc);
1640 }
John McCall8178df32011-02-22 22:38:33 +00001641
1642 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregor4cdad312012-10-23 20:05:01 +00001643 if (CGM.getCodeGenOpts().getDebugInfo()
1644 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001645 DI->setLocation(D.getLocation());
Adrian Prantl836e7c92013-03-14 17:53:33 +00001646 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, LocalAddr, Builder);
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001647 }
John McCall8178df32011-02-22 22:38:33 +00001648 }
1649
1650 return;
1651 }
1652 }
1653
Reid Spencer5f016e22007-07-11 17:01:13 +00001654 llvm::Value *DeclPtr;
Daniel Dunbare86bcf02010-02-08 22:53:07 +00001655 // If this is an aggregate or variable sized value, reuse the input pointer.
1656 if (!Ty->isConstantSizeType() ||
John McCall9d232c82013-03-07 21:37:08 +00001657 !CodeGenFunction::hasScalarEvaluationKind(Ty)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001658 DeclPtr = Arg;
Reid Spencer5f016e22007-07-11 17:01:13 +00001659 } else {
Daniel Dunbare86bcf02010-02-08 22:53:07 +00001660 // Otherwise, create a temporary to hold the value.
Eli Friedmanddfb8d12011-11-03 20:31:28 +00001661 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1662 D.getName() + ".addr");
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001663 CharUnits Align = getContext().getDeclAlign(&D);
1664 Alloc->setAlignment(Align.getQuantity());
Eli Friedmanddfb8d12011-11-03 20:31:28 +00001665 DeclPtr = Alloc;
Mike Stump1eb44332009-09-09 15:08:12 +00001666
John McCallf85e1932011-06-15 23:02:42 +00001667 bool doStore = true;
1668
1669 Qualifiers qs = Ty.getQualifiers();
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001670 LValue lv = MakeAddrLValue(DeclPtr, Ty, Align);
John McCallf85e1932011-06-15 23:02:42 +00001671 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1672 // We honor __attribute__((ns_consumed)) for types with lifetime.
1673 // For __strong, it's handled by just skipping the initial retain;
1674 // otherwise we have to balance out the initial +1 with an extra
1675 // cleanup to do the release at the end of the function.
1676 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1677
1678 // 'self' is always formally __strong, but if this is not an
1679 // init method then we don't want to retain it.
John McCall7acddac2011-06-17 06:42:21 +00001680 if (D.isARCPseudoStrong()) {
John McCallf85e1932011-06-15 23:02:42 +00001681 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1682 assert(&D == method->getSelfDecl());
John McCall7acddac2011-06-17 06:42:21 +00001683 assert(lt == Qualifiers::OCL_Strong);
1684 assert(qs.hasConst());
John McCallf85e1932011-06-15 23:02:42 +00001685 assert(method->getMethodFamily() != OMF_init);
John McCall175d6592011-06-15 23:40:09 +00001686 (void) method;
John McCallf85e1932011-06-15 23:02:42 +00001687 lt = Qualifiers::OCL_ExplicitNone;
1688 }
1689
1690 if (lt == Qualifiers::OCL_Strong) {
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001691 if (!isConsumed) {
1692 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1693 // use objc_storeStrong(&dest, value) for retaining the
1694 // object. But first, store a null into 'dest' because
1695 // objc_storeStrong attempts to release its old value.
1696 llvm::Value * Null = CGM.EmitNullConstant(D.getType());
1697 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
1698 EmitARCStoreStrongCall(lv.getAddress(), Arg, true);
1699 doStore = false;
1700 }
1701 else
John McCallf85e1932011-06-15 23:02:42 +00001702 // Don't use objc_retainBlock for block pointers, because we
1703 // don't want to Block_copy something just because we got it
1704 // as a parameter.
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001705 Arg = EmitARCRetainNonBlock(Arg);
1706 }
John McCallf85e1932011-06-15 23:02:42 +00001707 } else {
1708 // Push the cleanup for a consumed parameter.
John McCall5b07e802013-03-13 03:10:54 +00001709 if (isConsumed) {
1710 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1711 ? ARCPreciseLifetime : ARCImpreciseLifetime);
1712 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg,
1713 precise);
1714 }
John McCallf85e1932011-06-15 23:02:42 +00001715
1716 if (lt == Qualifiers::OCL_Weak) {
1717 EmitARCInitWeak(DeclPtr, Arg);
Chad Rosier7acebfb2012-02-18 01:20:35 +00001718 doStore = false; // The weak init is a store, no need to do two.
John McCallf85e1932011-06-15 23:02:42 +00001719 }
1720 }
1721
1722 // Enter the cleanup scope.
1723 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1724 }
1725
Daniel Dunbare86bcf02010-02-08 22:53:07 +00001726 // Store the initial value into the alloca.
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001727 if (doStore)
David Chisnall7a7ee302012-01-16 17:27:18 +00001728 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001729 }
1730
1731 llvm::Value *&DMEntry = LocalDeclMap[&D];
1732 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
1733 DMEntry = DeclPtr;
Sanjiv Guptacc9b1632008-05-30 10:30:31 +00001734
1735 // Emit debug info for param declaration.
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001736 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregor4cdad312012-10-23 20:05:01 +00001737 if (CGM.getCodeGenOpts().getDebugInfo()
1738 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001739 DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
1740 }
1741 }
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001742
1743 if (D.hasAttr<AnnotateAttr>())
1744 EmitVarAnnotations(&D, DeclPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001745}