blob: 519f03aba16de95f2a1860934658b09fdc7cde26 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Decl nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000015#include "CGDebugInfo.h"
Peter Collingbourne8c25fc52011-09-19 21:14:35 +000016#include "CGOpenCLRuntime.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000017#include "CodeGenModule.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000018#include "clang/AST/ASTContext.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000019#include "clang/AST/CharUnits.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000020#include "clang/AST/Decl.h"
Anders Carlsson19567ee2008-08-25 01:38:19 +000021#include "clang/AST/DeclObjC.h"
Nate Begeman8bd4afe2008-04-19 04:17:09 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner2621fd12008-05-08 05:58:21 +000023#include "clang/Basic/TargetInfo.h"
Chandler Carruth06057ce2010-06-15 23:19:56 +000024#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000025#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/GlobalVariable.h"
27#include "llvm/IR/Intrinsics.h"
28#include "llvm/IR/Type.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029using namespace clang;
30using namespace CodeGen;
31
32
33void CodeGenFunction::EmitDecl(const Decl &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +000034 switch (D.getKind()) {
Douglas Gregor08688ac2010-04-23 02:02:43 +000035 case Decl::TranslationUnit:
36 case Decl::Namespace:
37 case Decl::UnresolvedUsingTypename:
38 case Decl::ClassTemplateSpecialization:
39 case Decl::ClassTemplatePartialSpecialization:
40 case Decl::TemplateTypeParm:
41 case Decl::UnresolvedUsingValue:
Sean Hunt9a555912010-05-30 07:21:58 +000042 case Decl::NonTypeTemplateParm:
Douglas Gregor08688ac2010-04-23 02:02:43 +000043 case Decl::CXXMethod:
44 case Decl::CXXConstructor:
45 case Decl::CXXDestructor:
46 case Decl::CXXConversion:
47 case Decl::Field:
John McCall76da55d2013-04-16 07:28:30 +000048 case Decl::MSProperty:
Francois Pichet41f5e662010-11-21 06:49:41 +000049 case Decl::IndirectField:
Douglas Gregor08688ac2010-04-23 02:02:43 +000050 case Decl::ObjCIvar:
Eric Christophere1f54902011-08-23 22:38:00 +000051 case Decl::ObjCAtDefsField:
Chris Lattneraa9fc462007-10-08 21:37:32 +000052 case Decl::ParmVar:
Douglas Gregor08688ac2010-04-23 02:02:43 +000053 case Decl::ImplicitParam:
54 case Decl::ClassTemplate:
55 case Decl::FunctionTemplate:
Richard Smith3e4c6c42011-05-05 21:57:07 +000056 case Decl::TypeAliasTemplate:
Douglas Gregor08688ac2010-04-23 02:02:43 +000057 case Decl::TemplateTemplateParm:
58 case Decl::ObjCMethod:
59 case Decl::ObjCCategory:
60 case Decl::ObjCProtocol:
61 case Decl::ObjCInterface:
62 case Decl::ObjCCategoryImpl:
63 case Decl::ObjCImplementation:
64 case Decl::ObjCProperty:
65 case Decl::ObjCCompatibleAlias:
Abramo Bagnara6206d532010-06-05 05:09:32 +000066 case Decl::AccessSpec:
Douglas Gregor08688ac2010-04-23 02:02:43 +000067 case Decl::LinkageSpec:
68 case Decl::ObjCPropertyImpl:
Douglas Gregor08688ac2010-04-23 02:02:43 +000069 case Decl::FileScopeAsm:
70 case Decl::Friend:
71 case Decl::FriendTemplate:
72 case Decl::Block:
Tareq A. Siraj6afcf882013-04-16 19:37:38 +000073 case Decl::Captured:
Francois Pichetaf0f4d02011-08-14 03:52:19 +000074 case Decl::ClassScopeFunctionSpecialization:
David Blaikie9faebd22013-05-20 04:58:53 +000075 case Decl::UsingShadow:
David Blaikieb219cfc2011-09-23 05:06:16 +000076 llvm_unreachable("Declaration should not be in declstmts!");
Reid Spencer5f016e22007-07-11 17:01:13 +000077 case Decl::Function: // void X();
Argyrios Kyrtzidis35bc0822008-10-15 00:42:39 +000078 case Decl::Record: // struct/union/class X;
Reid Spencer5f016e22007-07-11 17:01:13 +000079 case Decl::Enum: // enum X;
Mike Stump1eb44332009-09-09 15:08:12 +000080 case Decl::EnumConstant: // enum ? { X = ? }
Argyrios Kyrtzidis35bc0822008-10-15 00:42:39 +000081 case Decl::CXXRecord: // struct/union/class X; [C++]
Anders Carlsson7b0ca3f2009-12-03 17:26:31 +000082 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
Chris Lattner4ae493c2011-02-18 02:08:43 +000083 case Decl::Label: // __label__ x;
Douglas Gregor15de72c2011-12-02 23:23:56 +000084 case Decl::Import:
Alexey Bataevc6400582013-03-22 06:34:35 +000085 case Decl::OMPThreadPrivate:
Michael Han684aa732013-02-22 17:15:32 +000086 case Decl::Empty:
Reid Spencer5f016e22007-07-11 17:01:13 +000087 // None of these decls require codegen support.
88 return;
David Blaikiec8c24272013-02-02 00:39:32 +000089
David Blaikiefc46ebc2013-05-20 22:50:41 +000090 case Decl::NamespaceAlias:
91 if (CGDebugInfo *DI = getDebugInfo())
92 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
93 return;
David Blaikie9faebd22013-05-20 04:58:53 +000094 case Decl::Using: // using X; [C++]
95 if (CGDebugInfo *DI = getDebugInfo())
96 DI->EmitUsingDecl(cast<UsingDecl>(D));
97 return;
David Blaikie957dac52013-04-22 06:13:21 +000098 case Decl::UsingDirective: // using namespace X; [C++]
99 if (CGDebugInfo *DI = getDebugInfo())
100 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
101 return;
Daniel Dunbar662174c82008-08-29 17:28:43 +0000102 case Decl::Var: {
103 const VarDecl &VD = cast<VarDecl>(D);
John McCallb6bbcc92010-10-15 04:57:14 +0000104 assert(VD.isLocalVarDecl() &&
Daniel Dunbar662174c82008-08-29 17:28:43 +0000105 "Should not see file-scope variables inside a function!");
John McCallb6bbcc92010-10-15 04:57:14 +0000106 return EmitVarDecl(VD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000107 }
Mike Stump1eb44332009-09-09 15:08:12 +0000108
Richard Smith162e1c12011-04-15 14:24:37 +0000109 case Decl::Typedef: // typedef int X;
110 case Decl::TypeAlias: { // using X = int; [C++0x]
111 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000112 QualType Ty = TD.getUnderlyingType();
Mike Stump1eb44332009-09-09 15:08:12 +0000113
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000114 if (Ty->isVariablyModifiedType())
John McCallbc8d40d2011-06-24 21:55:10 +0000115 EmitVariablyModifiedType(Ty);
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000116 }
Daniel Dunbar662174c82008-08-29 17:28:43 +0000117 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000118}
119
John McCallb6bbcc92010-10-15 04:57:14 +0000120/// EmitVarDecl - This method handles emission of any variable declaration
Reid Spencer5f016e22007-07-11 17:01:13 +0000121/// inside a function, including static vars etc.
John McCallb6bbcc92010-10-15 04:57:14 +0000122void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Enea Zaffanella713e3f22013-05-16 11:27:56 +0000123 if (D.isStaticLocal()) {
Eric Christophere1f54902011-08-23 22:38:00 +0000124 llvm::GlobalValue::LinkageTypes Linkage =
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000125 llvm::GlobalValue::InternalLinkage;
126
John McCall8b242332010-05-25 04:30:21 +0000127 // If the function definition has some sort of weak linkage, its
128 // static variables should also be weak so that they get properly
Rafael Espindola9610d772013-06-17 20:04:51 +0000129 // uniqued.
130 if (D.isExternallyVisible()) {
Eli Friedman678eca42013-06-13 21:50:44 +0000131 const Decl *D = CurCodeDecl;
132 while (true) {
133 if (isa<BlockDecl>(D)) {
134 // FIXME: Handle this case properly! (Should be similar to the
135 // way we handle lambdas in computeLVForDecl in Decl.cpp.)
136 break;
137 } else if (isa<CapturedDecl>(D)) {
138 D = cast<Decl>(cast<CapturedDecl>(D)->getParent());
139 } else {
140 break;
141 }
142 }
143 // FIXME: Do we really only care about FunctionDecls here?
Rafael Espindola9610d772013-06-17 20:04:51 +0000144 if (isa<FunctionDecl>(D)) {
Eli Friedman678eca42013-06-13 21:50:44 +0000145 llvm::GlobalValue::LinkageTypes ParentLinkage =
146 CGM.getFunctionLinkage(cast<FunctionDecl>(D));
147 if (llvm::GlobalValue::isWeakForLinker(ParentLinkage))
148 Linkage = ParentLinkage;
149 }
150 }
Eric Christophere1f54902011-08-23 22:38:00 +0000151
John McCallb6bbcc92010-10-15 04:57:14 +0000152 return EmitStaticVarDecl(D, Linkage);
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000153 }
Enea Zaffanella713e3f22013-05-16 11:27:56 +0000154
155 if (D.hasExternalStorage())
Lauro Ramos Venanciofea90b82008-02-16 22:30:38 +0000156 // Don't emit it now, allow it to be emitted lazily on its first use.
157 return;
Daniel Dunbar5466c7b2009-04-14 02:25:56 +0000158
Enea Zaffanella713e3f22013-05-16 11:27:56 +0000159 if (D.getStorageClass() == SC_OpenCLWorkGroupLocal)
160 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
161
162 assert(D.hasLocalStorage());
163 return EmitAutoVarDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000164}
165
Chris Lattner761acc12009-12-05 08:22:11 +0000166static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D,
167 const char *Separator) {
168 CodeGenModule &CGM = CGF.CGM;
Richard Smith7edf9e32012-11-01 22:30:59 +0000169 if (CGF.getLangOpts().CPlusPlus) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000170 StringRef Name = CGM.getMangledName(&D);
Anders Carlsson9a20d552010-06-22 16:16:50 +0000171 return Name.str();
John McCallf746aa62010-03-19 23:29:14 +0000172 }
Eric Christophere1f54902011-08-23 22:38:00 +0000173
Chris Lattner761acc12009-12-05 08:22:11 +0000174 std::string ContextName;
Fariborz Jahanianfaa5bfc2010-11-30 23:07:14 +0000175 if (!CGF.CurFuncDecl) {
176 // Better be in a block declared in global scope.
177 const NamedDecl *ND = cast<NamedDecl>(&D);
178 const DeclContext *DC = ND->getDeclContext();
179 if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
180 MangleBuffer Name;
Peter Collingbourne14110472011-01-13 18:57:25 +0000181 CGM.getBlockMangledName(GlobalDecl(), Name, BD);
Fariborz Jahanianfaa5bfc2010-11-30 23:07:14 +0000182 ContextName = Name.getString();
183 }
184 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000185 llvm_unreachable("Unknown context for block static var decl");
Fariborz Jahanianfaa5bfc2010-11-30 23:07:14 +0000186 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000187 StringRef Name = CGM.getMangledName(FD);
Anders Carlsson9a20d552010-06-22 16:16:50 +0000188 ContextName = Name.str();
John McCallf746aa62010-03-19 23:29:14 +0000189 } else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
Chris Lattner761acc12009-12-05 08:22:11 +0000190 ContextName = CGF.CurFn->getName();
191 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000192 llvm_unreachable("Unknown context for static var decl");
Eric Christophere1f54902011-08-23 22:38:00 +0000193
Chris Lattner761acc12009-12-05 08:22:11 +0000194 return ContextName + Separator + D.getNameAsString();
195}
196
Chandler Carruth0f30a122012-03-30 19:44:53 +0000197llvm::GlobalVariable *
John McCallb6bbcc92010-10-15 04:57:14 +0000198CodeGenFunction::CreateStaticVarDecl(const VarDecl &D,
199 const char *Separator,
200 llvm::GlobalValue::LinkageTypes Linkage) {
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000201 QualType Ty = D.getType();
Eli Friedman3c2b3172008-02-15 12:20:59 +0000202 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000203
Benjamin Kramer5c247db2011-11-20 21:05:04 +0000204 // Use the label if the variable is renamed with the asm-label extension.
205 std::string Name;
Benjamin Kramerc3c8f222011-11-21 15:47:23 +0000206 if (D.hasAttr<AsmLabelAttr>())
207 Name = CGM.getMangledName(&D);
208 else
Benjamin Kramer5c247db2011-11-20 21:05:04 +0000209 Name = GetStaticDeclName(*this, D, Separator);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000210
Chris Lattner2acc6e32011-07-18 04:24:23 +0000211 llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
Peter Collingbourne1aba7782012-08-28 20:37:10 +0000212 unsigned AddrSpace =
213 CGM.GetGlobalVarAddressSpace(&D, CGM.getContext().getTargetAddressSpace(Ty));
Anders Carlsson41f8a132009-09-26 18:16:06 +0000214 llvm::GlobalVariable *GV =
215 new llvm::GlobalVariable(CGM.getModule(), LTy,
216 Ty.isConstant(getContext()), Linkage,
Hans Wennborgde981f32012-06-28 08:01:44 +0000217 CGM.EmitNullConstant(D.getType()), Name, 0,
218 llvm::GlobalVariable::NotThreadLocal,
Peter Collingbourne1aba7782012-08-28 20:37:10 +0000219 AddrSpace);
Ken Dyck8b752f12010-01-27 17:10:57 +0000220 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Eli Friedman93cc5152013-06-17 21:51:45 +0000221 CGM.setGlobalVisibility(GV, &D);
Hans Wennborgde981f32012-06-28 08:01:44 +0000222
Richard Smith38afbc72013-04-13 02:43:54 +0000223 if (D.getTLSKind())
Hans Wennborgde981f32012-06-28 08:01:44 +0000224 CGM.setTLSMode(GV, D);
225
Anders Carlsson41f8a132009-09-26 18:16:06 +0000226 return GV;
Daniel Dunbar0096acf2009-02-25 19:24:29 +0000227}
228
Richard Smith7ca48502012-02-13 22:16:19 +0000229/// hasNontrivialDestruction - Determine whether a type's destruction is
230/// non-trivial. If so, and the variable uses static initialization, we must
231/// register its destructor to run on exit.
232static bool hasNontrivialDestruction(QualType T) {
233 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
234 return RD && !RD->hasTrivialDestructor();
235}
236
Chandler Carruth0f30a122012-03-30 19:44:53 +0000237/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
238/// global variable that has already been created for it. If the initializer
239/// has a different type than GV does, this may free GV and return a different
240/// one. Otherwise it just returns GV.
241llvm::GlobalVariable *
John McCallb6bbcc92010-10-15 04:57:14 +0000242CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
Chandler Carruth0f30a122012-03-30 19:44:53 +0000243 llvm::GlobalVariable *GV) {
244 llvm::Constant *Init = CGM.EmitConstantInit(D, this);
John McCallbf40cb52010-07-15 23:40:35 +0000245
Chris Lattner761acc12009-12-05 08:22:11 +0000246 // If constant emission failed, then this should be a C++ static
247 // initializer.
Chandler Carruth0f30a122012-03-30 19:44:53 +0000248 if (!Init) {
Richard Smith7edf9e32012-11-01 22:30:59 +0000249 if (!getLangOpts().CPlusPlus)
Chris Lattner761acc12009-12-05 08:22:11 +0000250 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
John McCall5cd91b52010-09-08 01:44:27 +0000251 else if (Builder.GetInsertBlock()) {
Eric Christophere1f54902011-08-23 22:38:00 +0000252 // Since we have a static initializer, this global variable can't
Anders Carlsson071c8102010-01-26 04:02:23 +0000253 // be constant.
Chandler Carruth0f30a122012-03-30 19:44:53 +0000254 GV->setConstant(false);
John McCall5cd91b52010-09-08 01:44:27 +0000255
Chandler Carruth0f30a122012-03-30 19:44:53 +0000256 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
Anders Carlsson071c8102010-01-26 04:02:23 +0000257 }
Chandler Carruth0f30a122012-03-30 19:44:53 +0000258 return GV;
Chris Lattner761acc12009-12-05 08:22:11 +0000259 }
John McCallbf40cb52010-07-15 23:40:35 +0000260
Chris Lattner761acc12009-12-05 08:22:11 +0000261 // The initializer may differ in type from the global. Rewrite
262 // the global to match the initializer. (We have to do this
263 // because some types, like unions, can't be completely represented
264 // in the LLVM type system.)
Chandler Carruth0f30a122012-03-30 19:44:53 +0000265 if (GV->getType()->getElementType() != Init->getType()) {
266 llvm::GlobalVariable *OldGV = GV;
267
268 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
269 OldGV->isConstant(),
270 OldGV->getLinkage(), Init, "",
271 /*InsertBefore*/ OldGV,
Hans Wennborg5e2d5de2012-06-23 11:51:46 +0000272 OldGV->getThreadLocalMode(),
Chandler Carruth0f30a122012-03-30 19:44:53 +0000273 CGM.getContext().getTargetAddressSpace(D.getType()));
274 GV->setVisibility(OldGV->getVisibility());
Eric Christophere1f54902011-08-23 22:38:00 +0000275
Chris Lattner761acc12009-12-05 08:22:11 +0000276 // Steal the name of the old global
Chandler Carruth0f30a122012-03-30 19:44:53 +0000277 GV->takeName(OldGV);
Eric Christophere1f54902011-08-23 22:38:00 +0000278
Chris Lattner761acc12009-12-05 08:22:11 +0000279 // Replace all uses of the old global with the new global
Chandler Carruth0f30a122012-03-30 19:44:53 +0000280 llvm::Constant *NewPtrForOldDecl =
281 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
282 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eric Christophere1f54902011-08-23 22:38:00 +0000283
Chris Lattner761acc12009-12-05 08:22:11 +0000284 // Erase the old global, since it is no longer used.
Chandler Carruth0f30a122012-03-30 19:44:53 +0000285 OldGV->eraseFromParent();
Chris Lattner761acc12009-12-05 08:22:11 +0000286 }
Eric Christophere1f54902011-08-23 22:38:00 +0000287
Chandler Carruth0f30a122012-03-30 19:44:53 +0000288 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
289 GV->setInitializer(Init);
Richard Smith7ca48502012-02-13 22:16:19 +0000290
291 if (hasNontrivialDestruction(D.getType())) {
292 // We have a constant initializer, but a nontrivial destructor. We still
293 // need to perform a guarded "initialization" in order to register the
Richard Smitha9b21d22012-02-17 06:48:11 +0000294 // destructor.
Chandler Carruth0f30a122012-03-30 19:44:53 +0000295 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
Richard Smith7ca48502012-02-13 22:16:19 +0000296 }
297
Chandler Carruth0f30a122012-03-30 19:44:53 +0000298 return GV;
Chris Lattner761acc12009-12-05 08:22:11 +0000299}
300
John McCallb6bbcc92010-10-15 04:57:14 +0000301void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000302 llvm::GlobalValue::LinkageTypes Linkage) {
Chandler Carruth0f30a122012-03-30 19:44:53 +0000303 llvm::Value *&DMEntry = LocalDeclMap[&D];
304 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
Mike Stump1eb44332009-09-09 15:08:12 +0000305
John McCall355bba72012-03-30 21:00:39 +0000306 // Check to see if we already have a global variable for this
307 // declaration. This can happen when double-emitting function
308 // bodies, e.g. with complete and base constructors.
309 llvm::Constant *addr =
310 CGM.getStaticLocalDeclAddress(&D);
311
312 llvm::GlobalVariable *var;
313 if (addr) {
314 var = cast<llvm::GlobalVariable>(addr->stripPointerCasts());
315 } else {
316 addr = var = CreateStaticVarDecl(D, ".", Linkage);
317 }
Daniel Dunbara985b312009-02-25 19:45:19 +0000318
Daniel Dunbare5731f82009-02-25 20:08:33 +0000319 // Store into LocalDeclMap before generating initializer to handle
320 // circular references.
John McCall355bba72012-03-30 21:00:39 +0000321 DMEntry = addr;
322 CGM.setStaticLocalDeclAddress(&D, addr);
Daniel Dunbare5731f82009-02-25 20:08:33 +0000323
John McCallfe67f3b2010-05-04 20:45:42 +0000324 // We can't have a VLA here, but we can have a pointer to a VLA,
325 // even though that doesn't really make any sense.
Eli Friedmanc62aad82009-04-20 03:54:15 +0000326 // Make sure to evaluate VLA bounds now so that we have them for later.
327 if (D.getType()->isVariablyModifiedType())
John McCallbc8d40d2011-06-24 21:55:10 +0000328 EmitVariablyModifiedType(D.getType());
Eric Christophere1f54902011-08-23 22:38:00 +0000329
John McCall355bba72012-03-30 21:00:39 +0000330 // Save the type in case adding the initializer forces a type change.
331 llvm::Type *expectedType = addr->getType();
Eli Friedmanc62aad82009-04-20 03:54:15 +0000332
Chris Lattner761acc12009-12-05 08:22:11 +0000333 // If this value has an initializer, emit it.
334 if (D.getInit())
John McCall355bba72012-03-30 21:00:39 +0000335 var = AddInitializerToStaticVarDecl(D, var);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000336
John McCall355bba72012-03-30 21:00:39 +0000337 var->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Chris Lattner0af95232010-03-10 23:59:59 +0000338
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000339 if (D.hasAttr<AnnotateAttr>())
John McCall355bba72012-03-30 21:00:39 +0000340 CGM.AddGlobalAnnotations(&D, var);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000341
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000342 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
John McCall355bba72012-03-30 21:00:39 +0000343 var->setSection(SA->getName());
Mike Stump1eb44332009-09-09 15:08:12 +0000344
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000345 if (D.hasAttr<UsedAttr>())
John McCall355bba72012-03-30 21:00:39 +0000346 CGM.AddUsedGlobal(var);
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000347
Chandler Carruth0f30a122012-03-30 19:44:53 +0000348 // We may have to cast the constant because of the initializer
349 // mismatch above.
350 //
351 // FIXME: It is really dangerous to store this in the map; if anyone
352 // RAUW's the GV uses of this constant will be invalid.
John McCall355bba72012-03-30 21:00:39 +0000353 llvm::Constant *castedAddr = llvm::ConstantExpr::getBitCast(var, expectedType);
354 DMEntry = castedAddr;
355 CGM.setStaticLocalDeclAddress(&D, castedAddr);
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000356
357 // Emit global variable debug descriptor for static vars.
Anders Carlssone896d982009-02-13 08:11:52 +0000358 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonovfd00eec2012-05-04 07:39:27 +0000359 if (DI &&
Douglas Gregor4cdad312012-10-23 20:05:01 +0000360 CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000361 DI->setLocation(D.getLocation());
John McCall355bba72012-03-30 21:00:39 +0000362 DI->EmitGlobalVariable(var, &D);
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000363 }
Anders Carlsson1a86b332007-10-17 00:52:43 +0000364}
Mike Stump1eb44332009-09-09 15:08:12 +0000365
John McCallda65ea82010-07-13 20:32:21 +0000366namespace {
John McCallbdc4d802011-07-09 01:37:26 +0000367 struct DestroyObject : EHScopeStack::Cleanup {
368 DestroyObject(llvm::Value *addr, QualType type,
John McCall2673c682011-07-11 08:38:19 +0000369 CodeGenFunction::Destroyer *destroyer,
370 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000371 : addr(addr), type(type), destroyer(destroyer),
John McCall2673c682011-07-11 08:38:19 +0000372 useEHCleanupForArray(useEHCleanupForArray) {}
John McCallda65ea82010-07-13 20:32:21 +0000373
John McCallbdc4d802011-07-09 01:37:26 +0000374 llvm::Value *addr;
375 QualType type;
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000376 CodeGenFunction::Destroyer *destroyer;
John McCall2673c682011-07-11 08:38:19 +0000377 bool useEHCleanupForArray;
John McCallda65ea82010-07-13 20:32:21 +0000378
John McCallad346f42011-07-12 20:27:29 +0000379 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall2673c682011-07-11 08:38:19 +0000380 // Don't use an EH cleanup recursively from an EH cleanup.
John McCallad346f42011-07-12 20:27:29 +0000381 bool useEHCleanupForArray =
382 flags.isForNormalCleanup() && this->useEHCleanupForArray;
John McCall2673c682011-07-11 08:38:19 +0000383
384 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
John McCallda65ea82010-07-13 20:32:21 +0000385 }
386 };
387
John McCallbdc4d802011-07-09 01:37:26 +0000388 struct DestroyNRVOVariable : EHScopeStack::Cleanup {
389 DestroyNRVOVariable(llvm::Value *addr,
390 const CXXDestructorDecl *Dtor,
391 llvm::Value *NRVOFlag)
392 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
John McCallda65ea82010-07-13 20:32:21 +0000393
394 const CXXDestructorDecl *Dtor;
395 llvm::Value *NRVOFlag;
396 llvm::Value *Loc;
397
John McCallad346f42011-07-12 20:27:29 +0000398 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallda65ea82010-07-13 20:32:21 +0000399 // Along the exceptions path we always execute the dtor.
John McCallad346f42011-07-12 20:27:29 +0000400 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
John McCallda65ea82010-07-13 20:32:21 +0000401
402 llvm::BasicBlock *SkipDtorBB = 0;
403 if (NRVO) {
404 // If we exited via NRVO, we skip the destructor call.
405 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
406 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
407 llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
408 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
409 CGF.EmitBlock(RunDtorBB);
410 }
Eric Christophere1f54902011-08-23 22:38:00 +0000411
John McCallda65ea82010-07-13 20:32:21 +0000412 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor378e1e72013-01-31 05:50:40 +0000413 /*ForVirtualBase=*/false,
414 /*Delegating=*/false,
415 Loc);
John McCallda65ea82010-07-13 20:32:21 +0000416
417 if (NRVO) CGF.EmitBlock(SkipDtorBB);
418 }
419 };
John McCallda65ea82010-07-13 20:32:21 +0000420
John McCall1f0fca52010-07-21 07:22:38 +0000421 struct CallStackRestore : EHScopeStack::Cleanup {
John McCalld8715092010-07-21 06:13:08 +0000422 llvm::Value *Stack;
423 CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
John McCallad346f42011-07-12 20:27:29 +0000424 void Emit(CodeGenFunction &CGF, Flags flags) {
Benjamin Kramer578faa82011-09-27 21:06:10 +0000425 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
John McCalld8715092010-07-21 06:13:08 +0000426 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
427 CGF.Builder.CreateCall(F, V);
428 }
429 };
430
John McCall0c24c802011-06-24 23:21:27 +0000431 struct ExtendGCLifetime : EHScopeStack::Cleanup {
432 const VarDecl &Var;
433 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
434
John McCallad346f42011-07-12 20:27:29 +0000435 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall0c24c802011-06-24 23:21:27 +0000436 // Compute the address of the local variable, in case it's a
437 // byref or something.
John McCallf4b88a42012-03-10 09:33:50 +0000438 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
439 Var.getType(), VK_LValue, SourceLocation());
John McCall0c24c802011-06-24 23:21:27 +0000440 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE));
441 CGF.EmitExtendGCLifetime(value);
442 }
443 };
444
John McCall1f0fca52010-07-21 07:22:38 +0000445 struct CallCleanupFunction : EHScopeStack::Cleanup {
John McCalld8715092010-07-21 06:13:08 +0000446 llvm::Constant *CleanupFn;
447 const CGFunctionInfo &FnInfo;
John McCalld8715092010-07-21 06:13:08 +0000448 const VarDecl &Var;
Eric Christophere1f54902011-08-23 22:38:00 +0000449
John McCalld8715092010-07-21 06:13:08 +0000450 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCall34695852011-02-22 06:44:22 +0000451 const VarDecl *Var)
452 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalld8715092010-07-21 06:13:08 +0000453
John McCallad346f42011-07-12 20:27:29 +0000454 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf4b88a42012-03-10 09:33:50 +0000455 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
456 Var.getType(), VK_LValue, SourceLocation());
John McCall34695852011-02-22 06:44:22 +0000457 // Compute the address of the local variable, in case it's a byref
458 // or something.
459 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
460
John McCalld8715092010-07-21 06:13:08 +0000461 // In some cases, the type of the function argument will be different from
462 // the type of the pointer. An example of this is
463 // void f(void* arg);
464 // __attribute__((cleanup(f))) void *g;
465 //
466 // To fix this we insert a bitcast here.
467 QualType ArgTy = FnInfo.arg_begin()->type;
468 llvm::Value *Arg =
469 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
470
471 CallArgList Args;
Eli Friedman04c9a492011-05-02 17:57:46 +0000472 Args.add(RValue::get(Arg),
473 CGF.getContext().getPointerType(Var.getType()));
John McCalld8715092010-07-21 06:13:08 +0000474 CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
475 }
476 };
Nadav Rotem495cfa42013-03-23 06:43:35 +0000477
478 /// A cleanup to call @llvm.lifetime.end.
479 class CallLifetimeEnd : public EHScopeStack::Cleanup {
480 llvm::Value *Addr;
481 llvm::Value *Size;
482 public:
483 CallLifetimeEnd(llvm::Value *addr, llvm::Value *size)
484 : Addr(addr), Size(size) {}
485
486 void Emit(CodeGenFunction &CGF, Flags flags) {
487 llvm::Value *castAddr = CGF.Builder.CreateBitCast(Addr, CGF.Int8PtrTy);
488 CGF.Builder.CreateCall2(CGF.CGM.getLLVMLifetimeEndFn(),
489 Size, castAddr)
490 ->setDoesNotThrow();
491 }
492 };
John McCalld8715092010-07-21 06:13:08 +0000493}
494
John McCallf85e1932011-06-15 23:02:42 +0000495/// EmitAutoVarWithLifetime - Does the setup required for an automatic
496/// variable with lifetime.
497static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
498 llvm::Value *addr,
499 Qualifiers::ObjCLifetime lifetime) {
500 switch (lifetime) {
501 case Qualifiers::OCL_None:
502 llvm_unreachable("present but none");
503
504 case Qualifiers::OCL_ExplicitNone:
505 // nothing to do
506 break;
507
508 case Qualifiers::OCL_Strong: {
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000509 CodeGenFunction::Destroyer *destroyer =
John McCall9928c482011-07-12 16:41:08 +0000510 (var.hasAttr<ObjCPreciseLifetimeAttr>()
511 ? CodeGenFunction::destroyARCStrongPrecise
512 : CodeGenFunction::destroyARCStrongImprecise);
513
514 CleanupKind cleanupKind = CGF.getARCCleanupKind();
515 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
516 cleanupKind & EHCleanup);
John McCallf85e1932011-06-15 23:02:42 +0000517 break;
518 }
519 case Qualifiers::OCL_Autoreleasing:
520 // nothing to do
521 break;
Eric Christophere1f54902011-08-23 22:38:00 +0000522
John McCallf85e1932011-06-15 23:02:42 +0000523 case Qualifiers::OCL_Weak:
524 // __weak objects always get EH cleanups; otherwise, exceptions
525 // could cause really nasty crashes instead of mere leaks.
John McCall9928c482011-07-12 16:41:08 +0000526 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
527 CodeGenFunction::destroyARCWeak,
528 /*useEHCleanup*/ true);
John McCallf85e1932011-06-15 23:02:42 +0000529 break;
530 }
531}
532
533static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
534 if (const Expr *e = dyn_cast<Expr>(s)) {
535 // Skip the most common kinds of expressions that make
536 // hierarchy-walking expensive.
537 s = e = e->IgnoreParenCasts();
538
539 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
540 return (ref->getDecl() == &var);
Fariborz Jahanianddfc8a12012-06-19 20:53:26 +0000541 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
542 const BlockDecl *block = be->getBlockDecl();
543 for (BlockDecl::capture_const_iterator i = block->capture_begin(),
544 e = block->capture_end(); i != e; ++i) {
545 if (i->getVariable() == &var)
546 return true;
547 }
548 }
John McCallf85e1932011-06-15 23:02:42 +0000549 }
550
551 for (Stmt::const_child_range children = s->children(); children; ++children)
Fariborz Jahanian8fefc8e2011-06-29 20:00:16 +0000552 // children might be null; as in missing decl or conditional of an if-stmt.
553 if ((*children) && isAccessedBy(var, *children))
John McCallf85e1932011-06-15 23:02:42 +0000554 return true;
555
556 return false;
557}
558
559static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
560 if (!decl) return false;
561 if (!isa<VarDecl>(decl)) return false;
562 const VarDecl *var = cast<VarDecl>(decl);
563 return isAccessedBy(*var, e);
564}
565
John McCalla07398e2011-06-16 04:16:24 +0000566static void drillIntoBlockVariable(CodeGenFunction &CGF,
567 LValue &lvalue,
568 const VarDecl *var) {
569 lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var));
570}
571
John McCallf85e1932011-06-15 23:02:42 +0000572void CodeGenFunction::EmitScalarInit(const Expr *init,
573 const ValueDecl *D,
John McCalla07398e2011-06-16 04:16:24 +0000574 LValue lvalue,
575 bool capturedByInit) {
John McCalla07398e2011-06-16 04:16:24 +0000576 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
John McCallf85e1932011-06-15 23:02:42 +0000577 if (!lifetime) {
578 llvm::Value *value = EmitScalarExpr(init);
John McCalla07398e2011-06-16 04:16:24 +0000579 if (capturedByInit)
580 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Chisnall7a7ee302012-01-16 17:27:18 +0000581 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
John McCallf85e1932011-06-15 23:02:42 +0000582 return;
583 }
584
585 // If we're emitting a value with lifetime, we have to do the
586 // initialization *before* we leave the cleanup scopes.
John McCall1a343eb2011-11-10 08:15:53 +0000587 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
588 enterFullExpression(ewc);
John McCallf85e1932011-06-15 23:02:42 +0000589 init = ewc->getSubExpr();
John McCall1a343eb2011-11-10 08:15:53 +0000590 }
591 CodeGenFunction::RunCleanupsScope Scope(*this);
John McCallf85e1932011-06-15 23:02:42 +0000592
593 // We have to maintain the illusion that the variable is
594 // zero-initialized. If the variable might be accessed in its
595 // initializer, zero-initialize before running the initializer, then
596 // actually perform the initialization with an assign.
597 bool accessedByInit = false;
598 if (lifetime != Qualifiers::OCL_ExplicitNone)
John McCallfb720812011-07-28 07:23:35 +0000599 accessedByInit = (capturedByInit || isAccessedBy(D, init));
John McCallf85e1932011-06-15 23:02:42 +0000600 if (accessedByInit) {
John McCalla07398e2011-06-16 04:16:24 +0000601 LValue tempLV = lvalue;
John McCallf85e1932011-06-15 23:02:42 +0000602 // Drill down to the __block object if necessary.
John McCallf85e1932011-06-15 23:02:42 +0000603 if (capturedByInit) {
604 // We can use a simple GEP for this because it can't have been
605 // moved yet.
John McCalla07398e2011-06-16 04:16:24 +0000606 tempLV.setAddress(Builder.CreateStructGEP(tempLV.getAddress(),
607 getByRefValueLLVMField(cast<VarDecl>(D))));
John McCallf85e1932011-06-15 23:02:42 +0000608 }
609
Chris Lattner2acc6e32011-07-18 04:24:23 +0000610 llvm::PointerType *ty
John McCalla07398e2011-06-16 04:16:24 +0000611 = cast<llvm::PointerType>(tempLV.getAddress()->getType());
John McCallf85e1932011-06-15 23:02:42 +0000612 ty = cast<llvm::PointerType>(ty->getElementType());
613
614 llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
Eric Christophere1f54902011-08-23 22:38:00 +0000615
John McCallf85e1932011-06-15 23:02:42 +0000616 // If __weak, we want to use a barrier under certain conditions.
617 if (lifetime == Qualifiers::OCL_Weak)
John McCalla07398e2011-06-16 04:16:24 +0000618 EmitARCInitWeak(tempLV.getAddress(), zero);
John McCallf85e1932011-06-15 23:02:42 +0000619
620 // Otherwise just do a simple store.
621 else
David Chisnall7a7ee302012-01-16 17:27:18 +0000622 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
John McCallf85e1932011-06-15 23:02:42 +0000623 }
624
625 // Emit the initializer.
626 llvm::Value *value = 0;
627
628 switch (lifetime) {
629 case Qualifiers::OCL_None:
630 llvm_unreachable("present but none");
631
632 case Qualifiers::OCL_ExplicitNone:
633 // nothing to do
634 value = EmitScalarExpr(init);
635 break;
636
637 case Qualifiers::OCL_Strong: {
638 value = EmitARCRetainScalarExpr(init);
639 break;
640 }
641
642 case Qualifiers::OCL_Weak: {
643 // No way to optimize a producing initializer into this. It's not
644 // worth optimizing for, because the value will immediately
645 // disappear in the common case.
646 value = EmitScalarExpr(init);
647
John McCalla07398e2011-06-16 04:16:24 +0000648 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCallf85e1932011-06-15 23:02:42 +0000649 if (accessedByInit)
John McCalla07398e2011-06-16 04:16:24 +0000650 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
John McCallf85e1932011-06-15 23:02:42 +0000651 else
John McCalla07398e2011-06-16 04:16:24 +0000652 EmitARCInitWeak(lvalue.getAddress(), value);
John McCallf85e1932011-06-15 23:02:42 +0000653 return;
654 }
655
656 case Qualifiers::OCL_Autoreleasing:
657 value = EmitARCRetainAutoreleaseScalarExpr(init);
658 break;
659 }
660
John McCalla07398e2011-06-16 04:16:24 +0000661 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCallf85e1932011-06-15 23:02:42 +0000662
663 // If the variable might have been accessed by its initializer, we
664 // might have to initialize with a barrier. We have to do this for
665 // both __weak and __strong, but __weak got filtered out above.
666 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
John McCalla07398e2011-06-16 04:16:24 +0000667 llvm::Value *oldValue = EmitLoadOfScalar(lvalue);
David Chisnall7a7ee302012-01-16 17:27:18 +0000668 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCall5b07e802013-03-13 03:10:54 +0000669 EmitARCRelease(oldValue, ARCImpreciseLifetime);
John McCallf85e1932011-06-15 23:02:42 +0000670 return;
671 }
672
David Chisnall7a7ee302012-01-16 17:27:18 +0000673 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCallf85e1932011-06-15 23:02:42 +0000674}
Chris Lattner94cd0112010-12-01 02:05:19 +0000675
John McCall7acddac2011-06-17 06:42:21 +0000676/// EmitScalarInit - Initialize the given lvalue with the given object.
677void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
678 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
679 if (!lifetime)
David Chisnall7a7ee302012-01-16 17:27:18 +0000680 return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
John McCall7acddac2011-06-17 06:42:21 +0000681
682 switch (lifetime) {
683 case Qualifiers::OCL_None:
684 llvm_unreachable("present but none");
685
686 case Qualifiers::OCL_ExplicitNone:
687 // nothing to do
688 break;
689
690 case Qualifiers::OCL_Strong:
691 init = EmitARCRetain(lvalue.getType(), init);
692 break;
693
694 case Qualifiers::OCL_Weak:
695 // Initialize and then skip the primitive store.
696 EmitARCInitWeak(lvalue.getAddress(), init);
697 return;
698
699 case Qualifiers::OCL_Autoreleasing:
700 init = EmitARCRetainAutorelease(lvalue.getType(), init);
701 break;
702 }
703
David Chisnall7a7ee302012-01-16 17:27:18 +0000704 EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
John McCall7acddac2011-06-17 06:42:21 +0000705}
706
Chris Lattner94cd0112010-12-01 02:05:19 +0000707/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
708/// non-zero parts of the specified initializer with equal or fewer than
709/// NumStores scalar stores.
710static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
711 unsigned &NumStores) {
Chris Lattner70b02942010-12-02 01:58:41 +0000712 // Zero and Undef never requires any extra stores.
713 if (isa<llvm::ConstantAggregateZero>(Init) ||
714 isa<llvm::ConstantPointerNull>(Init) ||
715 isa<llvm::UndefValue>(Init))
716 return true;
717 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
718 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
719 isa<llvm::ConstantExpr>(Init))
720 return Init->isNullValue() || NumStores--;
721
722 // See if we can emit each element.
723 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
724 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
725 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
726 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
727 return false;
728 }
729 return true;
730 }
Chris Lattnerf492cb12012-01-31 04:36:19 +0000731
732 if (llvm::ConstantDataSequential *CDS =
733 dyn_cast<llvm::ConstantDataSequential>(Init)) {
734 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
735 llvm::Constant *Elt = CDS->getElementAsConstant(i);
736 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
737 return false;
738 }
739 return true;
740 }
Eric Christophere1f54902011-08-23 22:38:00 +0000741
Chris Lattner94cd0112010-12-01 02:05:19 +0000742 // Anything else is hard and scary.
743 return false;
744}
745
746/// emitStoresForInitAfterMemset - For inits that
747/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
748/// stores that would be required.
749static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
John McCall34695852011-02-22 06:44:22 +0000750 bool isVolatile, CGBuilderTy &Builder) {
Benjamin Kramer06d43682012-08-27 22:07:02 +0000751 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
752 "called emitStoresForInitAfterMemset for zero or undef value.");
Eric Christophere1f54902011-08-23 22:38:00 +0000753
Chris Lattner70b02942010-12-02 01:58:41 +0000754 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
755 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
756 isa<llvm::ConstantExpr>(Init)) {
Chris Lattnerf492cb12012-01-31 04:36:19 +0000757 Builder.CreateStore(Init, Loc, isVolatile);
758 return;
759 }
760
761 if (llvm::ConstantDataSequential *CDS =
762 dyn_cast<llvm::ConstantDataSequential>(Init)) {
763 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
764 llvm::Constant *Elt = CDS->getElementAsConstant(i);
Benjamin Kramercfa07e32012-08-27 21:35:58 +0000765
766 // If necessary, get a pointer to the element and emit it.
767 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
768 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
769 isVolatile, Builder);
Chris Lattnerf492cb12012-01-31 04:36:19 +0000770 }
Chris Lattner70b02942010-12-02 01:58:41 +0000771 return;
772 }
Eric Christophere1f54902011-08-23 22:38:00 +0000773
Chris Lattner70b02942010-12-02 01:58:41 +0000774 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
775 "Unknown value type!");
Eric Christophere1f54902011-08-23 22:38:00 +0000776
Chris Lattner70b02942010-12-02 01:58:41 +0000777 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
778 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
Benjamin Kramercfa07e32012-08-27 21:35:58 +0000779
780 // If necessary, get a pointer to the element and emit it.
781 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
782 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
783 isVolatile, Builder);
Chris Lattner70b02942010-12-02 01:58:41 +0000784 }
Chris Lattner94cd0112010-12-01 02:05:19 +0000785}
786
787
788/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
789/// plus some stores to initialize a local variable instead of using a memcpy
790/// from a constant global. It is beneficial to use memset if the global is all
791/// zeros, or mostly zeros and large.
792static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
793 uint64_t GlobalSize) {
794 // If a global is all zeros, always use a memset.
795 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
796
Chris Lattner94cd0112010-12-01 02:05:19 +0000797 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
798 // do it if it will require 6 or fewer scalar stores.
799 // TODO: Should budget depends on the size? Avoiding a large global warrants
800 // plopping in more stores.
801 unsigned StoreBudget = 6;
802 uint64_t SizeLimit = 32;
Eric Christophere1f54902011-08-23 22:38:00 +0000803
804 return GlobalSize > SizeLimit &&
Chris Lattner94cd0112010-12-01 02:05:19 +0000805 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
806}
807
Nadav Rotem495cfa42013-03-23 06:43:35 +0000808/// Should we use the LLVM lifetime intrinsics for the given local variable?
809static bool shouldUseLifetimeMarkers(CodeGenFunction &CGF, const VarDecl &D,
810 unsigned Size) {
Alexey Samsonov4f01ed42013-04-02 13:19:46 +0000811 // Always emit lifetime markers in -fsanitize=use-after-scope mode.
812 if (CGF.getLangOpts().Sanitize.UseAfterScope)
813 return true;
Nadav Rotem495cfa42013-03-23 06:43:35 +0000814 // For now, only in optimized builds.
815 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0)
816 return false;
817
818 // Limit the size of marked objects to 32 bytes. We don't want to increase
819 // compile time by marking tiny objects.
820 unsigned SizeThreshold = 32;
821
822 return Size > SizeThreshold;
823}
824
Chris Lattner94cd0112010-12-01 02:05:19 +0000825
Nick Lewyckya9de3fa2010-12-30 20:21:55 +0000826/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Reid Spencer5f016e22007-07-11 17:01:13 +0000827/// variable declaration with auto, register, or no storage class specifier.
Chris Lattner2621fd12008-05-08 05:58:21 +0000828/// These turn into simple stack objects, or GlobalValues depending on target.
John McCall34695852011-02-22 06:44:22 +0000829void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
830 AutoVarEmission emission = EmitAutoVarAlloca(D);
831 EmitAutoVarInit(emission);
832 EmitAutoVarCleanups(emission);
833}
Reid Spencer5f016e22007-07-11 17:01:13 +0000834
John McCall34695852011-02-22 06:44:22 +0000835/// EmitAutoVarAlloca - Emit the alloca and debug information for a
836/// local variable. Does not emit initalization or destruction.
837CodeGenFunction::AutoVarEmission
838CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
839 QualType Ty = D.getType();
840
841 AutoVarEmission emission(D);
842
843 bool isByRef = D.hasAttr<BlocksAttr>();
844 emission.IsByRef = isByRef;
845
846 CharUnits alignment = getContext().getDeclAlign(&D);
847 emission.Alignment = alignment;
848
John McCallbc8d40d2011-06-24 21:55:10 +0000849 // If the type is variably-modified, emit all the VLA sizes for it.
850 if (Ty->isVariablyModifiedType())
851 EmitVariablyModifiedType(Ty);
852
Reid Spencer5f016e22007-07-11 17:01:13 +0000853 llvm::Value *DeclPtr;
Eli Friedman3c2b3172008-02-15 12:20:59 +0000854 if (Ty->isConstantSizeType()) {
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000855 bool NRVO = getLangOpts().ElideConstructors &&
856 D.isNRVOVariable();
John McCall34695852011-02-22 06:44:22 +0000857
Richard Smithe67ca582013-06-02 00:09:52 +0000858 // If this value is an array or struct with a statically determinable
859 // constant initializer, there are optimizations we can do.
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000860 //
861 // TODO: We should constant-evaluate the initializer of any variable,
862 // as long as it is initialized by a constant expression. Currently,
863 // isConstantInitializer produces wrong answers for structs with
864 // reference or bitfield members, and a few other cases, and checking
865 // for POD-ness protects us from some of these.
Richard Smithe67ca582013-06-02 00:09:52 +0000866 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
867 (D.isConstexpr() ||
868 ((Ty.isPODType(getContext()) ||
869 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
870 D.getInit()->isConstantInitializer(getContext(), false)))) {
John McCall34695852011-02-22 06:44:22 +0000871
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000872 // If the variable's a const type, and it's neither an NRVO
873 // candidate nor a __block variable and has no mutable members,
874 // emit it as a global instead.
875 if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
876 CGM.isTypeConstant(Ty, true)) {
877 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCall34695852011-02-22 06:44:22 +0000878
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000879 emission.Address = 0; // signal this condition to later callbacks
880 assert(emission.wasEmittedAsGlobal());
881 return emission;
Tanya Lattner59876c22009-11-04 01:18:09 +0000882 }
Eric Christophere1f54902011-08-23 22:38:00 +0000883
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000884 // Otherwise, tell the initialization code that we're in this case.
885 emission.IsConstantAggregate = true;
886 }
Eric Christophere1f54902011-08-23 22:38:00 +0000887
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000888 // A normal fixed sized variable becomes an alloca in the entry block,
889 // unless it's an NRVO variable.
890 llvm::Type *LTy = ConvertTypeForMem(Ty);
Eric Christophere1f54902011-08-23 22:38:00 +0000891
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000892 if (NRVO) {
893 // The named return value optimization: allocate this variable in the
894 // return slot, so that we can elide the copy when returning this
895 // variable (C++0x [class.copy]p34).
896 DeclPtr = ReturnValue;
Eric Christophere1f54902011-08-23 22:38:00 +0000897
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000898 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
899 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
900 // Create a flag that is used to indicate when the NRVO was applied
901 // to this variable. Set it to zero to indicate that NRVO was not
902 // applied.
903 llvm::Value *Zero = Builder.getFalse();
904 llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
905 EnsureInsertPoint();
906 Builder.CreateStore(Zero, NRVOFlag);
Eric Christophere1f54902011-08-23 22:38:00 +0000907
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000908 // Record the NRVO flag for this variable.
909 NRVOFlags[&D] = NRVOFlag;
910 emission.NRVOFlag = NRVOFlag;
Nadav Rotem495cfa42013-03-23 06:43:35 +0000911 }
Douglas Gregord86c4772010-05-15 06:46:45 +0000912 }
Chris Lattner2621fd12008-05-08 05:58:21 +0000913 } else {
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000914 if (isByRef)
915 LTy = BuildByRefType(&D);
916
917 llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
918 Alloc->setName(D.getName());
919
920 CharUnits allocaAlignment = alignment;
921 if (isByRef)
922 allocaAlignment = std::max(allocaAlignment,
John McCall64aa4b32013-04-16 22:48:15 +0000923 getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0)));
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000924 Alloc->setAlignment(allocaAlignment.getQuantity());
925 DeclPtr = Alloc;
926
927 // Emit a lifetime intrinsic if meaningful. There's no point
928 // in doing this if we don't have a valid insertion point (?).
929 uint64_t size = CGM.getDataLayout().getTypeAllocSize(LTy);
930 if (HaveInsertPoint() && shouldUseLifetimeMarkers(*this, D, size)) {
931 llvm::Value *sizeV = llvm::ConstantInt::get(Int64Ty, size);
932
933 emission.SizeForLifetimeMarkers = sizeV;
934 llvm::Value *castAddr = Builder.CreateBitCast(Alloc, Int8PtrTy);
935 Builder.CreateCall2(CGM.getLLVMLifetimeStartFn(), sizeV, castAddr)
936 ->setDoesNotThrow();
937 } else {
938 assert(!emission.useLifetimeMarkers());
939 }
Chris Lattner2621fd12008-05-08 05:58:21 +0000940 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000941 } else {
Daniel Dunbard286f052009-07-19 06:58:07 +0000942 EnsureInsertPoint();
943
Anders Carlsson5ecb1b92009-02-09 20:41:50 +0000944 if (!DidCallStackSave) {
Anders Carlsson5d463152008-12-12 07:38:43 +0000945 // Save the stack.
John McCalld16c2cf2011-02-08 08:22:06 +0000946 llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
Mike Stump1eb44332009-09-09 15:08:12 +0000947
Anders Carlsson5d463152008-12-12 07:38:43 +0000948 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
949 llvm::Value *V = Builder.CreateCall(F);
Mike Stump1eb44332009-09-09 15:08:12 +0000950
Anders Carlsson5d463152008-12-12 07:38:43 +0000951 Builder.CreateStore(V, Stack);
Anders Carlsson5ecb1b92009-02-09 20:41:50 +0000952
953 DidCallStackSave = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000954
John McCalld8715092010-07-21 06:13:08 +0000955 // Push a cleanup block and restore the stack there.
John McCall3ad32c82011-01-28 08:37:24 +0000956 // FIXME: in general circumstances, this should be an EH cleanup.
John McCall1f0fca52010-07-21 07:22:38 +0000957 EHStack.pushCleanup<CallStackRestore>(NormalCleanup, Stack);
Anders Carlsson5d463152008-12-12 07:38:43 +0000958 }
Mike Stump1eb44332009-09-09 15:08:12 +0000959
John McCallbc8d40d2011-06-24 21:55:10 +0000960 llvm::Value *elementCount;
961 QualType elementType;
962 llvm::tie(elementCount, elementType) = getVLASize(Ty);
Anders Carlsson5d463152008-12-12 07:38:43 +0000963
Chris Lattner2acc6e32011-07-18 04:24:23 +0000964 llvm::Type *llvmTy = ConvertTypeForMem(elementType);
Anders Carlsson5d463152008-12-12 07:38:43 +0000965
966 // Allocate memory for the array.
John McCallbc8d40d2011-06-24 21:55:10 +0000967 llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
968 vla->setAlignment(alignment.getQuantity());
Anders Carlsson41f8a132009-09-26 18:16:06 +0000969
John McCallbc8d40d2011-06-24 21:55:10 +0000970 DeclPtr = vla;
Reid Spencer5f016e22007-07-11 17:01:13 +0000971 }
Eli Friedman8f39f5e2008-12-20 23:11:59 +0000972
Reid Spencer5f016e22007-07-11 17:01:13 +0000973 llvm::Value *&DMEntry = LocalDeclMap[&D];
974 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
975 DMEntry = DeclPtr;
John McCall34695852011-02-22 06:44:22 +0000976 emission.Address = DeclPtr;
Sanjiv Guptacc9b1632008-05-30 10:30:31 +0000977
978 // Emit debug info for local var declaration.
Devang Patelc594abd2011-06-03 19:21:47 +0000979 if (HaveInsertPoint())
980 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregor4cdad312012-10-23 20:05:01 +0000981 if (CGM.getCodeGenOpts().getDebugInfo()
982 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonovfd00eec2012-05-04 07:39:27 +0000983 DI->setLocation(D.getLocation());
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000984 DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
Alexey Samsonovfd00eec2012-05-04 07:39:27 +0000985 }
Devang Patelc594abd2011-06-03 19:21:47 +0000986 }
Sanjiv Guptacc9b1632008-05-30 10:30:31 +0000987
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000988 if (D.hasAttr<AnnotateAttr>())
989 EmitVarAnnotations(&D, emission.Address);
990
John McCall34695852011-02-22 06:44:22 +0000991 return emission;
992}
993
994/// Determines whether the given __block variable is potentially
995/// captured by the given expression.
996static bool isCapturedBy(const VarDecl &var, const Expr *e) {
997 // Skip the most common kinds of expressions that make
998 // hierarchy-walking expensive.
999 e = e->IgnoreParenCasts();
1000
1001 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
1002 const BlockDecl *block = be->getBlockDecl();
1003 for (BlockDecl::capture_const_iterator i = block->capture_begin(),
1004 e = block->capture_end(); i != e; ++i) {
1005 if (i->getVariable() == &var)
1006 return true;
1007 }
1008
1009 // No need to walk into the subexpressions.
1010 return false;
1011 }
1012
Fariborz Jahanian5033be12011-08-23 16:47:15 +00001013 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1014 const CompoundStmt *CS = SE->getSubStmt();
Eric Christopherc6fad602011-08-23 23:44:09 +00001015 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1016 BE = CS->body_end(); BI != BE; ++BI)
Fariborz Jahanian045c8422011-08-25 00:06:26 +00001017 if (Expr *E = dyn_cast<Expr>((*BI))) {
Fariborz Jahanian5033be12011-08-23 16:47:15 +00001018 if (isCapturedBy(var, E))
1019 return true;
Fariborz Jahanian045c8422011-08-25 00:06:26 +00001020 }
1021 else if (DeclStmt *DS = dyn_cast<DeclStmt>((*BI))) {
1022 // special case declarations
1023 for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
1024 I != E; ++I) {
1025 if (VarDecl *VD = dyn_cast<VarDecl>((*I))) {
1026 Expr *Init = VD->getInit();
1027 if (Init && isCapturedBy(var, Init))
1028 return true;
1029 }
1030 }
1031 }
1032 else
1033 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1034 // Later, provide code to poke into statements for capture analysis.
1035 return true;
Fariborz Jahanian5033be12011-08-23 16:47:15 +00001036 return false;
1037 }
Eric Christophere1f54902011-08-23 22:38:00 +00001038
John McCall34695852011-02-22 06:44:22 +00001039 for (Stmt::const_child_range children = e->children(); children; ++children)
1040 if (isCapturedBy(var, cast<Expr>(*children)))
1041 return true;
1042
1043 return false;
1044}
1045
Douglas Gregorbcc3e662011-07-01 21:08:19 +00001046/// \brief Determine whether the given initializer is trivial in the sense
1047/// that it requires no code to be generated.
1048static bool isTrivialInitializer(const Expr *Init) {
1049 if (!Init)
1050 return true;
Eric Christophere1f54902011-08-23 22:38:00 +00001051
Douglas Gregorbcc3e662011-07-01 21:08:19 +00001052 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1053 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1054 if (Constructor->isTrivial() &&
1055 Constructor->isDefaultConstructor() &&
1056 !Construct->requiresZeroInitialization())
1057 return true;
Eric Christophere1f54902011-08-23 22:38:00 +00001058
Douglas Gregorbcc3e662011-07-01 21:08:19 +00001059 return false;
1060}
John McCall34695852011-02-22 06:44:22 +00001061void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall57b3b6a2011-02-22 07:16:58 +00001062 assert(emission.Variable && "emission was not valid!");
1063
John McCall34695852011-02-22 06:44:22 +00001064 // If this was emitted as a global constant, we're done.
1065 if (emission.wasEmittedAsGlobal()) return;
1066
John McCall57b3b6a2011-02-22 07:16:58 +00001067 const VarDecl &D = *emission.Variable;
John McCall34695852011-02-22 06:44:22 +00001068 QualType type = D.getType();
1069
Chris Lattner19785962007-07-12 00:39:48 +00001070 // If this local has an initializer, emit it now.
Daniel Dunbard286f052009-07-19 06:58:07 +00001071 const Expr *Init = D.getInit();
1072
1073 // If we are at an unreachable point, we don't need to emit the initializer
1074 // unless it contains a label.
1075 if (!HaveInsertPoint()) {
John McCall34695852011-02-22 06:44:22 +00001076 if (!Init || !ContainsLabel(Init)) return;
1077 EnsureInsertPoint();
Daniel Dunbard286f052009-07-19 06:58:07 +00001078 }
1079
John McCall5af02db2011-03-31 01:59:53 +00001080 // Initialize the structure of a __block variable.
1081 if (emission.IsByRef)
1082 emitByrefStructureInit(emission);
Anders Carlsson69c68b72009-02-07 23:51:38 +00001083
Douglas Gregorbcc3e662011-07-01 21:08:19 +00001084 if (isTrivialInitializer(Init))
1085 return;
Eric Christophere1f54902011-08-23 22:38:00 +00001086
John McCall5af02db2011-03-31 01:59:53 +00001087 CharUnits alignment = emission.Alignment;
1088
John McCall34695852011-02-22 06:44:22 +00001089 // Check whether this is a byref variable that's potentially
1090 // captured and moved by its own initializer. If so, we'll need to
1091 // emit the initializer first, then copy into the variable.
1092 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1093
1094 llvm::Value *Loc =
1095 capturedByInit ? emission.Address : emission.getObjectAddress(*this);
1096
Richard Smith51201882011-12-30 21:15:51 +00001097 llvm::Constant *constant = 0;
Richard Smithe67ca582013-06-02 00:09:52 +00001098 if (emission.IsConstantAggregate || D.isConstexpr()) {
Richard Smith51201882011-12-30 21:15:51 +00001099 assert(!capturedByInit && "constant init contains a capturing block?");
Richard Smith2d6a5672012-01-14 04:30:29 +00001100 constant = CGM.EmitConstantInit(D, this);
Richard Smith51201882011-12-30 21:15:51 +00001101 }
1102
1103 if (!constant) {
Eli Friedman6da2c712011-12-03 04:14:32 +00001104 LValue lv = MakeAddrLValue(Loc, type, alignment);
John McCalla07398e2011-06-16 04:16:24 +00001105 lv.setNonGC(true);
1106 return EmitExprAsInit(Init, &D, lv, capturedByInit);
1107 }
John McCall60d33652011-03-08 09:11:50 +00001108
Richard Smithe67ca582013-06-02 00:09:52 +00001109 if (!emission.IsConstantAggregate) {
1110 // For simple scalar/complex initialization, store the value directly.
1111 LValue lv = MakeAddrLValue(Loc, type, alignment);
1112 lv.setNonGC(true);
1113 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1114 }
1115
John McCall34695852011-02-22 06:44:22 +00001116 // If this is a simple aggregate initialization, we can optimize it
1117 // in various ways.
John McCall60d33652011-03-08 09:11:50 +00001118 bool isVolatile = type.isVolatileQualified();
John McCall34695852011-02-22 06:44:22 +00001119
John McCall60d33652011-03-08 09:11:50 +00001120 llvm::Value *SizeVal =
Eric Christophere1f54902011-08-23 22:38:00 +00001121 llvm::ConstantInt::get(IntPtrTy,
John McCall60d33652011-03-08 09:11:50 +00001122 getContext().getTypeSizeInChars(type).getQuantity());
John McCall34695852011-02-22 06:44:22 +00001123
Chris Lattner2acc6e32011-07-18 04:24:23 +00001124 llvm::Type *BP = Int8PtrTy;
John McCall60d33652011-03-08 09:11:50 +00001125 if (Loc->getType() != BP)
Benjamin Kramer578faa82011-09-27 21:06:10 +00001126 Loc = Builder.CreateBitCast(Loc, BP);
Mon P Wang3ecd7852010-04-04 03:10:52 +00001127
John McCall60d33652011-03-08 09:11:50 +00001128 // If the initializer is all or mostly zeros, codegen with memset then do
1129 // a few stores afterward.
Eric Christophere1f54902011-08-23 22:38:00 +00001130 if (shouldUseMemSetPlusStoresToInitialize(constant,
Micah Villmow25a6a842012-10-08 16:25:52 +00001131 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
John McCall60d33652011-03-08 09:11:50 +00001132 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1133 alignment.getQuantity(), isVolatile);
Benjamin Kramer06d43682012-08-27 22:07:02 +00001134 // Zero and undef don't require a stores.
1135 if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
John McCall60d33652011-03-08 09:11:50 +00001136 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
1137 emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +00001138 }
John McCall60d33652011-03-08 09:11:50 +00001139 } else {
Eric Christophere1f54902011-08-23 22:38:00 +00001140 // Otherwise, create a temporary global with the initializer then
John McCall60d33652011-03-08 09:11:50 +00001141 // memcpy from the global to the alloca.
1142 std::string Name = GetStaticDeclName(*this, D, ".");
1143 llvm::GlobalVariable *GV =
1144 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
Eric Christopher736a9c22011-08-24 00:33:55 +00001145 llvm::GlobalValue::PrivateLinkage,
Hans Wennborg5e2d5de2012-06-23 11:51:46 +00001146 constant, Name);
John McCall60d33652011-03-08 09:11:50 +00001147 GV->setAlignment(alignment.getQuantity());
Eli Friedman460980d2011-05-27 22:32:55 +00001148 GV->setUnnamedAddr(true);
Eric Christophere1f54902011-08-23 22:38:00 +00001149
John McCall60d33652011-03-08 09:11:50 +00001150 llvm::Value *SrcPtr = GV;
1151 if (SrcPtr->getType() != BP)
Benjamin Kramer578faa82011-09-27 21:06:10 +00001152 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
John McCall60d33652011-03-08 09:11:50 +00001153
1154 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
1155 isVolatile);
1156 }
1157}
1158
1159/// Emit an expression as an initializer for a variable at the given
1160/// location. The expression is not necessarily the normal
1161/// initializer for the variable, and the address is not necessarily
1162/// its normal location.
1163///
1164/// \param init the initializing expression
1165/// \param var the variable to act as if we're initializing
1166/// \param loc the address to initialize; its type is a pointer
1167/// to the LLVM mapping of the variable's type
1168/// \param alignment the alignment of the address
1169/// \param capturedByInit true if the variable is a __block variable
1170/// whose address is potentially changed by the initializer
1171void CodeGenFunction::EmitExprAsInit(const Expr *init,
John McCallf85e1932011-06-15 23:02:42 +00001172 const ValueDecl *D,
John McCalla07398e2011-06-16 04:16:24 +00001173 LValue lvalue,
John McCall60d33652011-03-08 09:11:50 +00001174 bool capturedByInit) {
John McCallf85e1932011-06-15 23:02:42 +00001175 QualType type = D->getType();
John McCall60d33652011-03-08 09:11:50 +00001176
1177 if (type->isReferenceType()) {
Richard Smithd4ec5622013-06-12 23:38:09 +00001178 RValue rvalue = EmitReferenceBindingToExpr(init);
Eric Christophere1f54902011-08-23 22:38:00 +00001179 if (capturedByInit)
John McCalla07398e2011-06-16 04:16:24 +00001180 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Chisnall7a7ee302012-01-16 17:27:18 +00001181 EmitStoreThroughLValue(rvalue, lvalue, true);
John McCall9d232c82013-03-07 21:37:08 +00001182 return;
1183 }
1184 switch (getEvaluationKind(type)) {
1185 case TEK_Scalar:
John McCalla07398e2011-06-16 04:16:24 +00001186 EmitScalarInit(init, D, lvalue, capturedByInit);
John McCall9d232c82013-03-07 21:37:08 +00001187 return;
1188 case TEK_Complex: {
John McCall60d33652011-03-08 09:11:50 +00001189 ComplexPairTy complex = EmitComplexExpr(init);
John McCalla07398e2011-06-16 04:16:24 +00001190 if (capturedByInit)
1191 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall9d232c82013-03-07 21:37:08 +00001192 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
1193 return;
1194 }
1195 case TEK_Aggregate:
John McCall9eda3ab2013-03-07 21:37:17 +00001196 if (type->isAtomicType()) {
1197 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1198 } else {
1199 // TODO: how can we delay here if D is captured by its initializer?
1200 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
Chad Rosier649b4a12012-03-29 17:37:10 +00001201 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001202 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001203 AggValueSlot::IsNotAliased));
John McCall9eda3ab2013-03-07 21:37:17 +00001204 }
John McCall9d232c82013-03-07 21:37:08 +00001205 return;
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +00001206 }
John McCall9d232c82013-03-07 21:37:08 +00001207 llvm_unreachable("bad evaluation kind");
John McCall34695852011-02-22 06:44:22 +00001208}
John McCallf1549f62010-07-06 01:34:17 +00001209
John McCallbdc4d802011-07-09 01:37:26 +00001210/// Enter a destroy cleanup for the given local variable.
1211void CodeGenFunction::emitAutoVarTypeCleanup(
1212 const CodeGenFunction::AutoVarEmission &emission,
1213 QualType::DestructionKind dtorKind) {
1214 assert(dtorKind != QualType::DK_none);
1215
1216 // Note that for __block variables, we want to destroy the
1217 // original stack object, not the possibly forwarded object.
1218 llvm::Value *addr = emission.getObjectAddress(*this);
1219
1220 const VarDecl *var = emission.Variable;
1221 QualType type = var->getType();
1222
1223 CleanupKind cleanupKind = NormalAndEHCleanup;
1224 CodeGenFunction::Destroyer *destroyer = 0;
1225
1226 switch (dtorKind) {
1227 case QualType::DK_none:
1228 llvm_unreachable("no cleanup for trivially-destructible variable");
1229
1230 case QualType::DK_cxx_destructor:
1231 // If there's an NRVO flag on the emission, we need a different
1232 // cleanup.
1233 if (emission.NRVOFlag) {
1234 assert(!type->isArrayType());
1235 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1236 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor,
1237 emission.NRVOFlag);
1238 return;
1239 }
1240 break;
1241
1242 case QualType::DK_objc_strong_lifetime:
1243 // Suppress cleanups for pseudo-strong variables.
1244 if (var->isARCPseudoStrong()) return;
Eric Christophere1f54902011-08-23 22:38:00 +00001245
John McCallbdc4d802011-07-09 01:37:26 +00001246 // Otherwise, consider whether to use an EH cleanup or not.
1247 cleanupKind = getARCCleanupKind();
1248
1249 // Use the imprecise destroyer by default.
1250 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1251 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1252 break;
1253
1254 case QualType::DK_objc_weak_lifetime:
1255 break;
1256 }
1257
1258 // If we haven't chosen a more specific destroyer, use the default.
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001259 if (!destroyer) destroyer = getDestroyer(dtorKind);
John McCall2673c682011-07-11 08:38:19 +00001260
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00001261 // Use an EH cleanup in array destructors iff the destructor itself
John McCall2673c682011-07-11 08:38:19 +00001262 // is being pushed as an EH cleanup.
1263 bool useEHCleanup = (cleanupKind & EHCleanup);
1264 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1265 useEHCleanup);
John McCallbdc4d802011-07-09 01:37:26 +00001266}
1267
John McCall34695852011-02-22 06:44:22 +00001268void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall57b3b6a2011-02-22 07:16:58 +00001269 assert(emission.Variable && "emission was not valid!");
1270
John McCall34695852011-02-22 06:44:22 +00001271 // If this was emitted as a global constant, we're done.
1272 if (emission.wasEmittedAsGlobal()) return;
1273
John McCall38baeab2012-04-13 18:44:05 +00001274 // If we don't have an insertion point, we're done. Sema prevents
1275 // us from jumping into any of these scopes anyway.
1276 if (!HaveInsertPoint()) return;
1277
John McCall57b3b6a2011-02-22 07:16:58 +00001278 const VarDecl &D = *emission.Variable;
John McCall34695852011-02-22 06:44:22 +00001279
Nadav Rotem495cfa42013-03-23 06:43:35 +00001280 // Make sure we call @llvm.lifetime.end. This needs to happen
1281 // *last*, so the cleanup needs to be pushed *first*.
1282 if (emission.useLifetimeMarkers()) {
1283 EHStack.pushCleanup<CallLifetimeEnd>(NormalCleanup,
1284 emission.getAllocatedAddress(),
1285 emission.getSizeForLifetimeMarkers());
1286 }
1287
John McCallbdc4d802011-07-09 01:37:26 +00001288 // Check the type for a cleanup.
1289 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1290 emitAutoVarTypeCleanup(emission, dtorKind);
John McCallf85e1932011-06-15 23:02:42 +00001291
John McCall0c24c802011-06-24 23:21:27 +00001292 // In GC mode, honor objc_precise_lifetime.
David Blaikie4e4d0842012-03-11 07:00:24 +00001293 if (getLangOpts().getGC() != LangOptions::NonGC &&
John McCall0c24c802011-06-24 23:21:27 +00001294 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1295 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1296 }
1297
John McCall34695852011-02-22 06:44:22 +00001298 // Handle the cleanup attribute.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001299 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlsson69c68b72009-02-07 23:51:38 +00001300 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001301
John McCall34695852011-02-22 06:44:22 +00001302 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlsson69c68b72009-02-07 23:51:38 +00001303 assert(F && "Could not find function!");
Mike Stump1eb44332009-09-09 15:08:12 +00001304
John McCallde5d3c72012-02-17 03:33:10 +00001305 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
John McCall34695852011-02-22 06:44:22 +00001306 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlsson69c68b72009-02-07 23:51:38 +00001307 }
Mike Stump797b6322009-03-05 01:23:13 +00001308
John McCall34695852011-02-22 06:44:22 +00001309 // If this is a block variable, call _Block_object_destroy
1310 // (on the unforwarded address).
John McCall5af02db2011-03-31 01:59:53 +00001311 if (emission.IsByRef)
1312 enterByrefCleanup(emission);
Reid Spencer5f016e22007-07-11 17:01:13 +00001313}
1314
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001315CodeGenFunction::Destroyer *
John McCallbdc4d802011-07-09 01:37:26 +00001316CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1317 switch (kind) {
1318 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
John McCall0850e8d2011-07-09 09:09:00 +00001319 case QualType::DK_cxx_destructor:
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001320 return destroyCXXObject;
John McCall0850e8d2011-07-09 09:09:00 +00001321 case QualType::DK_objc_strong_lifetime:
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001322 return destroyARCStrongPrecise;
John McCall0850e8d2011-07-09 09:09:00 +00001323 case QualType::DK_objc_weak_lifetime:
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001324 return destroyARCWeak;
John McCallbdc4d802011-07-09 01:37:26 +00001325 }
Matt Beaumont-Gayba4be252012-01-27 00:46:27 +00001326 llvm_unreachable("Unknown DestructionKind");
John McCallbdc4d802011-07-09 01:37:26 +00001327}
1328
John McCall074cae02013-02-01 05:11:40 +00001329/// pushEHDestroy - Push the standard destructor for the given type as
1330/// an EH-only cleanup.
1331void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
1332 llvm::Value *addr, QualType type) {
1333 assert(dtorKind && "cannot push destructor for trivial type");
1334 assert(needsEHCleanup(dtorKind));
1335
1336 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1337}
1338
1339/// pushDestroy - Push the standard destructor for the given type as
1340/// at least a normal cleanup.
John McCall9928c482011-07-12 16:41:08 +00001341void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
1342 llvm::Value *addr, QualType type) {
1343 assert(dtorKind && "cannot push destructor for trivial type");
1344
1345 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1346 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1347 cleanupKind & EHCleanup);
1348}
1349
John McCallbdc4d802011-07-09 01:37:26 +00001350void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *addr,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001351 QualType type, Destroyer *destroyer,
John McCall2673c682011-07-11 08:38:19 +00001352 bool useEHCleanupForArray) {
John McCall9928c482011-07-12 16:41:08 +00001353 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1354 destroyer, useEHCleanupForArray);
John McCallbdc4d802011-07-09 01:37:26 +00001355}
1356
Richard Smith8a07cd32013-06-12 20:42:33 +00001357void CodeGenFunction::pushLifetimeExtendedDestroy(
1358 CleanupKind cleanupKind, llvm::Value *addr, QualType type,
1359 Destroyer *destroyer, bool useEHCleanupForArray) {
1360 assert(!isInConditionalBranch() &&
1361 "performing lifetime extension from within conditional");
1362
1363 // Push an EH-only cleanup for the object now.
1364 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1365 // around in case a temporary's destructor throws an exception.
1366 if (cleanupKind & EHCleanup)
1367 EHStack.pushCleanup<DestroyObject>(
1368 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1369 destroyer, useEHCleanupForArray);
1370
1371 // Remember that we need to push a full cleanup for the object at the
1372 // end of the full-expression.
1373 pushCleanupAfterFullExpr<DestroyObject>(
1374 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1375}
1376
John McCall2673c682011-07-11 08:38:19 +00001377/// emitDestroy - Immediately perform the destruction of the given
1378/// object.
1379///
1380/// \param addr - the address of the object; a type*
1381/// \param type - the type of the object; if an array type, all
1382/// objects are destroyed in reverse order
1383/// \param destroyer - the function to call to destroy individual
1384/// elements
1385/// \param useEHCleanupForArray - whether an EH cleanup should be
1386/// used when destroying array elements, in case one of the
1387/// destructions throws an exception
John McCallbdc4d802011-07-09 01:37:26 +00001388void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001389 Destroyer *destroyer,
John McCall2673c682011-07-11 08:38:19 +00001390 bool useEHCleanupForArray) {
John McCallbdc4d802011-07-09 01:37:26 +00001391 const ArrayType *arrayType = getContext().getAsArrayType(type);
1392 if (!arrayType)
1393 return destroyer(*this, addr, type);
1394
1395 llvm::Value *begin = addr;
1396 llvm::Value *length = emitArrayLength(arrayType, type, begin);
John McCallfbf780a2011-07-13 08:09:46 +00001397
1398 // Normally we have to check whether the array is zero-length.
1399 bool checkZeroLength = true;
1400
1401 // But if the array length is constant, we can suppress that.
1402 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1403 // ...and if it's constant zero, we can just skip the entire thing.
1404 if (constLength->isZero()) return;
1405 checkZeroLength = false;
1406 }
1407
John McCallbdc4d802011-07-09 01:37:26 +00001408 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
John McCallfbf780a2011-07-13 08:09:46 +00001409 emitArrayDestroy(begin, end, type, destroyer,
1410 checkZeroLength, useEHCleanupForArray);
John McCallbdc4d802011-07-09 01:37:26 +00001411}
1412
John McCall2673c682011-07-11 08:38:19 +00001413/// emitArrayDestroy - Destroys all the elements of the given array,
1414/// beginning from last to first. The array cannot be zero-length.
1415///
1416/// \param begin - a type* denoting the first element of the array
1417/// \param end - a type* denoting one past the end of the array
1418/// \param type - the element type of the array
1419/// \param destroyer - the function to call to destroy elements
1420/// \param useEHCleanup - whether to push an EH cleanup to destroy
1421/// the remaining elements in case the destruction of a single
1422/// element throws
John McCallbdc4d802011-07-09 01:37:26 +00001423void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1424 llvm::Value *end,
1425 QualType type,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001426 Destroyer *destroyer,
John McCallfbf780a2011-07-13 08:09:46 +00001427 bool checkZeroLength,
John McCall2673c682011-07-11 08:38:19 +00001428 bool useEHCleanup) {
John McCallbdc4d802011-07-09 01:37:26 +00001429 assert(!type->isArrayType());
1430
1431 // The basic structure here is a do-while loop, because we don't
1432 // need to check for the zero-element case.
1433 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1434 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1435
John McCallfbf780a2011-07-13 08:09:46 +00001436 if (checkZeroLength) {
1437 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1438 "arraydestroy.isempty");
1439 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1440 }
1441
John McCallbdc4d802011-07-09 01:37:26 +00001442 // Enter the loop body, making that address the current address.
1443 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1444 EmitBlock(bodyBB);
1445 llvm::PHINode *elementPast =
1446 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1447 elementPast->addIncoming(end, entryBB);
1448
1449 // Shift the address back by one element.
1450 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1451 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1452 "arraydestroy.element");
1453
John McCall2673c682011-07-11 08:38:19 +00001454 if (useEHCleanup)
1455 pushRegularPartialArrayCleanup(begin, element, type, destroyer);
1456
John McCallbdc4d802011-07-09 01:37:26 +00001457 // Perform the actual destruction there.
1458 destroyer(*this, element, type);
1459
John McCall2673c682011-07-11 08:38:19 +00001460 if (useEHCleanup)
1461 PopCleanupBlock();
1462
John McCallbdc4d802011-07-09 01:37:26 +00001463 // Check whether we've reached the end.
1464 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1465 Builder.CreateCondBr(done, doneBB, bodyBB);
1466 elementPast->addIncoming(element, Builder.GetInsertBlock());
1467
1468 // Done.
1469 EmitBlock(doneBB);
1470}
1471
John McCall2673c682011-07-11 08:38:19 +00001472/// Perform partial array destruction as if in an EH cleanup. Unlike
1473/// emitArrayDestroy, the element type here may still be an array type.
John McCall2673c682011-07-11 08:38:19 +00001474static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1475 llvm::Value *begin, llvm::Value *end,
1476 QualType type,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001477 CodeGenFunction::Destroyer *destroyer) {
John McCall2673c682011-07-11 08:38:19 +00001478 // If the element type is itself an array, drill down.
John McCallfbf780a2011-07-13 08:09:46 +00001479 unsigned arrayDepth = 0;
John McCall2673c682011-07-11 08:38:19 +00001480 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1481 // VLAs don't require a GEP index to walk into.
1482 if (!isa<VariableArrayType>(arrayType))
John McCallfbf780a2011-07-13 08:09:46 +00001483 arrayDepth++;
John McCall2673c682011-07-11 08:38:19 +00001484 type = arrayType->getElementType();
1485 }
John McCallfbf780a2011-07-13 08:09:46 +00001486
1487 if (arrayDepth) {
1488 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, arrayDepth+1);
1489
Chris Lattner5f9e2722011-07-23 10:55:15 +00001490 SmallVector<llvm::Value*,4> gepIndices(arrayDepth, zero);
Jay Foad0f6ac7c2011-07-22 08:16:57 +00001491 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1492 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
John McCall2673c682011-07-11 08:38:19 +00001493 }
1494
John McCallfbf780a2011-07-13 08:09:46 +00001495 // Destroy the array. We don't ever need an EH cleanup because we
1496 // assume that we're in an EH cleanup ourselves, so a throwing
1497 // destructor causes an immediate terminate.
1498 CGF.emitArrayDestroy(begin, end, type, destroyer,
1499 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
John McCall2673c682011-07-11 08:38:19 +00001500}
1501
John McCallbdc4d802011-07-09 01:37:26 +00001502namespace {
John McCall2673c682011-07-11 08:38:19 +00001503 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1504 /// array destroy where the end pointer is regularly determined and
1505 /// does not need to be loaded from a local.
1506 class RegularPartialArrayDestroy : public EHScopeStack::Cleanup {
1507 llvm::Value *ArrayBegin;
1508 llvm::Value *ArrayEnd;
1509 QualType ElementType;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001510 CodeGenFunction::Destroyer *Destroyer;
John McCall2673c682011-07-11 08:38:19 +00001511 public:
1512 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
1513 QualType elementType,
1514 CodeGenFunction::Destroyer *destroyer)
1515 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001516 ElementType(elementType), Destroyer(destroyer) {}
John McCall2673c682011-07-11 08:38:19 +00001517
John McCallad346f42011-07-12 20:27:29 +00001518 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall2673c682011-07-11 08:38:19 +00001519 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
1520 ElementType, Destroyer);
1521 }
1522 };
1523
1524 /// IrregularPartialArrayDestroy - a cleanup which performs a
1525 /// partial array destroy where the end pointer is irregularly
1526 /// determined and must be loaded from a local.
1527 class IrregularPartialArrayDestroy : public EHScopeStack::Cleanup {
John McCallbdc4d802011-07-09 01:37:26 +00001528 llvm::Value *ArrayBegin;
1529 llvm::Value *ArrayEndPointer;
1530 QualType ElementType;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001531 CodeGenFunction::Destroyer *Destroyer;
John McCallbdc4d802011-07-09 01:37:26 +00001532 public:
John McCall2673c682011-07-11 08:38:19 +00001533 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
1534 llvm::Value *arrayEndPointer,
1535 QualType elementType,
1536 CodeGenFunction::Destroyer *destroyer)
John McCallbdc4d802011-07-09 01:37:26 +00001537 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001538 ElementType(elementType), Destroyer(destroyer) {}
John McCallbdc4d802011-07-09 01:37:26 +00001539
John McCallad346f42011-07-12 20:27:29 +00001540 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallbdc4d802011-07-09 01:37:26 +00001541 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
John McCall2673c682011-07-11 08:38:19 +00001542 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
1543 ElementType, Destroyer);
John McCallbdc4d802011-07-09 01:37:26 +00001544 }
1545 };
1546}
1547
John McCall2673c682011-07-11 08:38:19 +00001548/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
John McCallbdc4d802011-07-09 01:37:26 +00001549/// already-constructed elements of the given array. The cleanup
John McCall2673c682011-07-11 08:38:19 +00001550/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christophere1f54902011-08-23 22:38:00 +00001551///
John McCallbdc4d802011-07-09 01:37:26 +00001552/// \param elementType - the immediate element type of the array;
1553/// possibly still an array type
John McCall9928c482011-07-12 16:41:08 +00001554void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
John McCall2673c682011-07-11 08:38:19 +00001555 llvm::Value *arrayEndPointer,
1556 QualType elementType,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001557 Destroyer *destroyer) {
John McCall9928c482011-07-12 16:41:08 +00001558 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1559 arrayBegin, arrayEndPointer,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001560 elementType, destroyer);
John McCall2673c682011-07-11 08:38:19 +00001561}
1562
1563/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1564/// already-constructed elements of the given array. The cleanup
1565/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christophere1f54902011-08-23 22:38:00 +00001566///
John McCall2673c682011-07-11 08:38:19 +00001567/// \param elementType - the immediate element type of the array;
1568/// possibly still an array type
John McCall2673c682011-07-11 08:38:19 +00001569void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1570 llvm::Value *arrayEnd,
1571 QualType elementType,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001572 Destroyer *destroyer) {
John McCall9928c482011-07-12 16:41:08 +00001573 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
John McCall2673c682011-07-11 08:38:19 +00001574 arrayBegin, arrayEnd,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001575 elementType, destroyer);
John McCallbdc4d802011-07-09 01:37:26 +00001576}
1577
Nadav Rotem495cfa42013-03-23 06:43:35 +00001578/// Lazily declare the @llvm.lifetime.start intrinsic.
1579llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
1580 if (LifetimeStartFn) return LifetimeStartFn;
1581 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1582 llvm::Intrinsic::lifetime_start);
1583 return LifetimeStartFn;
1584}
1585
1586/// Lazily declare the @llvm.lifetime.end intrinsic.
1587llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
1588 if (LifetimeEndFn) return LifetimeEndFn;
1589 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1590 llvm::Intrinsic::lifetime_end);
1591 return LifetimeEndFn;
1592}
1593
John McCallf85e1932011-06-15 23:02:42 +00001594namespace {
1595 /// A cleanup to perform a release of an object at the end of a
1596 /// function. This is used to balance out the incoming +1 of a
1597 /// ns_consumed argument when we can't reasonably do that just by
1598 /// not doing the initial retain for a __block argument.
1599 struct ConsumeARCParameter : EHScopeStack::Cleanup {
John McCall5b07e802013-03-13 03:10:54 +00001600 ConsumeARCParameter(llvm::Value *param,
1601 ARCPreciseLifetime_t precise)
1602 : Param(param), Precise(precise) {}
John McCallf85e1932011-06-15 23:02:42 +00001603
1604 llvm::Value *Param;
John McCall5b07e802013-03-13 03:10:54 +00001605 ARCPreciseLifetime_t Precise;
John McCallf85e1932011-06-15 23:02:42 +00001606
John McCallad346f42011-07-12 20:27:29 +00001607 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall5b07e802013-03-13 03:10:54 +00001608 CGF.EmitARCRelease(Param, Precise);
John McCallf85e1932011-06-15 23:02:42 +00001609 }
1610 };
1611}
1612
Mike Stump1eb44332009-09-09 15:08:12 +00001613/// Emit an alloca (or GlobalValue depending on target)
Chris Lattner2621fd12008-05-08 05:58:21 +00001614/// for the specified parameter and set up LocalDeclMap.
Devang Patel093ac462011-03-03 20:13:15 +00001615void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
1616 unsigned ArgNo) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001617 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Gupta31fc07d2008-10-31 09:52:39 +00001618 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001619 "Invalid argument to EmitParmDecl");
John McCall8178df32011-02-22 22:38:33 +00001620
1621 Arg->setName(D.getName());
1622
Adrian Prantl836e7c92013-03-14 17:53:33 +00001623 QualType Ty = D.getType();
1624
John McCall8178df32011-02-22 22:38:33 +00001625 // Use better IR generation for certain implicit parameters.
1626 if (isa<ImplicitParamDecl>(D)) {
1627 // The only implicit argument a block has is its literal.
1628 if (BlockInfo) {
1629 LocalDeclMap[&D] = Arg;
Adrian Prantl836e7c92013-03-14 17:53:33 +00001630 llvm::Value *LocalAddr = 0;
1631 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
Adrian Prantl9b97adf2013-03-29 19:20:35 +00001632 // Allocate a stack slot to let the debug info survive the RA.
Adrian Prantl836e7c92013-03-14 17:53:33 +00001633 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1634 D.getName() + ".addr");
1635 Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity());
1636 LValue lv = MakeAddrLValue(Alloc, Ty, getContext().getDeclAlign(&D));
1637 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
1638 LocalAddr = Builder.CreateLoad(Alloc);
1639 }
John McCall8178df32011-02-22 22:38:33 +00001640
1641 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregor4cdad312012-10-23 20:05:01 +00001642 if (CGM.getCodeGenOpts().getDebugInfo()
1643 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001644 DI->setLocation(D.getLocation());
Adrian Prantl836e7c92013-03-14 17:53:33 +00001645 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, LocalAddr, Builder);
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001646 }
John McCall8178df32011-02-22 22:38:33 +00001647 }
1648
1649 return;
1650 }
1651 }
1652
Reid Spencer5f016e22007-07-11 17:01:13 +00001653 llvm::Value *DeclPtr;
Reid Kleckner9b601952013-06-21 12:45:15 +00001654 bool HasNonScalarEvalKind = !CodeGenFunction::hasScalarEvaluationKind(Ty);
Daniel Dunbare86bcf02010-02-08 22:53:07 +00001655 // If this is an aggregate or variable sized value, reuse the input pointer.
Reid Kleckner9b601952013-06-21 12:45:15 +00001656 if (HasNonScalarEvalKind || !Ty->isConstantSizeType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001657 DeclPtr = Arg;
Reid Kleckner9b601952013-06-21 12:45:15 +00001658 // Push a destructor cleanup for this parameter if the ABI requires it.
1659 if (HasNonScalarEvalKind &&
1660 getTarget().getCXXABI().isArgumentDestroyedByCallee()) {
1661 if (const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl()) {
1662 if (RD->hasNonTrivialDestructor())
1663 pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
1664 }
1665 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001666 } else {
Daniel Dunbare86bcf02010-02-08 22:53:07 +00001667 // Otherwise, create a temporary to hold the value.
Eli Friedmanddfb8d12011-11-03 20:31:28 +00001668 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1669 D.getName() + ".addr");
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001670 CharUnits Align = getContext().getDeclAlign(&D);
1671 Alloc->setAlignment(Align.getQuantity());
Eli Friedmanddfb8d12011-11-03 20:31:28 +00001672 DeclPtr = Alloc;
Mike Stump1eb44332009-09-09 15:08:12 +00001673
John McCallf85e1932011-06-15 23:02:42 +00001674 bool doStore = true;
1675
1676 Qualifiers qs = Ty.getQualifiers();
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001677 LValue lv = MakeAddrLValue(DeclPtr, Ty, Align);
John McCallf85e1932011-06-15 23:02:42 +00001678 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1679 // We honor __attribute__((ns_consumed)) for types with lifetime.
1680 // For __strong, it's handled by just skipping the initial retain;
1681 // otherwise we have to balance out the initial +1 with an extra
1682 // cleanup to do the release at the end of the function.
1683 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1684
1685 // 'self' is always formally __strong, but if this is not an
1686 // init method then we don't want to retain it.
John McCall7acddac2011-06-17 06:42:21 +00001687 if (D.isARCPseudoStrong()) {
John McCallf85e1932011-06-15 23:02:42 +00001688 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1689 assert(&D == method->getSelfDecl());
John McCall7acddac2011-06-17 06:42:21 +00001690 assert(lt == Qualifiers::OCL_Strong);
1691 assert(qs.hasConst());
John McCallf85e1932011-06-15 23:02:42 +00001692 assert(method->getMethodFamily() != OMF_init);
John McCall175d6592011-06-15 23:40:09 +00001693 (void) method;
John McCallf85e1932011-06-15 23:02:42 +00001694 lt = Qualifiers::OCL_ExplicitNone;
1695 }
1696
1697 if (lt == Qualifiers::OCL_Strong) {
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001698 if (!isConsumed) {
1699 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1700 // use objc_storeStrong(&dest, value) for retaining the
1701 // object. But first, store a null into 'dest' because
1702 // objc_storeStrong attempts to release its old value.
1703 llvm::Value * Null = CGM.EmitNullConstant(D.getType());
1704 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
1705 EmitARCStoreStrongCall(lv.getAddress(), Arg, true);
1706 doStore = false;
1707 }
1708 else
John McCallf85e1932011-06-15 23:02:42 +00001709 // Don't use objc_retainBlock for block pointers, because we
1710 // don't want to Block_copy something just because we got it
1711 // as a parameter.
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001712 Arg = EmitARCRetainNonBlock(Arg);
1713 }
John McCallf85e1932011-06-15 23:02:42 +00001714 } else {
1715 // Push the cleanup for a consumed parameter.
John McCall5b07e802013-03-13 03:10:54 +00001716 if (isConsumed) {
1717 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1718 ? ARCPreciseLifetime : ARCImpreciseLifetime);
1719 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg,
1720 precise);
1721 }
John McCallf85e1932011-06-15 23:02:42 +00001722
1723 if (lt == Qualifiers::OCL_Weak) {
1724 EmitARCInitWeak(DeclPtr, Arg);
Chad Rosier7acebfb2012-02-18 01:20:35 +00001725 doStore = false; // The weak init is a store, no need to do two.
John McCallf85e1932011-06-15 23:02:42 +00001726 }
1727 }
1728
1729 // Enter the cleanup scope.
1730 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1731 }
1732
Daniel Dunbare86bcf02010-02-08 22:53:07 +00001733 // Store the initial value into the alloca.
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001734 if (doStore)
David Chisnall7a7ee302012-01-16 17:27:18 +00001735 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001736 }
1737
1738 llvm::Value *&DMEntry = LocalDeclMap[&D];
1739 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
1740 DMEntry = DeclPtr;
Sanjiv Guptacc9b1632008-05-30 10:30:31 +00001741
1742 // Emit debug info for param declaration.
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001743 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregor4cdad312012-10-23 20:05:01 +00001744 if (CGM.getCodeGenOpts().getDebugInfo()
1745 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001746 DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
1747 }
1748 }
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001749
1750 if (D.hasAttr<AnnotateAttr>())
1751 EmitVarAnnotations(&D, DeclPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001752}