blob: 0f8ab1b0b39e5ffe20cbcb3621361d1f05a84385 [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:
Larisse Voufoef4579c2013-08-06 01:03:05 +000040 case Decl::VarTemplateSpecialization:
41 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor08688ac2010-04-23 02:02:43 +000042 case Decl::TemplateTypeParm:
43 case Decl::UnresolvedUsingValue:
Sean Hunt9a555912010-05-30 07:21:58 +000044 case Decl::NonTypeTemplateParm:
Douglas Gregor08688ac2010-04-23 02:02:43 +000045 case Decl::CXXMethod:
46 case Decl::CXXConstructor:
47 case Decl::CXXDestructor:
48 case Decl::CXXConversion:
49 case Decl::Field:
John McCall76da55d2013-04-16 07:28:30 +000050 case Decl::MSProperty:
Francois Pichet41f5e662010-11-21 06:49:41 +000051 case Decl::IndirectField:
Douglas Gregor08688ac2010-04-23 02:02:43 +000052 case Decl::ObjCIvar:
Eric Christophere1f54902011-08-23 22:38:00 +000053 case Decl::ObjCAtDefsField:
Chris Lattneraa9fc462007-10-08 21:37:32 +000054 case Decl::ParmVar:
Douglas Gregor08688ac2010-04-23 02:02:43 +000055 case Decl::ImplicitParam:
56 case Decl::ClassTemplate:
Larisse Voufoef4579c2013-08-06 01:03:05 +000057 case Decl::VarTemplate:
Douglas Gregor08688ac2010-04-23 02:02:43 +000058 case Decl::FunctionTemplate:
Richard Smith3e4c6c42011-05-05 21:57:07 +000059 case Decl::TypeAliasTemplate:
Douglas Gregor08688ac2010-04-23 02:02:43 +000060 case Decl::TemplateTemplateParm:
61 case Decl::ObjCMethod:
62 case Decl::ObjCCategory:
63 case Decl::ObjCProtocol:
64 case Decl::ObjCInterface:
65 case Decl::ObjCCategoryImpl:
66 case Decl::ObjCImplementation:
67 case Decl::ObjCProperty:
68 case Decl::ObjCCompatibleAlias:
Abramo Bagnara6206d532010-06-05 05:09:32 +000069 case Decl::AccessSpec:
Douglas Gregor08688ac2010-04-23 02:02:43 +000070 case Decl::LinkageSpec:
71 case Decl::ObjCPropertyImpl:
Douglas Gregor08688ac2010-04-23 02:02:43 +000072 case Decl::FileScopeAsm:
73 case Decl::Friend:
74 case Decl::FriendTemplate:
75 case Decl::Block:
Tareq A. Siraj6afcf882013-04-16 19:37:38 +000076 case Decl::Captured:
Francois Pichetaf0f4d02011-08-14 03:52:19 +000077 case Decl::ClassScopeFunctionSpecialization:
David Blaikie9faebd22013-05-20 04:58:53 +000078 case Decl::UsingShadow:
David Blaikieb219cfc2011-09-23 05:06:16 +000079 llvm_unreachable("Declaration should not be in declstmts!");
Reid Spencer5f016e22007-07-11 17:01:13 +000080 case Decl::Function: // void X();
Argyrios Kyrtzidis35bc0822008-10-15 00:42:39 +000081 case Decl::Record: // struct/union/class X;
Reid Spencer5f016e22007-07-11 17:01:13 +000082 case Decl::Enum: // enum X;
Mike Stump1eb44332009-09-09 15:08:12 +000083 case Decl::EnumConstant: // enum ? { X = ? }
Argyrios Kyrtzidis35bc0822008-10-15 00:42:39 +000084 case Decl::CXXRecord: // struct/union/class X; [C++]
Anders Carlsson7b0ca3f2009-12-03 17:26:31 +000085 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
Chris Lattner4ae493c2011-02-18 02:08:43 +000086 case Decl::Label: // __label__ x;
Douglas Gregor15de72c2011-12-02 23:23:56 +000087 case Decl::Import:
Alexey Bataevc6400582013-03-22 06:34:35 +000088 case Decl::OMPThreadPrivate:
Michael Han684aa732013-02-22 17:15:32 +000089 case Decl::Empty:
Reid Spencer5f016e22007-07-11 17:01:13 +000090 // None of these decls require codegen support.
91 return;
David Blaikiec8c24272013-02-02 00:39:32 +000092
David Blaikiefc46ebc2013-05-20 22:50:41 +000093 case Decl::NamespaceAlias:
94 if (CGDebugInfo *DI = getDebugInfo())
95 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
96 return;
David Blaikie9faebd22013-05-20 04:58:53 +000097 case Decl::Using: // using X; [C++]
98 if (CGDebugInfo *DI = getDebugInfo())
99 DI->EmitUsingDecl(cast<UsingDecl>(D));
100 return;
David Blaikie957dac52013-04-22 06:13:21 +0000101 case Decl::UsingDirective: // using namespace X; [C++]
102 if (CGDebugInfo *DI = getDebugInfo())
103 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
104 return;
Daniel Dunbar662174c82008-08-29 17:28:43 +0000105 case Decl::Var: {
106 const VarDecl &VD = cast<VarDecl>(D);
John McCallb6bbcc92010-10-15 04:57:14 +0000107 assert(VD.isLocalVarDecl() &&
Daniel Dunbar662174c82008-08-29 17:28:43 +0000108 "Should not see file-scope variables inside a function!");
John McCallb6bbcc92010-10-15 04:57:14 +0000109 return EmitVarDecl(VD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000110 }
Mike Stump1eb44332009-09-09 15:08:12 +0000111
Richard Smith162e1c12011-04-15 14:24:37 +0000112 case Decl::Typedef: // typedef int X;
113 case Decl::TypeAlias: { // using X = int; [C++0x]
114 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000115 QualType Ty = TD.getUnderlyingType();
Mike Stump1eb44332009-09-09 15:08:12 +0000116
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000117 if (Ty->isVariablyModifiedType())
John McCallbc8d40d2011-06-24 21:55:10 +0000118 EmitVariablyModifiedType(Ty);
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000119 }
Daniel Dunbar662174c82008-08-29 17:28:43 +0000120 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000121}
122
John McCallb6bbcc92010-10-15 04:57:14 +0000123/// EmitVarDecl - This method handles emission of any variable declaration
Reid Spencer5f016e22007-07-11 17:01:13 +0000124/// inside a function, including static vars etc.
John McCallb6bbcc92010-10-15 04:57:14 +0000125void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Enea Zaffanella713e3f22013-05-16 11:27:56 +0000126 if (D.isStaticLocal()) {
Eric Christophere1f54902011-08-23 22:38:00 +0000127 llvm::GlobalValue::LinkageTypes Linkage =
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000128 llvm::GlobalValue::InternalLinkage;
129
Eli Friedman7a36a592013-07-01 20:53:07 +0000130 // If the variable is externally visible, it must have weak linkage so it
131 // can be uniqued.
Rafael Espindola9610d772013-06-17 20:04:51 +0000132 if (D.isExternallyVisible()) {
Eli Friedman7a36a592013-07-01 20:53:07 +0000133 Linkage = llvm::GlobalValue::LinkOnceODRLinkage;
Eli Friedman07369dd2013-07-01 20:22:57 +0000134
135 // FIXME: We need to force the emission/use of a guard variable for
136 // some variables even if we can constant-evaluate them because
137 // we can't guarantee every translation unit will constant-evaluate them.
Eli Friedman678eca42013-06-13 21:50:44 +0000138 }
Eric Christophere1f54902011-08-23 22:38:00 +0000139
John McCallb6bbcc92010-10-15 04:57:14 +0000140 return EmitStaticVarDecl(D, Linkage);
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000141 }
Enea Zaffanella713e3f22013-05-16 11:27:56 +0000142
143 if (D.hasExternalStorage())
Lauro Ramos Venanciofea90b82008-02-16 22:30:38 +0000144 // Don't emit it now, allow it to be emitted lazily on its first use.
145 return;
Daniel Dunbar5466c7b2009-04-14 02:25:56 +0000146
Enea Zaffanella713e3f22013-05-16 11:27:56 +0000147 if (D.getStorageClass() == SC_OpenCLWorkGroupLocal)
148 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
149
150 assert(D.hasLocalStorage());
151 return EmitAutoVarDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000152}
153
Chris Lattner761acc12009-12-05 08:22:11 +0000154static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D,
155 const char *Separator) {
156 CodeGenModule &CGM = CGF.CGM;
Richard Smith7edf9e32012-11-01 22:30:59 +0000157 if (CGF.getLangOpts().CPlusPlus) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000158 StringRef Name = CGM.getMangledName(&D);
Anders Carlsson9a20d552010-06-22 16:16:50 +0000159 return Name.str();
John McCallf746aa62010-03-19 23:29:14 +0000160 }
Eric Christophere1f54902011-08-23 22:38:00 +0000161
Chris Lattner761acc12009-12-05 08:22:11 +0000162 std::string ContextName;
Fariborz Jahanianfaa5bfc2010-11-30 23:07:14 +0000163 if (!CGF.CurFuncDecl) {
164 // Better be in a block declared in global scope.
165 const NamedDecl *ND = cast<NamedDecl>(&D);
166 const DeclContext *DC = ND->getDeclContext();
167 if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
168 MangleBuffer Name;
Peter Collingbourne14110472011-01-13 18:57:25 +0000169 CGM.getBlockMangledName(GlobalDecl(), Name, BD);
Fariborz Jahanianfaa5bfc2010-11-30 23:07:14 +0000170 ContextName = Name.getString();
171 }
172 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000173 llvm_unreachable("Unknown context for block static var decl");
Fariborz Jahanianfaa5bfc2010-11-30 23:07:14 +0000174 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000175 StringRef Name = CGM.getMangledName(FD);
Anders Carlsson9a20d552010-06-22 16:16:50 +0000176 ContextName = Name.str();
John McCallf746aa62010-03-19 23:29:14 +0000177 } else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
Chris Lattner761acc12009-12-05 08:22:11 +0000178 ContextName = CGF.CurFn->getName();
179 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000180 llvm_unreachable("Unknown context for static var decl");
Eric Christophere1f54902011-08-23 22:38:00 +0000181
Chris Lattner761acc12009-12-05 08:22:11 +0000182 return ContextName + Separator + D.getNameAsString();
183}
184
Chandler Carruth0f30a122012-03-30 19:44:53 +0000185llvm::GlobalVariable *
John McCallb6bbcc92010-10-15 04:57:14 +0000186CodeGenFunction::CreateStaticVarDecl(const VarDecl &D,
187 const char *Separator,
188 llvm::GlobalValue::LinkageTypes Linkage) {
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000189 QualType Ty = D.getType();
Eli Friedman3c2b3172008-02-15 12:20:59 +0000190 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000191
Benjamin Kramer5c247db2011-11-20 21:05:04 +0000192 // Use the label if the variable is renamed with the asm-label extension.
193 std::string Name;
Benjamin Kramerc3c8f222011-11-21 15:47:23 +0000194 if (D.hasAttr<AsmLabelAttr>())
195 Name = CGM.getMangledName(&D);
196 else
Benjamin Kramer5c247db2011-11-20 21:05:04 +0000197 Name = GetStaticDeclName(*this, D, Separator);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000198
Chris Lattner2acc6e32011-07-18 04:24:23 +0000199 llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
Peter Collingbourne1aba7782012-08-28 20:37:10 +0000200 unsigned AddrSpace =
201 CGM.GetGlobalVarAddressSpace(&D, CGM.getContext().getTargetAddressSpace(Ty));
Anders Carlsson41f8a132009-09-26 18:16:06 +0000202 llvm::GlobalVariable *GV =
203 new llvm::GlobalVariable(CGM.getModule(), LTy,
204 Ty.isConstant(getContext()), Linkage,
Hans Wennborgde981f32012-06-28 08:01:44 +0000205 CGM.EmitNullConstant(D.getType()), Name, 0,
206 llvm::GlobalVariable::NotThreadLocal,
Peter Collingbourne1aba7782012-08-28 20:37:10 +0000207 AddrSpace);
Ken Dyck8b752f12010-01-27 17:10:57 +0000208 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Eli Friedman93cc5152013-06-17 21:51:45 +0000209 CGM.setGlobalVisibility(GV, &D);
Hans Wennborgde981f32012-06-28 08:01:44 +0000210
Richard Smith38afbc72013-04-13 02:43:54 +0000211 if (D.getTLSKind())
Hans Wennborgde981f32012-06-28 08:01:44 +0000212 CGM.setTLSMode(GV, D);
213
Anders Carlsson41f8a132009-09-26 18:16:06 +0000214 return GV;
Daniel Dunbar0096acf2009-02-25 19:24:29 +0000215}
216
Richard Smith7ca48502012-02-13 22:16:19 +0000217/// hasNontrivialDestruction - Determine whether a type's destruction is
218/// non-trivial. If so, and the variable uses static initialization, we must
219/// register its destructor to run on exit.
220static bool hasNontrivialDestruction(QualType T) {
221 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
222 return RD && !RD->hasTrivialDestructor();
223}
224
Chandler Carruth0f30a122012-03-30 19:44:53 +0000225/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
226/// global variable that has already been created for it. If the initializer
227/// has a different type than GV does, this may free GV and return a different
228/// one. Otherwise it just returns GV.
229llvm::GlobalVariable *
John McCallb6bbcc92010-10-15 04:57:14 +0000230CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
Chandler Carruth0f30a122012-03-30 19:44:53 +0000231 llvm::GlobalVariable *GV) {
232 llvm::Constant *Init = CGM.EmitConstantInit(D, this);
John McCallbf40cb52010-07-15 23:40:35 +0000233
Chris Lattner761acc12009-12-05 08:22:11 +0000234 // If constant emission failed, then this should be a C++ static
235 // initializer.
Chandler Carruth0f30a122012-03-30 19:44:53 +0000236 if (!Init) {
Richard Smith7edf9e32012-11-01 22:30:59 +0000237 if (!getLangOpts().CPlusPlus)
Chris Lattner761acc12009-12-05 08:22:11 +0000238 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
John McCall5cd91b52010-09-08 01:44:27 +0000239 else if (Builder.GetInsertBlock()) {
Eric Christophere1f54902011-08-23 22:38:00 +0000240 // Since we have a static initializer, this global variable can't
Anders Carlsson071c8102010-01-26 04:02:23 +0000241 // be constant.
Chandler Carruth0f30a122012-03-30 19:44:53 +0000242 GV->setConstant(false);
John McCall5cd91b52010-09-08 01:44:27 +0000243
Chandler Carruth0f30a122012-03-30 19:44:53 +0000244 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
Anders Carlsson071c8102010-01-26 04:02:23 +0000245 }
Chandler Carruth0f30a122012-03-30 19:44:53 +0000246 return GV;
Chris Lattner761acc12009-12-05 08:22:11 +0000247 }
John McCallbf40cb52010-07-15 23:40:35 +0000248
Chris Lattner761acc12009-12-05 08:22:11 +0000249 // The initializer may differ in type from the global. Rewrite
250 // the global to match the initializer. (We have to do this
251 // because some types, like unions, can't be completely represented
252 // in the LLVM type system.)
Chandler Carruth0f30a122012-03-30 19:44:53 +0000253 if (GV->getType()->getElementType() != Init->getType()) {
254 llvm::GlobalVariable *OldGV = GV;
255
256 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
257 OldGV->isConstant(),
258 OldGV->getLinkage(), Init, "",
259 /*InsertBefore*/ OldGV,
Hans Wennborg5e2d5de2012-06-23 11:51:46 +0000260 OldGV->getThreadLocalMode(),
Chandler Carruth0f30a122012-03-30 19:44:53 +0000261 CGM.getContext().getTargetAddressSpace(D.getType()));
262 GV->setVisibility(OldGV->getVisibility());
Eric Christophere1f54902011-08-23 22:38:00 +0000263
Chris Lattner761acc12009-12-05 08:22:11 +0000264 // Steal the name of the old global
Chandler Carruth0f30a122012-03-30 19:44:53 +0000265 GV->takeName(OldGV);
Eric Christophere1f54902011-08-23 22:38:00 +0000266
Chris Lattner761acc12009-12-05 08:22:11 +0000267 // Replace all uses of the old global with the new global
Chandler Carruth0f30a122012-03-30 19:44:53 +0000268 llvm::Constant *NewPtrForOldDecl =
269 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
270 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eric Christophere1f54902011-08-23 22:38:00 +0000271
Chris Lattner761acc12009-12-05 08:22:11 +0000272 // Erase the old global, since it is no longer used.
Chandler Carruth0f30a122012-03-30 19:44:53 +0000273 OldGV->eraseFromParent();
Chris Lattner761acc12009-12-05 08:22:11 +0000274 }
Eric Christophere1f54902011-08-23 22:38:00 +0000275
Chandler Carruth0f30a122012-03-30 19:44:53 +0000276 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
277 GV->setInitializer(Init);
Richard Smith7ca48502012-02-13 22:16:19 +0000278
279 if (hasNontrivialDestruction(D.getType())) {
280 // We have a constant initializer, but a nontrivial destructor. We still
281 // need to perform a guarded "initialization" in order to register the
Richard Smitha9b21d22012-02-17 06:48:11 +0000282 // destructor.
Chandler Carruth0f30a122012-03-30 19:44:53 +0000283 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
Richard Smith7ca48502012-02-13 22:16:19 +0000284 }
285
Chandler Carruth0f30a122012-03-30 19:44:53 +0000286 return GV;
Chris Lattner761acc12009-12-05 08:22:11 +0000287}
288
John McCallb6bbcc92010-10-15 04:57:14 +0000289void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000290 llvm::GlobalValue::LinkageTypes Linkage) {
Chandler Carruth0f30a122012-03-30 19:44:53 +0000291 llvm::Value *&DMEntry = LocalDeclMap[&D];
292 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
Mike Stump1eb44332009-09-09 15:08:12 +0000293
John McCall355bba72012-03-30 21:00:39 +0000294 // Check to see if we already have a global variable for this
295 // declaration. This can happen when double-emitting function
296 // bodies, e.g. with complete and base constructors.
297 llvm::Constant *addr =
298 CGM.getStaticLocalDeclAddress(&D);
299
300 llvm::GlobalVariable *var;
301 if (addr) {
302 var = cast<llvm::GlobalVariable>(addr->stripPointerCasts());
303 } else {
304 addr = var = CreateStaticVarDecl(D, ".", Linkage);
305 }
Daniel Dunbara985b312009-02-25 19:45:19 +0000306
Daniel Dunbare5731f82009-02-25 20:08:33 +0000307 // Store into LocalDeclMap before generating initializer to handle
308 // circular references.
John McCall355bba72012-03-30 21:00:39 +0000309 DMEntry = addr;
310 CGM.setStaticLocalDeclAddress(&D, addr);
Daniel Dunbare5731f82009-02-25 20:08:33 +0000311
John McCallfe67f3b2010-05-04 20:45:42 +0000312 // We can't have a VLA here, but we can have a pointer to a VLA,
313 // even though that doesn't really make any sense.
Eli Friedmanc62aad82009-04-20 03:54:15 +0000314 // Make sure to evaluate VLA bounds now so that we have them for later.
315 if (D.getType()->isVariablyModifiedType())
John McCallbc8d40d2011-06-24 21:55:10 +0000316 EmitVariablyModifiedType(D.getType());
Eric Christophere1f54902011-08-23 22:38:00 +0000317
John McCall355bba72012-03-30 21:00:39 +0000318 // Save the type in case adding the initializer forces a type change.
319 llvm::Type *expectedType = addr->getType();
Eli Friedmanc62aad82009-04-20 03:54:15 +0000320
Chris Lattner761acc12009-12-05 08:22:11 +0000321 // If this value has an initializer, emit it.
322 if (D.getInit())
John McCall355bba72012-03-30 21:00:39 +0000323 var = AddInitializerToStaticVarDecl(D, var);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000324
John McCall355bba72012-03-30 21:00:39 +0000325 var->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Chris Lattner0af95232010-03-10 23:59:59 +0000326
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000327 if (D.hasAttr<AnnotateAttr>())
John McCall355bba72012-03-30 21:00:39 +0000328 CGM.AddGlobalAnnotations(&D, var);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000329
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000330 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
John McCall355bba72012-03-30 21:00:39 +0000331 var->setSection(SA->getName());
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000333 if (D.hasAttr<UsedAttr>())
John McCall355bba72012-03-30 21:00:39 +0000334 CGM.AddUsedGlobal(var);
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000335
Chandler Carruth0f30a122012-03-30 19:44:53 +0000336 // We may have to cast the constant because of the initializer
337 // mismatch above.
338 //
339 // FIXME: It is really dangerous to store this in the map; if anyone
340 // RAUW's the GV uses of this constant will be invalid.
John McCall355bba72012-03-30 21:00:39 +0000341 llvm::Constant *castedAddr = llvm::ConstantExpr::getBitCast(var, expectedType);
342 DMEntry = castedAddr;
343 CGM.setStaticLocalDeclAddress(&D, castedAddr);
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000344
345 // Emit global variable debug descriptor for static vars.
Anders Carlssone896d982009-02-13 08:11:52 +0000346 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonovfd00eec2012-05-04 07:39:27 +0000347 if (DI &&
Douglas Gregor4cdad312012-10-23 20:05:01 +0000348 CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000349 DI->setLocation(D.getLocation());
John McCall355bba72012-03-30 21:00:39 +0000350 DI->EmitGlobalVariable(var, &D);
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000351 }
Anders Carlsson1a86b332007-10-17 00:52:43 +0000352}
Mike Stump1eb44332009-09-09 15:08:12 +0000353
John McCallda65ea82010-07-13 20:32:21 +0000354namespace {
John McCallbdc4d802011-07-09 01:37:26 +0000355 struct DestroyObject : EHScopeStack::Cleanup {
356 DestroyObject(llvm::Value *addr, QualType type,
John McCall2673c682011-07-11 08:38:19 +0000357 CodeGenFunction::Destroyer *destroyer,
358 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000359 : addr(addr), type(type), destroyer(destroyer),
John McCall2673c682011-07-11 08:38:19 +0000360 useEHCleanupForArray(useEHCleanupForArray) {}
John McCallda65ea82010-07-13 20:32:21 +0000361
John McCallbdc4d802011-07-09 01:37:26 +0000362 llvm::Value *addr;
363 QualType type;
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000364 CodeGenFunction::Destroyer *destroyer;
John McCall2673c682011-07-11 08:38:19 +0000365 bool useEHCleanupForArray;
John McCallda65ea82010-07-13 20:32:21 +0000366
John McCallad346f42011-07-12 20:27:29 +0000367 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall2673c682011-07-11 08:38:19 +0000368 // Don't use an EH cleanup recursively from an EH cleanup.
John McCallad346f42011-07-12 20:27:29 +0000369 bool useEHCleanupForArray =
370 flags.isForNormalCleanup() && this->useEHCleanupForArray;
John McCall2673c682011-07-11 08:38:19 +0000371
372 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
John McCallda65ea82010-07-13 20:32:21 +0000373 }
374 };
375
John McCallbdc4d802011-07-09 01:37:26 +0000376 struct DestroyNRVOVariable : EHScopeStack::Cleanup {
377 DestroyNRVOVariable(llvm::Value *addr,
378 const CXXDestructorDecl *Dtor,
379 llvm::Value *NRVOFlag)
380 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
John McCallda65ea82010-07-13 20:32:21 +0000381
382 const CXXDestructorDecl *Dtor;
383 llvm::Value *NRVOFlag;
384 llvm::Value *Loc;
385
John McCallad346f42011-07-12 20:27:29 +0000386 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallda65ea82010-07-13 20:32:21 +0000387 // Along the exceptions path we always execute the dtor.
John McCallad346f42011-07-12 20:27:29 +0000388 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
John McCallda65ea82010-07-13 20:32:21 +0000389
390 llvm::BasicBlock *SkipDtorBB = 0;
391 if (NRVO) {
392 // If we exited via NRVO, we skip the destructor call.
393 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
394 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
395 llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
396 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
397 CGF.EmitBlock(RunDtorBB);
398 }
Eric Christophere1f54902011-08-23 22:38:00 +0000399
John McCallda65ea82010-07-13 20:32:21 +0000400 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor378e1e72013-01-31 05:50:40 +0000401 /*ForVirtualBase=*/false,
402 /*Delegating=*/false,
403 Loc);
John McCallda65ea82010-07-13 20:32:21 +0000404
405 if (NRVO) CGF.EmitBlock(SkipDtorBB);
406 }
407 };
John McCallda65ea82010-07-13 20:32:21 +0000408
John McCall1f0fca52010-07-21 07:22:38 +0000409 struct CallStackRestore : EHScopeStack::Cleanup {
John McCalld8715092010-07-21 06:13:08 +0000410 llvm::Value *Stack;
411 CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
John McCallad346f42011-07-12 20:27:29 +0000412 void Emit(CodeGenFunction &CGF, Flags flags) {
Benjamin Kramer578faa82011-09-27 21:06:10 +0000413 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
John McCalld8715092010-07-21 06:13:08 +0000414 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
415 CGF.Builder.CreateCall(F, V);
416 }
417 };
418
John McCall0c24c802011-06-24 23:21:27 +0000419 struct ExtendGCLifetime : EHScopeStack::Cleanup {
420 const VarDecl &Var;
421 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
422
John McCallad346f42011-07-12 20:27:29 +0000423 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall0c24c802011-06-24 23:21:27 +0000424 // Compute the address of the local variable, in case it's a
425 // byref or something.
John McCallf4b88a42012-03-10 09:33:50 +0000426 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
427 Var.getType(), VK_LValue, SourceLocation());
Nick Lewycky4ee7dc22013-10-02 02:29:49 +0000428 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
429 SourceLocation());
John McCall0c24c802011-06-24 23:21:27 +0000430 CGF.EmitExtendGCLifetime(value);
431 }
432 };
433
John McCall1f0fca52010-07-21 07:22:38 +0000434 struct CallCleanupFunction : EHScopeStack::Cleanup {
John McCalld8715092010-07-21 06:13:08 +0000435 llvm::Constant *CleanupFn;
436 const CGFunctionInfo &FnInfo;
John McCalld8715092010-07-21 06:13:08 +0000437 const VarDecl &Var;
Eric Christophere1f54902011-08-23 22:38:00 +0000438
John McCalld8715092010-07-21 06:13:08 +0000439 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCall34695852011-02-22 06:44:22 +0000440 const VarDecl *Var)
441 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalld8715092010-07-21 06:13:08 +0000442
John McCallad346f42011-07-12 20:27:29 +0000443 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf4b88a42012-03-10 09:33:50 +0000444 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
445 Var.getType(), VK_LValue, SourceLocation());
John McCall34695852011-02-22 06:44:22 +0000446 // Compute the address of the local variable, in case it's a byref
447 // or something.
448 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
449
John McCalld8715092010-07-21 06:13:08 +0000450 // In some cases, the type of the function argument will be different from
451 // the type of the pointer. An example of this is
452 // void f(void* arg);
453 // __attribute__((cleanup(f))) void *g;
454 //
455 // To fix this we insert a bitcast here.
456 QualType ArgTy = FnInfo.arg_begin()->type;
457 llvm::Value *Arg =
458 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
459
460 CallArgList Args;
Eli Friedman04c9a492011-05-02 17:57:46 +0000461 Args.add(RValue::get(Arg),
462 CGF.getContext().getPointerType(Var.getType()));
John McCalld8715092010-07-21 06:13:08 +0000463 CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
464 }
465 };
Nadav Rotem495cfa42013-03-23 06:43:35 +0000466
467 /// A cleanup to call @llvm.lifetime.end.
468 class CallLifetimeEnd : public EHScopeStack::Cleanup {
469 llvm::Value *Addr;
470 llvm::Value *Size;
471 public:
472 CallLifetimeEnd(llvm::Value *addr, llvm::Value *size)
473 : Addr(addr), Size(size) {}
474
475 void Emit(CodeGenFunction &CGF, Flags flags) {
476 llvm::Value *castAddr = CGF.Builder.CreateBitCast(Addr, CGF.Int8PtrTy);
477 CGF.Builder.CreateCall2(CGF.CGM.getLLVMLifetimeEndFn(),
478 Size, castAddr)
479 ->setDoesNotThrow();
480 }
481 };
John McCalld8715092010-07-21 06:13:08 +0000482}
483
John McCallf85e1932011-06-15 23:02:42 +0000484/// EmitAutoVarWithLifetime - Does the setup required for an automatic
485/// variable with lifetime.
486static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
487 llvm::Value *addr,
488 Qualifiers::ObjCLifetime lifetime) {
489 switch (lifetime) {
490 case Qualifiers::OCL_None:
491 llvm_unreachable("present but none");
492
493 case Qualifiers::OCL_ExplicitNone:
494 // nothing to do
495 break;
496
497 case Qualifiers::OCL_Strong: {
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000498 CodeGenFunction::Destroyer *destroyer =
John McCall9928c482011-07-12 16:41:08 +0000499 (var.hasAttr<ObjCPreciseLifetimeAttr>()
500 ? CodeGenFunction::destroyARCStrongPrecise
501 : CodeGenFunction::destroyARCStrongImprecise);
502
503 CleanupKind cleanupKind = CGF.getARCCleanupKind();
504 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
505 cleanupKind & EHCleanup);
John McCallf85e1932011-06-15 23:02:42 +0000506 break;
507 }
508 case Qualifiers::OCL_Autoreleasing:
509 // nothing to do
510 break;
Eric Christophere1f54902011-08-23 22:38:00 +0000511
John McCallf85e1932011-06-15 23:02:42 +0000512 case Qualifiers::OCL_Weak:
513 // __weak objects always get EH cleanups; otherwise, exceptions
514 // could cause really nasty crashes instead of mere leaks.
John McCall9928c482011-07-12 16:41:08 +0000515 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
516 CodeGenFunction::destroyARCWeak,
517 /*useEHCleanup*/ true);
John McCallf85e1932011-06-15 23:02:42 +0000518 break;
519 }
520}
521
522static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
523 if (const Expr *e = dyn_cast<Expr>(s)) {
524 // Skip the most common kinds of expressions that make
525 // hierarchy-walking expensive.
526 s = e = e->IgnoreParenCasts();
527
528 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
529 return (ref->getDecl() == &var);
Fariborz Jahanianddfc8a12012-06-19 20:53:26 +0000530 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
531 const BlockDecl *block = be->getBlockDecl();
532 for (BlockDecl::capture_const_iterator i = block->capture_begin(),
533 e = block->capture_end(); i != e; ++i) {
534 if (i->getVariable() == &var)
535 return true;
536 }
537 }
John McCallf85e1932011-06-15 23:02:42 +0000538 }
539
540 for (Stmt::const_child_range children = s->children(); children; ++children)
Fariborz Jahanian8fefc8e2011-06-29 20:00:16 +0000541 // children might be null; as in missing decl or conditional of an if-stmt.
542 if ((*children) && isAccessedBy(var, *children))
John McCallf85e1932011-06-15 23:02:42 +0000543 return true;
544
545 return false;
546}
547
548static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
549 if (!decl) return false;
550 if (!isa<VarDecl>(decl)) return false;
551 const VarDecl *var = cast<VarDecl>(decl);
552 return isAccessedBy(*var, e);
553}
554
John McCalla07398e2011-06-16 04:16:24 +0000555static void drillIntoBlockVariable(CodeGenFunction &CGF,
556 LValue &lvalue,
557 const VarDecl *var) {
558 lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var));
559}
560
John McCallf85e1932011-06-15 23:02:42 +0000561void CodeGenFunction::EmitScalarInit(const Expr *init,
562 const ValueDecl *D,
John McCalla07398e2011-06-16 04:16:24 +0000563 LValue lvalue,
564 bool capturedByInit) {
John McCalla07398e2011-06-16 04:16:24 +0000565 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
John McCallf85e1932011-06-15 23:02:42 +0000566 if (!lifetime) {
567 llvm::Value *value = EmitScalarExpr(init);
John McCalla07398e2011-06-16 04:16:24 +0000568 if (capturedByInit)
569 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Chisnall7a7ee302012-01-16 17:27:18 +0000570 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
John McCallf85e1932011-06-15 23:02:42 +0000571 return;
572 }
573
574 // If we're emitting a value with lifetime, we have to do the
575 // initialization *before* we leave the cleanup scopes.
John McCall1a343eb2011-11-10 08:15:53 +0000576 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
577 enterFullExpression(ewc);
John McCallf85e1932011-06-15 23:02:42 +0000578 init = ewc->getSubExpr();
John McCall1a343eb2011-11-10 08:15:53 +0000579 }
580 CodeGenFunction::RunCleanupsScope Scope(*this);
John McCallf85e1932011-06-15 23:02:42 +0000581
582 // We have to maintain the illusion that the variable is
583 // zero-initialized. If the variable might be accessed in its
584 // initializer, zero-initialize before running the initializer, then
585 // actually perform the initialization with an assign.
586 bool accessedByInit = false;
587 if (lifetime != Qualifiers::OCL_ExplicitNone)
John McCallfb720812011-07-28 07:23:35 +0000588 accessedByInit = (capturedByInit || isAccessedBy(D, init));
John McCallf85e1932011-06-15 23:02:42 +0000589 if (accessedByInit) {
John McCalla07398e2011-06-16 04:16:24 +0000590 LValue tempLV = lvalue;
John McCallf85e1932011-06-15 23:02:42 +0000591 // Drill down to the __block object if necessary.
John McCallf85e1932011-06-15 23:02:42 +0000592 if (capturedByInit) {
593 // We can use a simple GEP for this because it can't have been
594 // moved yet.
John McCalla07398e2011-06-16 04:16:24 +0000595 tempLV.setAddress(Builder.CreateStructGEP(tempLV.getAddress(),
596 getByRefValueLLVMField(cast<VarDecl>(D))));
John McCallf85e1932011-06-15 23:02:42 +0000597 }
598
Chris Lattner2acc6e32011-07-18 04:24:23 +0000599 llvm::PointerType *ty
John McCalla07398e2011-06-16 04:16:24 +0000600 = cast<llvm::PointerType>(tempLV.getAddress()->getType());
John McCallf85e1932011-06-15 23:02:42 +0000601 ty = cast<llvm::PointerType>(ty->getElementType());
602
603 llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
Eric Christophere1f54902011-08-23 22:38:00 +0000604
John McCallf85e1932011-06-15 23:02:42 +0000605 // If __weak, we want to use a barrier under certain conditions.
606 if (lifetime == Qualifiers::OCL_Weak)
John McCalla07398e2011-06-16 04:16:24 +0000607 EmitARCInitWeak(tempLV.getAddress(), zero);
John McCallf85e1932011-06-15 23:02:42 +0000608
609 // Otherwise just do a simple store.
610 else
David Chisnall7a7ee302012-01-16 17:27:18 +0000611 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
John McCallf85e1932011-06-15 23:02:42 +0000612 }
613
614 // Emit the initializer.
615 llvm::Value *value = 0;
616
617 switch (lifetime) {
618 case Qualifiers::OCL_None:
619 llvm_unreachable("present but none");
620
621 case Qualifiers::OCL_ExplicitNone:
622 // nothing to do
623 value = EmitScalarExpr(init);
624 break;
625
626 case Qualifiers::OCL_Strong: {
627 value = EmitARCRetainScalarExpr(init);
628 break;
629 }
630
631 case Qualifiers::OCL_Weak: {
632 // No way to optimize a producing initializer into this. It's not
633 // worth optimizing for, because the value will immediately
634 // disappear in the common case.
635 value = EmitScalarExpr(init);
636
John McCalla07398e2011-06-16 04:16:24 +0000637 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCallf85e1932011-06-15 23:02:42 +0000638 if (accessedByInit)
John McCalla07398e2011-06-16 04:16:24 +0000639 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
John McCallf85e1932011-06-15 23:02:42 +0000640 else
John McCalla07398e2011-06-16 04:16:24 +0000641 EmitARCInitWeak(lvalue.getAddress(), value);
John McCallf85e1932011-06-15 23:02:42 +0000642 return;
643 }
644
645 case Qualifiers::OCL_Autoreleasing:
646 value = EmitARCRetainAutoreleaseScalarExpr(init);
647 break;
648 }
649
John McCalla07398e2011-06-16 04:16:24 +0000650 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCallf85e1932011-06-15 23:02:42 +0000651
652 // If the variable might have been accessed by its initializer, we
653 // might have to initialize with a barrier. We have to do this for
654 // both __weak and __strong, but __weak got filtered out above.
655 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
Nick Lewycky4ee7dc22013-10-02 02:29:49 +0000656 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
David Chisnall7a7ee302012-01-16 17:27:18 +0000657 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCall5b07e802013-03-13 03:10:54 +0000658 EmitARCRelease(oldValue, ARCImpreciseLifetime);
John McCallf85e1932011-06-15 23:02:42 +0000659 return;
660 }
661
David Chisnall7a7ee302012-01-16 17:27:18 +0000662 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCallf85e1932011-06-15 23:02:42 +0000663}
Chris Lattner94cd0112010-12-01 02:05:19 +0000664
John McCall7acddac2011-06-17 06:42:21 +0000665/// EmitScalarInit - Initialize the given lvalue with the given object.
666void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
667 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
668 if (!lifetime)
David Chisnall7a7ee302012-01-16 17:27:18 +0000669 return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
John McCall7acddac2011-06-17 06:42:21 +0000670
671 switch (lifetime) {
672 case Qualifiers::OCL_None:
673 llvm_unreachable("present but none");
674
675 case Qualifiers::OCL_ExplicitNone:
676 // nothing to do
677 break;
678
679 case Qualifiers::OCL_Strong:
680 init = EmitARCRetain(lvalue.getType(), init);
681 break;
682
683 case Qualifiers::OCL_Weak:
684 // Initialize and then skip the primitive store.
685 EmitARCInitWeak(lvalue.getAddress(), init);
686 return;
687
688 case Qualifiers::OCL_Autoreleasing:
689 init = EmitARCRetainAutorelease(lvalue.getType(), init);
690 break;
691 }
692
David Chisnall7a7ee302012-01-16 17:27:18 +0000693 EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
John McCall7acddac2011-06-17 06:42:21 +0000694}
695
Chris Lattner94cd0112010-12-01 02:05:19 +0000696/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
697/// non-zero parts of the specified initializer with equal or fewer than
698/// NumStores scalar stores.
699static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
700 unsigned &NumStores) {
Chris Lattner70b02942010-12-02 01:58:41 +0000701 // Zero and Undef never requires any extra stores.
702 if (isa<llvm::ConstantAggregateZero>(Init) ||
703 isa<llvm::ConstantPointerNull>(Init) ||
704 isa<llvm::UndefValue>(Init))
705 return true;
706 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
707 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
708 isa<llvm::ConstantExpr>(Init))
709 return Init->isNullValue() || NumStores--;
710
711 // See if we can emit each element.
712 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
713 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
714 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
715 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
716 return false;
717 }
718 return true;
719 }
Chris Lattnerf492cb12012-01-31 04:36:19 +0000720
721 if (llvm::ConstantDataSequential *CDS =
722 dyn_cast<llvm::ConstantDataSequential>(Init)) {
723 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
724 llvm::Constant *Elt = CDS->getElementAsConstant(i);
725 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
726 return false;
727 }
728 return true;
729 }
Eric Christophere1f54902011-08-23 22:38:00 +0000730
Chris Lattner94cd0112010-12-01 02:05:19 +0000731 // Anything else is hard and scary.
732 return false;
733}
734
735/// emitStoresForInitAfterMemset - For inits that
736/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
737/// stores that would be required.
738static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
John McCall34695852011-02-22 06:44:22 +0000739 bool isVolatile, CGBuilderTy &Builder) {
Benjamin Kramer06d43682012-08-27 22:07:02 +0000740 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
741 "called emitStoresForInitAfterMemset for zero or undef value.");
Eric Christophere1f54902011-08-23 22:38:00 +0000742
Chris Lattner70b02942010-12-02 01:58:41 +0000743 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
744 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
745 isa<llvm::ConstantExpr>(Init)) {
Chris Lattnerf492cb12012-01-31 04:36:19 +0000746 Builder.CreateStore(Init, Loc, isVolatile);
747 return;
748 }
749
750 if (llvm::ConstantDataSequential *CDS =
751 dyn_cast<llvm::ConstantDataSequential>(Init)) {
752 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
753 llvm::Constant *Elt = CDS->getElementAsConstant(i);
Benjamin Kramercfa07e32012-08-27 21:35:58 +0000754
755 // If necessary, get a pointer to the element and emit it.
756 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
757 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
758 isVolatile, Builder);
Chris Lattnerf492cb12012-01-31 04:36:19 +0000759 }
Chris Lattner70b02942010-12-02 01:58:41 +0000760 return;
761 }
Eric Christophere1f54902011-08-23 22:38:00 +0000762
Chris Lattner70b02942010-12-02 01:58:41 +0000763 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
764 "Unknown value type!");
Eric Christophere1f54902011-08-23 22:38:00 +0000765
Chris Lattner70b02942010-12-02 01:58:41 +0000766 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
767 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
Benjamin Kramercfa07e32012-08-27 21:35:58 +0000768
769 // If necessary, get a pointer to the element and emit it.
770 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
771 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
772 isVolatile, Builder);
Chris Lattner70b02942010-12-02 01:58:41 +0000773 }
Chris Lattner94cd0112010-12-01 02:05:19 +0000774}
775
776
777/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
778/// plus some stores to initialize a local variable instead of using a memcpy
779/// from a constant global. It is beneficial to use memset if the global is all
780/// zeros, or mostly zeros and large.
781static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
782 uint64_t GlobalSize) {
783 // If a global is all zeros, always use a memset.
784 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
785
Chris Lattner94cd0112010-12-01 02:05:19 +0000786 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
787 // do it if it will require 6 or fewer scalar stores.
788 // TODO: Should budget depends on the size? Avoiding a large global warrants
789 // plopping in more stores.
790 unsigned StoreBudget = 6;
791 uint64_t SizeLimit = 32;
Eric Christophere1f54902011-08-23 22:38:00 +0000792
793 return GlobalSize > SizeLimit &&
Chris Lattner94cd0112010-12-01 02:05:19 +0000794 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
795}
796
Nadav Rotem495cfa42013-03-23 06:43:35 +0000797/// Should we use the LLVM lifetime intrinsics for the given local variable?
798static bool shouldUseLifetimeMarkers(CodeGenFunction &CGF, const VarDecl &D,
799 unsigned Size) {
Alexey Samsonov4f01ed42013-04-02 13:19:46 +0000800 // Always emit lifetime markers in -fsanitize=use-after-scope mode.
801 if (CGF.getLangOpts().Sanitize.UseAfterScope)
802 return true;
Nadav Rotem495cfa42013-03-23 06:43:35 +0000803 // For now, only in optimized builds.
804 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0)
805 return false;
806
807 // Limit the size of marked objects to 32 bytes. We don't want to increase
808 // compile time by marking tiny objects.
809 unsigned SizeThreshold = 32;
810
811 return Size > SizeThreshold;
812}
813
Chris Lattner94cd0112010-12-01 02:05:19 +0000814
Nick Lewyckya9de3fa2010-12-30 20:21:55 +0000815/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Reid Spencer5f016e22007-07-11 17:01:13 +0000816/// variable declaration with auto, register, or no storage class specifier.
Chris Lattner2621fd12008-05-08 05:58:21 +0000817/// These turn into simple stack objects, or GlobalValues depending on target.
John McCall34695852011-02-22 06:44:22 +0000818void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
819 AutoVarEmission emission = EmitAutoVarAlloca(D);
820 EmitAutoVarInit(emission);
821 EmitAutoVarCleanups(emission);
822}
Reid Spencer5f016e22007-07-11 17:01:13 +0000823
John McCall34695852011-02-22 06:44:22 +0000824/// EmitAutoVarAlloca - Emit the alloca and debug information for a
825/// local variable. Does not emit initalization or destruction.
826CodeGenFunction::AutoVarEmission
827CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
828 QualType Ty = D.getType();
829
830 AutoVarEmission emission(D);
831
832 bool isByRef = D.hasAttr<BlocksAttr>();
833 emission.IsByRef = isByRef;
834
835 CharUnits alignment = getContext().getDeclAlign(&D);
836 emission.Alignment = alignment;
837
John McCallbc8d40d2011-06-24 21:55:10 +0000838 // If the type is variably-modified, emit all the VLA sizes for it.
839 if (Ty->isVariablyModifiedType())
840 EmitVariablyModifiedType(Ty);
841
Reid Spencer5f016e22007-07-11 17:01:13 +0000842 llvm::Value *DeclPtr;
Eli Friedman3c2b3172008-02-15 12:20:59 +0000843 if (Ty->isConstantSizeType()) {
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000844 bool NRVO = getLangOpts().ElideConstructors &&
845 D.isNRVOVariable();
John McCall34695852011-02-22 06:44:22 +0000846
Richard Smithe67ca582013-06-02 00:09:52 +0000847 // If this value is an array or struct with a statically determinable
848 // constant initializer, there are optimizations we can do.
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000849 //
850 // TODO: We should constant-evaluate the initializer of any variable,
851 // as long as it is initialized by a constant expression. Currently,
852 // isConstantInitializer produces wrong answers for structs with
853 // reference or bitfield members, and a few other cases, and checking
854 // for POD-ness protects us from some of these.
Richard Smithe67ca582013-06-02 00:09:52 +0000855 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
856 (D.isConstexpr() ||
857 ((Ty.isPODType(getContext()) ||
858 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
859 D.getInit()->isConstantInitializer(getContext(), false)))) {
John McCall34695852011-02-22 06:44:22 +0000860
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000861 // If the variable's a const type, and it's neither an NRVO
862 // candidate nor a __block variable and has no mutable members,
863 // emit it as a global instead.
864 if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
865 CGM.isTypeConstant(Ty, true)) {
866 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCall34695852011-02-22 06:44:22 +0000867
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000868 emission.Address = 0; // signal this condition to later callbacks
869 assert(emission.wasEmittedAsGlobal());
870 return emission;
Tanya Lattner59876c22009-11-04 01:18:09 +0000871 }
Eric Christophere1f54902011-08-23 22:38:00 +0000872
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000873 // Otherwise, tell the initialization code that we're in this case.
874 emission.IsConstantAggregate = true;
875 }
Eric Christophere1f54902011-08-23 22:38:00 +0000876
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000877 // A normal fixed sized variable becomes an alloca in the entry block,
878 // unless it's an NRVO variable.
879 llvm::Type *LTy = ConvertTypeForMem(Ty);
Eric Christophere1f54902011-08-23 22:38:00 +0000880
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000881 if (NRVO) {
882 // The named return value optimization: allocate this variable in the
883 // return slot, so that we can elide the copy when returning this
884 // variable (C++0x [class.copy]p34).
885 DeclPtr = ReturnValue;
Eric Christophere1f54902011-08-23 22:38:00 +0000886
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000887 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
888 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
889 // Create a flag that is used to indicate when the NRVO was applied
890 // to this variable. Set it to zero to indicate that NRVO was not
891 // applied.
892 llvm::Value *Zero = Builder.getFalse();
893 llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
894 EnsureInsertPoint();
895 Builder.CreateStore(Zero, NRVOFlag);
Eric Christophere1f54902011-08-23 22:38:00 +0000896
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000897 // Record the NRVO flag for this variable.
898 NRVOFlags[&D] = NRVOFlag;
899 emission.NRVOFlag = NRVOFlag;
Nadav Rotem495cfa42013-03-23 06:43:35 +0000900 }
Douglas Gregord86c4772010-05-15 06:46:45 +0000901 }
Chris Lattner2621fd12008-05-08 05:58:21 +0000902 } else {
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000903 if (isByRef)
904 LTy = BuildByRefType(&D);
905
906 llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
907 Alloc->setName(D.getName());
908
909 CharUnits allocaAlignment = alignment;
910 if (isByRef)
911 allocaAlignment = std::max(allocaAlignment,
John McCall64aa4b32013-04-16 22:48:15 +0000912 getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0)));
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000913 Alloc->setAlignment(allocaAlignment.getQuantity());
914 DeclPtr = Alloc;
915
916 // Emit a lifetime intrinsic if meaningful. There's no point
917 // in doing this if we don't have a valid insertion point (?).
918 uint64_t size = CGM.getDataLayout().getTypeAllocSize(LTy);
919 if (HaveInsertPoint() && shouldUseLifetimeMarkers(*this, D, size)) {
920 llvm::Value *sizeV = llvm::ConstantInt::get(Int64Ty, size);
921
922 emission.SizeForLifetimeMarkers = sizeV;
923 llvm::Value *castAddr = Builder.CreateBitCast(Alloc, Int8PtrTy);
924 Builder.CreateCall2(CGM.getLLVMLifetimeStartFn(), sizeV, castAddr)
925 ->setDoesNotThrow();
926 } else {
927 assert(!emission.useLifetimeMarkers());
928 }
Chris Lattner2621fd12008-05-08 05:58:21 +0000929 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000930 } else {
Daniel Dunbard286f052009-07-19 06:58:07 +0000931 EnsureInsertPoint();
932
Anders Carlsson5ecb1b92009-02-09 20:41:50 +0000933 if (!DidCallStackSave) {
Anders Carlsson5d463152008-12-12 07:38:43 +0000934 // Save the stack.
John McCalld16c2cf2011-02-08 08:22:06 +0000935 llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
Mike Stump1eb44332009-09-09 15:08:12 +0000936
Anders Carlsson5d463152008-12-12 07:38:43 +0000937 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
938 llvm::Value *V = Builder.CreateCall(F);
Mike Stump1eb44332009-09-09 15:08:12 +0000939
Anders Carlsson5d463152008-12-12 07:38:43 +0000940 Builder.CreateStore(V, Stack);
Anders Carlsson5ecb1b92009-02-09 20:41:50 +0000941
942 DidCallStackSave = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000943
John McCalld8715092010-07-21 06:13:08 +0000944 // Push a cleanup block and restore the stack there.
John McCall3ad32c82011-01-28 08:37:24 +0000945 // FIXME: in general circumstances, this should be an EH cleanup.
John McCall1f0fca52010-07-21 07:22:38 +0000946 EHStack.pushCleanup<CallStackRestore>(NormalCleanup, Stack);
Anders Carlsson5d463152008-12-12 07:38:43 +0000947 }
Mike Stump1eb44332009-09-09 15:08:12 +0000948
John McCallbc8d40d2011-06-24 21:55:10 +0000949 llvm::Value *elementCount;
950 QualType elementType;
951 llvm::tie(elementCount, elementType) = getVLASize(Ty);
Anders Carlsson5d463152008-12-12 07:38:43 +0000952
Chris Lattner2acc6e32011-07-18 04:24:23 +0000953 llvm::Type *llvmTy = ConvertTypeForMem(elementType);
Anders Carlsson5d463152008-12-12 07:38:43 +0000954
955 // Allocate memory for the array.
John McCallbc8d40d2011-06-24 21:55:10 +0000956 llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
957 vla->setAlignment(alignment.getQuantity());
Anders Carlsson41f8a132009-09-26 18:16:06 +0000958
John McCallbc8d40d2011-06-24 21:55:10 +0000959 DeclPtr = vla;
Reid Spencer5f016e22007-07-11 17:01:13 +0000960 }
Eli Friedman8f39f5e2008-12-20 23:11:59 +0000961
Reid Spencer5f016e22007-07-11 17:01:13 +0000962 llvm::Value *&DMEntry = LocalDeclMap[&D];
963 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
964 DMEntry = DeclPtr;
John McCall34695852011-02-22 06:44:22 +0000965 emission.Address = DeclPtr;
Sanjiv Guptacc9b1632008-05-30 10:30:31 +0000966
967 // Emit debug info for local var declaration.
Devang Patelc594abd2011-06-03 19:21:47 +0000968 if (HaveInsertPoint())
969 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregor4cdad312012-10-23 20:05:01 +0000970 if (CGM.getCodeGenOpts().getDebugInfo()
971 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonovfd00eec2012-05-04 07:39:27 +0000972 DI->setLocation(D.getLocation());
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000973 DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
Alexey Samsonovfd00eec2012-05-04 07:39:27 +0000974 }
Devang Patelc594abd2011-06-03 19:21:47 +0000975 }
Sanjiv Guptacc9b1632008-05-30 10:30:31 +0000976
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000977 if (D.hasAttr<AnnotateAttr>())
978 EmitVarAnnotations(&D, emission.Address);
979
John McCall34695852011-02-22 06:44:22 +0000980 return emission;
981}
982
983/// Determines whether the given __block variable is potentially
984/// captured by the given expression.
985static bool isCapturedBy(const VarDecl &var, const Expr *e) {
986 // Skip the most common kinds of expressions that make
987 // hierarchy-walking expensive.
988 e = e->IgnoreParenCasts();
989
990 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
991 const BlockDecl *block = be->getBlockDecl();
992 for (BlockDecl::capture_const_iterator i = block->capture_begin(),
993 e = block->capture_end(); i != e; ++i) {
994 if (i->getVariable() == &var)
995 return true;
996 }
997
998 // No need to walk into the subexpressions.
999 return false;
1000 }
1001
Fariborz Jahanian5033be12011-08-23 16:47:15 +00001002 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1003 const CompoundStmt *CS = SE->getSubStmt();
Eric Christopherc6fad602011-08-23 23:44:09 +00001004 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1005 BE = CS->body_end(); BI != BE; ++BI)
Fariborz Jahanian045c8422011-08-25 00:06:26 +00001006 if (Expr *E = dyn_cast<Expr>((*BI))) {
Fariborz Jahanian5033be12011-08-23 16:47:15 +00001007 if (isCapturedBy(var, E))
1008 return true;
Fariborz Jahanian045c8422011-08-25 00:06:26 +00001009 }
1010 else if (DeclStmt *DS = dyn_cast<DeclStmt>((*BI))) {
1011 // special case declarations
1012 for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
1013 I != E; ++I) {
1014 if (VarDecl *VD = dyn_cast<VarDecl>((*I))) {
1015 Expr *Init = VD->getInit();
1016 if (Init && isCapturedBy(var, Init))
1017 return true;
1018 }
1019 }
1020 }
1021 else
1022 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1023 // Later, provide code to poke into statements for capture analysis.
1024 return true;
Fariborz Jahanian5033be12011-08-23 16:47:15 +00001025 return false;
1026 }
Eric Christophere1f54902011-08-23 22:38:00 +00001027
John McCall34695852011-02-22 06:44:22 +00001028 for (Stmt::const_child_range children = e->children(); children; ++children)
1029 if (isCapturedBy(var, cast<Expr>(*children)))
1030 return true;
1031
1032 return false;
1033}
1034
Douglas Gregorbcc3e662011-07-01 21:08:19 +00001035/// \brief Determine whether the given initializer is trivial in the sense
1036/// that it requires no code to be generated.
1037static bool isTrivialInitializer(const Expr *Init) {
1038 if (!Init)
1039 return true;
Eric Christophere1f54902011-08-23 22:38:00 +00001040
Douglas Gregorbcc3e662011-07-01 21:08:19 +00001041 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1042 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1043 if (Constructor->isTrivial() &&
1044 Constructor->isDefaultConstructor() &&
1045 !Construct->requiresZeroInitialization())
1046 return true;
Eric Christophere1f54902011-08-23 22:38:00 +00001047
Douglas Gregorbcc3e662011-07-01 21:08:19 +00001048 return false;
1049}
John McCall34695852011-02-22 06:44:22 +00001050void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall57b3b6a2011-02-22 07:16:58 +00001051 assert(emission.Variable && "emission was not valid!");
1052
John McCall34695852011-02-22 06:44:22 +00001053 // If this was emitted as a global constant, we're done.
1054 if (emission.wasEmittedAsGlobal()) return;
1055
John McCall57b3b6a2011-02-22 07:16:58 +00001056 const VarDecl &D = *emission.Variable;
John McCall34695852011-02-22 06:44:22 +00001057 QualType type = D.getType();
1058
Chris Lattner19785962007-07-12 00:39:48 +00001059 // If this local has an initializer, emit it now.
Daniel Dunbard286f052009-07-19 06:58:07 +00001060 const Expr *Init = D.getInit();
1061
1062 // If we are at an unreachable point, we don't need to emit the initializer
1063 // unless it contains a label.
1064 if (!HaveInsertPoint()) {
John McCall34695852011-02-22 06:44:22 +00001065 if (!Init || !ContainsLabel(Init)) return;
1066 EnsureInsertPoint();
Daniel Dunbard286f052009-07-19 06:58:07 +00001067 }
1068
John McCall5af02db2011-03-31 01:59:53 +00001069 // Initialize the structure of a __block variable.
1070 if (emission.IsByRef)
1071 emitByrefStructureInit(emission);
Anders Carlsson69c68b72009-02-07 23:51:38 +00001072
Douglas Gregorbcc3e662011-07-01 21:08:19 +00001073 if (isTrivialInitializer(Init))
1074 return;
Eric Christophere1f54902011-08-23 22:38:00 +00001075
John McCall5af02db2011-03-31 01:59:53 +00001076 CharUnits alignment = emission.Alignment;
1077
John McCall34695852011-02-22 06:44:22 +00001078 // Check whether this is a byref variable that's potentially
1079 // captured and moved by its own initializer. If so, we'll need to
1080 // emit the initializer first, then copy into the variable.
1081 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1082
1083 llvm::Value *Loc =
1084 capturedByInit ? emission.Address : emission.getObjectAddress(*this);
1085
Richard Smith51201882011-12-30 21:15:51 +00001086 llvm::Constant *constant = 0;
Richard Smithe67ca582013-06-02 00:09:52 +00001087 if (emission.IsConstantAggregate || D.isConstexpr()) {
Richard Smith51201882011-12-30 21:15:51 +00001088 assert(!capturedByInit && "constant init contains a capturing block?");
Richard Smith2d6a5672012-01-14 04:30:29 +00001089 constant = CGM.EmitConstantInit(D, this);
Richard Smith51201882011-12-30 21:15:51 +00001090 }
1091
1092 if (!constant) {
Eli Friedman6da2c712011-12-03 04:14:32 +00001093 LValue lv = MakeAddrLValue(Loc, type, alignment);
John McCalla07398e2011-06-16 04:16:24 +00001094 lv.setNonGC(true);
1095 return EmitExprAsInit(Init, &D, lv, capturedByInit);
1096 }
John McCall60d33652011-03-08 09:11:50 +00001097
Richard Smithe67ca582013-06-02 00:09:52 +00001098 if (!emission.IsConstantAggregate) {
1099 // For simple scalar/complex initialization, store the value directly.
1100 LValue lv = MakeAddrLValue(Loc, type, alignment);
1101 lv.setNonGC(true);
1102 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1103 }
1104
John McCall34695852011-02-22 06:44:22 +00001105 // If this is a simple aggregate initialization, we can optimize it
1106 // in various ways.
John McCall60d33652011-03-08 09:11:50 +00001107 bool isVolatile = type.isVolatileQualified();
John McCall34695852011-02-22 06:44:22 +00001108
John McCall60d33652011-03-08 09:11:50 +00001109 llvm::Value *SizeVal =
Eric Christophere1f54902011-08-23 22:38:00 +00001110 llvm::ConstantInt::get(IntPtrTy,
John McCall60d33652011-03-08 09:11:50 +00001111 getContext().getTypeSizeInChars(type).getQuantity());
John McCall34695852011-02-22 06:44:22 +00001112
Chris Lattner2acc6e32011-07-18 04:24:23 +00001113 llvm::Type *BP = Int8PtrTy;
John McCall60d33652011-03-08 09:11:50 +00001114 if (Loc->getType() != BP)
Benjamin Kramer578faa82011-09-27 21:06:10 +00001115 Loc = Builder.CreateBitCast(Loc, BP);
Mon P Wang3ecd7852010-04-04 03:10:52 +00001116
John McCall60d33652011-03-08 09:11:50 +00001117 // If the initializer is all or mostly zeros, codegen with memset then do
1118 // a few stores afterward.
Eric Christophere1f54902011-08-23 22:38:00 +00001119 if (shouldUseMemSetPlusStoresToInitialize(constant,
Micah Villmow25a6a842012-10-08 16:25:52 +00001120 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
John McCall60d33652011-03-08 09:11:50 +00001121 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1122 alignment.getQuantity(), isVolatile);
Benjamin Kramer06d43682012-08-27 22:07:02 +00001123 // Zero and undef don't require a stores.
1124 if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
John McCall60d33652011-03-08 09:11:50 +00001125 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
1126 emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +00001127 }
John McCall60d33652011-03-08 09:11:50 +00001128 } else {
Eric Christophere1f54902011-08-23 22:38:00 +00001129 // Otherwise, create a temporary global with the initializer then
John McCall60d33652011-03-08 09:11:50 +00001130 // memcpy from the global to the alloca.
1131 std::string Name = GetStaticDeclName(*this, D, ".");
1132 llvm::GlobalVariable *GV =
1133 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
Eric Christopher736a9c22011-08-24 00:33:55 +00001134 llvm::GlobalValue::PrivateLinkage,
Hans Wennborg5e2d5de2012-06-23 11:51:46 +00001135 constant, Name);
John McCall60d33652011-03-08 09:11:50 +00001136 GV->setAlignment(alignment.getQuantity());
Eli Friedman460980d2011-05-27 22:32:55 +00001137 GV->setUnnamedAddr(true);
Eric Christophere1f54902011-08-23 22:38:00 +00001138
John McCall60d33652011-03-08 09:11:50 +00001139 llvm::Value *SrcPtr = GV;
1140 if (SrcPtr->getType() != BP)
Benjamin Kramer578faa82011-09-27 21:06:10 +00001141 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
John McCall60d33652011-03-08 09:11:50 +00001142
1143 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
1144 isVolatile);
1145 }
1146}
1147
1148/// Emit an expression as an initializer for a variable at the given
1149/// location. The expression is not necessarily the normal
1150/// initializer for the variable, and the address is not necessarily
1151/// its normal location.
1152///
1153/// \param init the initializing expression
1154/// \param var the variable to act as if we're initializing
1155/// \param loc the address to initialize; its type is a pointer
1156/// to the LLVM mapping of the variable's type
1157/// \param alignment the alignment of the address
1158/// \param capturedByInit true if the variable is a __block variable
1159/// whose address is potentially changed by the initializer
1160void CodeGenFunction::EmitExprAsInit(const Expr *init,
John McCallf85e1932011-06-15 23:02:42 +00001161 const ValueDecl *D,
John McCalla07398e2011-06-16 04:16:24 +00001162 LValue lvalue,
John McCall60d33652011-03-08 09:11:50 +00001163 bool capturedByInit) {
John McCallf85e1932011-06-15 23:02:42 +00001164 QualType type = D->getType();
John McCall60d33652011-03-08 09:11:50 +00001165
1166 if (type->isReferenceType()) {
Richard Smithd4ec5622013-06-12 23:38:09 +00001167 RValue rvalue = EmitReferenceBindingToExpr(init);
Eric Christophere1f54902011-08-23 22:38:00 +00001168 if (capturedByInit)
John McCalla07398e2011-06-16 04:16:24 +00001169 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Chisnall7a7ee302012-01-16 17:27:18 +00001170 EmitStoreThroughLValue(rvalue, lvalue, true);
John McCall9d232c82013-03-07 21:37:08 +00001171 return;
1172 }
1173 switch (getEvaluationKind(type)) {
1174 case TEK_Scalar:
John McCalla07398e2011-06-16 04:16:24 +00001175 EmitScalarInit(init, D, lvalue, capturedByInit);
John McCall9d232c82013-03-07 21:37:08 +00001176 return;
1177 case TEK_Complex: {
John McCall60d33652011-03-08 09:11:50 +00001178 ComplexPairTy complex = EmitComplexExpr(init);
John McCalla07398e2011-06-16 04:16:24 +00001179 if (capturedByInit)
1180 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall9d232c82013-03-07 21:37:08 +00001181 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
1182 return;
1183 }
1184 case TEK_Aggregate:
John McCall9eda3ab2013-03-07 21:37:17 +00001185 if (type->isAtomicType()) {
1186 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1187 } else {
1188 // TODO: how can we delay here if D is captured by its initializer?
1189 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
Chad Rosier649b4a12012-03-29 17:37:10 +00001190 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001191 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001192 AggValueSlot::IsNotAliased));
John McCall9eda3ab2013-03-07 21:37:17 +00001193 }
John McCall9d232c82013-03-07 21:37:08 +00001194 return;
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +00001195 }
John McCall9d232c82013-03-07 21:37:08 +00001196 llvm_unreachable("bad evaluation kind");
John McCall34695852011-02-22 06:44:22 +00001197}
John McCallf1549f62010-07-06 01:34:17 +00001198
John McCallbdc4d802011-07-09 01:37:26 +00001199/// Enter a destroy cleanup for the given local variable.
1200void CodeGenFunction::emitAutoVarTypeCleanup(
1201 const CodeGenFunction::AutoVarEmission &emission,
1202 QualType::DestructionKind dtorKind) {
1203 assert(dtorKind != QualType::DK_none);
1204
1205 // Note that for __block variables, we want to destroy the
1206 // original stack object, not the possibly forwarded object.
1207 llvm::Value *addr = emission.getObjectAddress(*this);
1208
1209 const VarDecl *var = emission.Variable;
1210 QualType type = var->getType();
1211
1212 CleanupKind cleanupKind = NormalAndEHCleanup;
1213 CodeGenFunction::Destroyer *destroyer = 0;
1214
1215 switch (dtorKind) {
1216 case QualType::DK_none:
1217 llvm_unreachable("no cleanup for trivially-destructible variable");
1218
1219 case QualType::DK_cxx_destructor:
1220 // If there's an NRVO flag on the emission, we need a different
1221 // cleanup.
1222 if (emission.NRVOFlag) {
1223 assert(!type->isArrayType());
1224 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1225 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor,
1226 emission.NRVOFlag);
1227 return;
1228 }
1229 break;
1230
1231 case QualType::DK_objc_strong_lifetime:
1232 // Suppress cleanups for pseudo-strong variables.
1233 if (var->isARCPseudoStrong()) return;
Eric Christophere1f54902011-08-23 22:38:00 +00001234
John McCallbdc4d802011-07-09 01:37:26 +00001235 // Otherwise, consider whether to use an EH cleanup or not.
1236 cleanupKind = getARCCleanupKind();
1237
1238 // Use the imprecise destroyer by default.
1239 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1240 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1241 break;
1242
1243 case QualType::DK_objc_weak_lifetime:
1244 break;
1245 }
1246
1247 // If we haven't chosen a more specific destroyer, use the default.
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001248 if (!destroyer) destroyer = getDestroyer(dtorKind);
John McCall2673c682011-07-11 08:38:19 +00001249
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00001250 // Use an EH cleanup in array destructors iff the destructor itself
John McCall2673c682011-07-11 08:38:19 +00001251 // is being pushed as an EH cleanup.
1252 bool useEHCleanup = (cleanupKind & EHCleanup);
1253 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1254 useEHCleanup);
John McCallbdc4d802011-07-09 01:37:26 +00001255}
1256
John McCall34695852011-02-22 06:44:22 +00001257void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall57b3b6a2011-02-22 07:16:58 +00001258 assert(emission.Variable && "emission was not valid!");
1259
John McCall34695852011-02-22 06:44:22 +00001260 // If this was emitted as a global constant, we're done.
1261 if (emission.wasEmittedAsGlobal()) return;
1262
John McCall38baeab2012-04-13 18:44:05 +00001263 // If we don't have an insertion point, we're done. Sema prevents
1264 // us from jumping into any of these scopes anyway.
1265 if (!HaveInsertPoint()) return;
1266
John McCall57b3b6a2011-02-22 07:16:58 +00001267 const VarDecl &D = *emission.Variable;
John McCall34695852011-02-22 06:44:22 +00001268
Nadav Rotem495cfa42013-03-23 06:43:35 +00001269 // Make sure we call @llvm.lifetime.end. This needs to happen
1270 // *last*, so the cleanup needs to be pushed *first*.
1271 if (emission.useLifetimeMarkers()) {
1272 EHStack.pushCleanup<CallLifetimeEnd>(NormalCleanup,
1273 emission.getAllocatedAddress(),
1274 emission.getSizeForLifetimeMarkers());
1275 }
1276
John McCallbdc4d802011-07-09 01:37:26 +00001277 // Check the type for a cleanup.
1278 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1279 emitAutoVarTypeCleanup(emission, dtorKind);
John McCallf85e1932011-06-15 23:02:42 +00001280
John McCall0c24c802011-06-24 23:21:27 +00001281 // In GC mode, honor objc_precise_lifetime.
David Blaikie4e4d0842012-03-11 07:00:24 +00001282 if (getLangOpts().getGC() != LangOptions::NonGC &&
John McCall0c24c802011-06-24 23:21:27 +00001283 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1284 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1285 }
1286
John McCall34695852011-02-22 06:44:22 +00001287 // Handle the cleanup attribute.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001288 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlsson69c68b72009-02-07 23:51:38 +00001289 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001290
John McCall34695852011-02-22 06:44:22 +00001291 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlsson69c68b72009-02-07 23:51:38 +00001292 assert(F && "Could not find function!");
Mike Stump1eb44332009-09-09 15:08:12 +00001293
John McCallde5d3c72012-02-17 03:33:10 +00001294 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
John McCall34695852011-02-22 06:44:22 +00001295 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlsson69c68b72009-02-07 23:51:38 +00001296 }
Mike Stump797b6322009-03-05 01:23:13 +00001297
John McCall34695852011-02-22 06:44:22 +00001298 // If this is a block variable, call _Block_object_destroy
1299 // (on the unforwarded address).
John McCall5af02db2011-03-31 01:59:53 +00001300 if (emission.IsByRef)
1301 enterByrefCleanup(emission);
Reid Spencer5f016e22007-07-11 17:01:13 +00001302}
1303
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001304CodeGenFunction::Destroyer *
John McCallbdc4d802011-07-09 01:37:26 +00001305CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1306 switch (kind) {
1307 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
John McCall0850e8d2011-07-09 09:09:00 +00001308 case QualType::DK_cxx_destructor:
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001309 return destroyCXXObject;
John McCall0850e8d2011-07-09 09:09:00 +00001310 case QualType::DK_objc_strong_lifetime:
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001311 return destroyARCStrongPrecise;
John McCall0850e8d2011-07-09 09:09:00 +00001312 case QualType::DK_objc_weak_lifetime:
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001313 return destroyARCWeak;
John McCallbdc4d802011-07-09 01:37:26 +00001314 }
Matt Beaumont-Gayba4be252012-01-27 00:46:27 +00001315 llvm_unreachable("Unknown DestructionKind");
John McCallbdc4d802011-07-09 01:37:26 +00001316}
1317
John McCall074cae02013-02-01 05:11:40 +00001318/// pushEHDestroy - Push the standard destructor for the given type as
1319/// an EH-only cleanup.
1320void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
1321 llvm::Value *addr, QualType type) {
1322 assert(dtorKind && "cannot push destructor for trivial type");
1323 assert(needsEHCleanup(dtorKind));
1324
1325 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1326}
1327
1328/// pushDestroy - Push the standard destructor for the given type as
1329/// at least a normal cleanup.
John McCall9928c482011-07-12 16:41:08 +00001330void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
1331 llvm::Value *addr, QualType type) {
1332 assert(dtorKind && "cannot push destructor for trivial type");
1333
1334 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1335 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1336 cleanupKind & EHCleanup);
1337}
1338
John McCallbdc4d802011-07-09 01:37:26 +00001339void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *addr,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001340 QualType type, Destroyer *destroyer,
John McCall2673c682011-07-11 08:38:19 +00001341 bool useEHCleanupForArray) {
John McCall9928c482011-07-12 16:41:08 +00001342 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1343 destroyer, useEHCleanupForArray);
John McCallbdc4d802011-07-09 01:37:26 +00001344}
1345
Richard Smith8a07cd32013-06-12 20:42:33 +00001346void CodeGenFunction::pushLifetimeExtendedDestroy(
1347 CleanupKind cleanupKind, llvm::Value *addr, QualType type,
1348 Destroyer *destroyer, bool useEHCleanupForArray) {
1349 assert(!isInConditionalBranch() &&
1350 "performing lifetime extension from within conditional");
1351
1352 // Push an EH-only cleanup for the object now.
1353 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1354 // around in case a temporary's destructor throws an exception.
1355 if (cleanupKind & EHCleanup)
1356 EHStack.pushCleanup<DestroyObject>(
1357 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1358 destroyer, useEHCleanupForArray);
1359
1360 // Remember that we need to push a full cleanup for the object at the
1361 // end of the full-expression.
1362 pushCleanupAfterFullExpr<DestroyObject>(
1363 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1364}
1365
John McCall2673c682011-07-11 08:38:19 +00001366/// emitDestroy - Immediately perform the destruction of the given
1367/// object.
1368///
1369/// \param addr - the address of the object; a type*
1370/// \param type - the type of the object; if an array type, all
1371/// objects are destroyed in reverse order
1372/// \param destroyer - the function to call to destroy individual
1373/// elements
1374/// \param useEHCleanupForArray - whether an EH cleanup should be
1375/// used when destroying array elements, in case one of the
1376/// destructions throws an exception
John McCallbdc4d802011-07-09 01:37:26 +00001377void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001378 Destroyer *destroyer,
John McCall2673c682011-07-11 08:38:19 +00001379 bool useEHCleanupForArray) {
John McCallbdc4d802011-07-09 01:37:26 +00001380 const ArrayType *arrayType = getContext().getAsArrayType(type);
1381 if (!arrayType)
1382 return destroyer(*this, addr, type);
1383
1384 llvm::Value *begin = addr;
1385 llvm::Value *length = emitArrayLength(arrayType, type, begin);
John McCallfbf780a2011-07-13 08:09:46 +00001386
1387 // Normally we have to check whether the array is zero-length.
1388 bool checkZeroLength = true;
1389
1390 // But if the array length is constant, we can suppress that.
1391 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1392 // ...and if it's constant zero, we can just skip the entire thing.
1393 if (constLength->isZero()) return;
1394 checkZeroLength = false;
1395 }
1396
John McCallbdc4d802011-07-09 01:37:26 +00001397 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
John McCallfbf780a2011-07-13 08:09:46 +00001398 emitArrayDestroy(begin, end, type, destroyer,
1399 checkZeroLength, useEHCleanupForArray);
John McCallbdc4d802011-07-09 01:37:26 +00001400}
1401
John McCall2673c682011-07-11 08:38:19 +00001402/// emitArrayDestroy - Destroys all the elements of the given array,
1403/// beginning from last to first. The array cannot be zero-length.
1404///
1405/// \param begin - a type* denoting the first element of the array
1406/// \param end - a type* denoting one past the end of the array
1407/// \param type - the element type of the array
1408/// \param destroyer - the function to call to destroy elements
1409/// \param useEHCleanup - whether to push an EH cleanup to destroy
1410/// the remaining elements in case the destruction of a single
1411/// element throws
John McCallbdc4d802011-07-09 01:37:26 +00001412void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1413 llvm::Value *end,
1414 QualType type,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001415 Destroyer *destroyer,
John McCallfbf780a2011-07-13 08:09:46 +00001416 bool checkZeroLength,
John McCall2673c682011-07-11 08:38:19 +00001417 bool useEHCleanup) {
John McCallbdc4d802011-07-09 01:37:26 +00001418 assert(!type->isArrayType());
1419
1420 // The basic structure here is a do-while loop, because we don't
1421 // need to check for the zero-element case.
1422 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1423 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1424
John McCallfbf780a2011-07-13 08:09:46 +00001425 if (checkZeroLength) {
1426 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1427 "arraydestroy.isempty");
1428 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1429 }
1430
John McCallbdc4d802011-07-09 01:37:26 +00001431 // Enter the loop body, making that address the current address.
1432 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1433 EmitBlock(bodyBB);
1434 llvm::PHINode *elementPast =
1435 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1436 elementPast->addIncoming(end, entryBB);
1437
1438 // Shift the address back by one element.
1439 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1440 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1441 "arraydestroy.element");
1442
John McCall2673c682011-07-11 08:38:19 +00001443 if (useEHCleanup)
1444 pushRegularPartialArrayCleanup(begin, element, type, destroyer);
1445
John McCallbdc4d802011-07-09 01:37:26 +00001446 // Perform the actual destruction there.
1447 destroyer(*this, element, type);
1448
John McCall2673c682011-07-11 08:38:19 +00001449 if (useEHCleanup)
1450 PopCleanupBlock();
1451
John McCallbdc4d802011-07-09 01:37:26 +00001452 // Check whether we've reached the end.
1453 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1454 Builder.CreateCondBr(done, doneBB, bodyBB);
1455 elementPast->addIncoming(element, Builder.GetInsertBlock());
1456
1457 // Done.
1458 EmitBlock(doneBB);
1459}
1460
John McCall2673c682011-07-11 08:38:19 +00001461/// Perform partial array destruction as if in an EH cleanup. Unlike
1462/// emitArrayDestroy, the element type here may still be an array type.
John McCall2673c682011-07-11 08:38:19 +00001463static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1464 llvm::Value *begin, llvm::Value *end,
1465 QualType type,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001466 CodeGenFunction::Destroyer *destroyer) {
John McCall2673c682011-07-11 08:38:19 +00001467 // If the element type is itself an array, drill down.
John McCallfbf780a2011-07-13 08:09:46 +00001468 unsigned arrayDepth = 0;
John McCall2673c682011-07-11 08:38:19 +00001469 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1470 // VLAs don't require a GEP index to walk into.
1471 if (!isa<VariableArrayType>(arrayType))
John McCallfbf780a2011-07-13 08:09:46 +00001472 arrayDepth++;
John McCall2673c682011-07-11 08:38:19 +00001473 type = arrayType->getElementType();
1474 }
John McCallfbf780a2011-07-13 08:09:46 +00001475
1476 if (arrayDepth) {
1477 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, arrayDepth+1);
1478
Chris Lattner5f9e2722011-07-23 10:55:15 +00001479 SmallVector<llvm::Value*,4> gepIndices(arrayDepth, zero);
Jay Foad0f6ac7c2011-07-22 08:16:57 +00001480 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1481 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
John McCall2673c682011-07-11 08:38:19 +00001482 }
1483
John McCallfbf780a2011-07-13 08:09:46 +00001484 // Destroy the array. We don't ever need an EH cleanup because we
1485 // assume that we're in an EH cleanup ourselves, so a throwing
1486 // destructor causes an immediate terminate.
1487 CGF.emitArrayDestroy(begin, end, type, destroyer,
1488 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
John McCall2673c682011-07-11 08:38:19 +00001489}
1490
John McCallbdc4d802011-07-09 01:37:26 +00001491namespace {
John McCall2673c682011-07-11 08:38:19 +00001492 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1493 /// array destroy where the end pointer is regularly determined and
1494 /// does not need to be loaded from a local.
1495 class RegularPartialArrayDestroy : public EHScopeStack::Cleanup {
1496 llvm::Value *ArrayBegin;
1497 llvm::Value *ArrayEnd;
1498 QualType ElementType;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001499 CodeGenFunction::Destroyer *Destroyer;
John McCall2673c682011-07-11 08:38:19 +00001500 public:
1501 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
1502 QualType elementType,
1503 CodeGenFunction::Destroyer *destroyer)
1504 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001505 ElementType(elementType), Destroyer(destroyer) {}
John McCall2673c682011-07-11 08:38:19 +00001506
John McCallad346f42011-07-12 20:27:29 +00001507 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall2673c682011-07-11 08:38:19 +00001508 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
1509 ElementType, Destroyer);
1510 }
1511 };
1512
1513 /// IrregularPartialArrayDestroy - a cleanup which performs a
1514 /// partial array destroy where the end pointer is irregularly
1515 /// determined and must be loaded from a local.
1516 class IrregularPartialArrayDestroy : public EHScopeStack::Cleanup {
John McCallbdc4d802011-07-09 01:37:26 +00001517 llvm::Value *ArrayBegin;
1518 llvm::Value *ArrayEndPointer;
1519 QualType ElementType;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001520 CodeGenFunction::Destroyer *Destroyer;
John McCallbdc4d802011-07-09 01:37:26 +00001521 public:
John McCall2673c682011-07-11 08:38:19 +00001522 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
1523 llvm::Value *arrayEndPointer,
1524 QualType elementType,
1525 CodeGenFunction::Destroyer *destroyer)
John McCallbdc4d802011-07-09 01:37:26 +00001526 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001527 ElementType(elementType), Destroyer(destroyer) {}
John McCallbdc4d802011-07-09 01:37:26 +00001528
John McCallad346f42011-07-12 20:27:29 +00001529 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallbdc4d802011-07-09 01:37:26 +00001530 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
John McCall2673c682011-07-11 08:38:19 +00001531 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
1532 ElementType, Destroyer);
John McCallbdc4d802011-07-09 01:37:26 +00001533 }
1534 };
1535}
1536
John McCall2673c682011-07-11 08:38:19 +00001537/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
John McCallbdc4d802011-07-09 01:37:26 +00001538/// already-constructed elements of the given array. The cleanup
John McCall2673c682011-07-11 08:38:19 +00001539/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christophere1f54902011-08-23 22:38:00 +00001540///
John McCallbdc4d802011-07-09 01:37:26 +00001541/// \param elementType - the immediate element type of the array;
1542/// possibly still an array type
John McCall9928c482011-07-12 16:41:08 +00001543void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
John McCall2673c682011-07-11 08:38:19 +00001544 llvm::Value *arrayEndPointer,
1545 QualType elementType,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001546 Destroyer *destroyer) {
John McCall9928c482011-07-12 16:41:08 +00001547 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1548 arrayBegin, arrayEndPointer,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001549 elementType, destroyer);
John McCall2673c682011-07-11 08:38:19 +00001550}
1551
1552/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1553/// already-constructed elements of the given array. The cleanup
1554/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christophere1f54902011-08-23 22:38:00 +00001555///
John McCall2673c682011-07-11 08:38:19 +00001556/// \param elementType - the immediate element type of the array;
1557/// possibly still an array type
John McCall2673c682011-07-11 08:38:19 +00001558void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1559 llvm::Value *arrayEnd,
1560 QualType elementType,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001561 Destroyer *destroyer) {
John McCall9928c482011-07-12 16:41:08 +00001562 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
John McCall2673c682011-07-11 08:38:19 +00001563 arrayBegin, arrayEnd,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001564 elementType, destroyer);
John McCallbdc4d802011-07-09 01:37:26 +00001565}
1566
Nadav Rotem495cfa42013-03-23 06:43:35 +00001567/// Lazily declare the @llvm.lifetime.start intrinsic.
1568llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
1569 if (LifetimeStartFn) return LifetimeStartFn;
1570 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1571 llvm::Intrinsic::lifetime_start);
1572 return LifetimeStartFn;
1573}
1574
1575/// Lazily declare the @llvm.lifetime.end intrinsic.
1576llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
1577 if (LifetimeEndFn) return LifetimeEndFn;
1578 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1579 llvm::Intrinsic::lifetime_end);
1580 return LifetimeEndFn;
1581}
1582
John McCallf85e1932011-06-15 23:02:42 +00001583namespace {
1584 /// A cleanup to perform a release of an object at the end of a
1585 /// function. This is used to balance out the incoming +1 of a
1586 /// ns_consumed argument when we can't reasonably do that just by
1587 /// not doing the initial retain for a __block argument.
1588 struct ConsumeARCParameter : EHScopeStack::Cleanup {
John McCall5b07e802013-03-13 03:10:54 +00001589 ConsumeARCParameter(llvm::Value *param,
1590 ARCPreciseLifetime_t precise)
1591 : Param(param), Precise(precise) {}
John McCallf85e1932011-06-15 23:02:42 +00001592
1593 llvm::Value *Param;
John McCall5b07e802013-03-13 03:10:54 +00001594 ARCPreciseLifetime_t Precise;
John McCallf85e1932011-06-15 23:02:42 +00001595
John McCallad346f42011-07-12 20:27:29 +00001596 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall5b07e802013-03-13 03:10:54 +00001597 CGF.EmitARCRelease(Param, Precise);
John McCallf85e1932011-06-15 23:02:42 +00001598 }
1599 };
1600}
1601
Mike Stump1eb44332009-09-09 15:08:12 +00001602/// Emit an alloca (or GlobalValue depending on target)
Chris Lattner2621fd12008-05-08 05:58:21 +00001603/// for the specified parameter and set up LocalDeclMap.
Devang Patel093ac462011-03-03 20:13:15 +00001604void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
1605 unsigned ArgNo) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001606 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Gupta31fc07d2008-10-31 09:52:39 +00001607 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001608 "Invalid argument to EmitParmDecl");
John McCall8178df32011-02-22 22:38:33 +00001609
1610 Arg->setName(D.getName());
1611
Adrian Prantl836e7c92013-03-14 17:53:33 +00001612 QualType Ty = D.getType();
1613
John McCall8178df32011-02-22 22:38:33 +00001614 // Use better IR generation for certain implicit parameters.
1615 if (isa<ImplicitParamDecl>(D)) {
1616 // The only implicit argument a block has is its literal.
1617 if (BlockInfo) {
1618 LocalDeclMap[&D] = Arg;
Adrian Prantl836e7c92013-03-14 17:53:33 +00001619 llvm::Value *LocalAddr = 0;
1620 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
Adrian Prantl9b97adf2013-03-29 19:20:35 +00001621 // Allocate a stack slot to let the debug info survive the RA.
Adrian Prantl836e7c92013-03-14 17:53:33 +00001622 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1623 D.getName() + ".addr");
1624 Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity());
1625 LValue lv = MakeAddrLValue(Alloc, Ty, getContext().getDeclAlign(&D));
1626 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
1627 LocalAddr = Builder.CreateLoad(Alloc);
1628 }
John McCall8178df32011-02-22 22:38:33 +00001629
1630 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregor4cdad312012-10-23 20:05:01 +00001631 if (CGM.getCodeGenOpts().getDebugInfo()
1632 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001633 DI->setLocation(D.getLocation());
Adrian Prantl836e7c92013-03-14 17:53:33 +00001634 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, LocalAddr, Builder);
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001635 }
John McCall8178df32011-02-22 22:38:33 +00001636 }
1637
1638 return;
1639 }
1640 }
1641
Reid Spencer5f016e22007-07-11 17:01:13 +00001642 llvm::Value *DeclPtr;
Reid Kleckner9b601952013-06-21 12:45:15 +00001643 bool HasNonScalarEvalKind = !CodeGenFunction::hasScalarEvaluationKind(Ty);
Daniel Dunbare86bcf02010-02-08 22:53:07 +00001644 // If this is an aggregate or variable sized value, reuse the input pointer.
Reid Kleckner9b601952013-06-21 12:45:15 +00001645 if (HasNonScalarEvalKind || !Ty->isConstantSizeType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001646 DeclPtr = Arg;
Reid Kleckner9b601952013-06-21 12:45:15 +00001647 // Push a destructor cleanup for this parameter if the ABI requires it.
1648 if (HasNonScalarEvalKind &&
1649 getTarget().getCXXABI().isArgumentDestroyedByCallee()) {
1650 if (const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl()) {
1651 if (RD->hasNonTrivialDestructor())
1652 pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
1653 }
1654 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001655 } else {
Daniel Dunbare86bcf02010-02-08 22:53:07 +00001656 // Otherwise, create a temporary to hold the value.
Eli Friedmanddfb8d12011-11-03 20:31:28 +00001657 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1658 D.getName() + ".addr");
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001659 CharUnits Align = getContext().getDeclAlign(&D);
1660 Alloc->setAlignment(Align.getQuantity());
Eli Friedmanddfb8d12011-11-03 20:31:28 +00001661 DeclPtr = Alloc;
Mike Stump1eb44332009-09-09 15:08:12 +00001662
John McCallf85e1932011-06-15 23:02:42 +00001663 bool doStore = true;
1664
1665 Qualifiers qs = Ty.getQualifiers();
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001666 LValue lv = MakeAddrLValue(DeclPtr, Ty, Align);
John McCallf85e1932011-06-15 23:02:42 +00001667 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1668 // We honor __attribute__((ns_consumed)) for types with lifetime.
1669 // For __strong, it's handled by just skipping the initial retain;
1670 // otherwise we have to balance out the initial +1 with an extra
1671 // cleanup to do the release at the end of the function.
1672 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1673
1674 // 'self' is always formally __strong, but if this is not an
1675 // init method then we don't want to retain it.
John McCall7acddac2011-06-17 06:42:21 +00001676 if (D.isARCPseudoStrong()) {
John McCallf85e1932011-06-15 23:02:42 +00001677 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1678 assert(&D == method->getSelfDecl());
John McCall7acddac2011-06-17 06:42:21 +00001679 assert(lt == Qualifiers::OCL_Strong);
1680 assert(qs.hasConst());
John McCallf85e1932011-06-15 23:02:42 +00001681 assert(method->getMethodFamily() != OMF_init);
John McCall175d6592011-06-15 23:40:09 +00001682 (void) method;
John McCallf85e1932011-06-15 23:02:42 +00001683 lt = Qualifiers::OCL_ExplicitNone;
1684 }
1685
1686 if (lt == Qualifiers::OCL_Strong) {
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001687 if (!isConsumed) {
1688 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1689 // use objc_storeStrong(&dest, value) for retaining the
1690 // object. But first, store a null into 'dest' because
1691 // objc_storeStrong attempts to release its old value.
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001692 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001693 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
1694 EmitARCStoreStrongCall(lv.getAddress(), Arg, true);
1695 doStore = false;
1696 }
1697 else
John McCallf85e1932011-06-15 23:02:42 +00001698 // Don't use objc_retainBlock for block pointers, because we
1699 // don't want to Block_copy something just because we got it
1700 // as a parameter.
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001701 Arg = EmitARCRetainNonBlock(Arg);
1702 }
John McCallf85e1932011-06-15 23:02:42 +00001703 } else {
1704 // Push the cleanup for a consumed parameter.
John McCall5b07e802013-03-13 03:10:54 +00001705 if (isConsumed) {
1706 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1707 ? ARCPreciseLifetime : ARCImpreciseLifetime);
1708 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg,
1709 precise);
1710 }
John McCallf85e1932011-06-15 23:02:42 +00001711
1712 if (lt == Qualifiers::OCL_Weak) {
1713 EmitARCInitWeak(DeclPtr, Arg);
Chad Rosier7acebfb2012-02-18 01:20:35 +00001714 doStore = false; // The weak init is a store, no need to do two.
John McCallf85e1932011-06-15 23:02:42 +00001715 }
1716 }
1717
1718 // Enter the cleanup scope.
1719 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1720 }
1721
Daniel Dunbare86bcf02010-02-08 22:53:07 +00001722 // Store the initial value into the alloca.
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001723 if (doStore)
David Chisnall7a7ee302012-01-16 17:27:18 +00001724 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001725 }
1726
1727 llvm::Value *&DMEntry = LocalDeclMap[&D];
1728 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
1729 DMEntry = DeclPtr;
Sanjiv Guptacc9b1632008-05-30 10:30:31 +00001730
1731 // Emit debug info for param declaration.
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001732 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregor4cdad312012-10-23 20:05:01 +00001733 if (CGM.getCodeGenOpts().getDebugInfo()
1734 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001735 DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
1736 }
1737 }
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001738
1739 if (D.hasAttr<AnnotateAttr>())
1740 EmitVarAnnotations(&D, DeclPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001741}