blob: 89407cd70c3d2e63315b501f51a75d7672327733 [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"
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -080015#include "CGBlocks.h"
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -070016#include "CGCleanup.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000017#include "CGDebugInfo.h"
Peter Collingbourne8c25fc52011-09-19 21:14:35 +000018#include "CGOpenCLRuntime.h"
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -070019#include "CGOpenMPRuntime.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "CodeGenModule.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000021#include "clang/AST/ASTContext.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000022#include "clang/AST/CharUnits.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000023#include "clang/AST/Decl.h"
Anders Carlsson19567ee2008-08-25 01:38:19 +000024#include "clang/AST/DeclObjC.h"
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -070025#include "clang/AST/DeclOpenMP.h"
Nate Begeman8bd4afe2008-04-19 04:17:09 +000026#include "clang/Basic/SourceManager.h"
Chris Lattner2621fd12008-05-08 05:58:21 +000027#include "clang/Basic/TargetInfo.h"
Mark Lacey8b549992013-10-30 21:53:58 +000028#include "clang/CodeGen/CGFunctionInfo.h"
Chandler Carruth06057ce2010-06-15 23:19:56 +000029#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000030#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/GlobalVariable.h"
32#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/Type.h"
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -070034
Reid Spencer5f016e22007-07-11 17:01:13 +000035using namespace clang;
36using namespace CodeGen;
37
Reid Spencer5f016e22007-07-11 17:01:13 +000038void CodeGenFunction::EmitDecl(const Decl &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +000039 switch (D.getKind()) {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -080040 case Decl::BuiltinTemplate:
Douglas Gregor08688ac2010-04-23 02:02:43 +000041 case Decl::TranslationUnit:
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -070042 case Decl::ExternCContext:
Douglas Gregor08688ac2010-04-23 02:02:43 +000043 case Decl::Namespace:
44 case Decl::UnresolvedUsingTypename:
45 case Decl::ClassTemplateSpecialization:
46 case Decl::ClassTemplatePartialSpecialization:
Larisse Voufoef4579c2013-08-06 01:03:05 +000047 case Decl::VarTemplateSpecialization:
48 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor08688ac2010-04-23 02:02:43 +000049 case Decl::TemplateTypeParm:
50 case Decl::UnresolvedUsingValue:
Sean Hunt9a555912010-05-30 07:21:58 +000051 case Decl::NonTypeTemplateParm:
Douglas Gregor08688ac2010-04-23 02:02:43 +000052 case Decl::CXXMethod:
53 case Decl::CXXConstructor:
54 case Decl::CXXDestructor:
55 case Decl::CXXConversion:
56 case Decl::Field:
John McCall76da55d2013-04-16 07:28:30 +000057 case Decl::MSProperty:
Francois Pichet41f5e662010-11-21 06:49:41 +000058 case Decl::IndirectField:
Douglas Gregor08688ac2010-04-23 02:02:43 +000059 case Decl::ObjCIvar:
Eric Christophere1f54902011-08-23 22:38:00 +000060 case Decl::ObjCAtDefsField:
Chris Lattneraa9fc462007-10-08 21:37:32 +000061 case Decl::ParmVar:
Douglas Gregor08688ac2010-04-23 02:02:43 +000062 case Decl::ImplicitParam:
63 case Decl::ClassTemplate:
Larisse Voufoef4579c2013-08-06 01:03:05 +000064 case Decl::VarTemplate:
Douglas Gregor08688ac2010-04-23 02:02:43 +000065 case Decl::FunctionTemplate:
Richard Smith3e4c6c42011-05-05 21:57:07 +000066 case Decl::TypeAliasTemplate:
Douglas Gregor08688ac2010-04-23 02:02:43 +000067 case Decl::TemplateTemplateParm:
68 case Decl::ObjCMethod:
69 case Decl::ObjCCategory:
70 case Decl::ObjCProtocol:
71 case Decl::ObjCInterface:
72 case Decl::ObjCCategoryImpl:
73 case Decl::ObjCImplementation:
74 case Decl::ObjCProperty:
75 case Decl::ObjCCompatibleAlias:
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -070076 case Decl::PragmaComment:
77 case Decl::PragmaDetectMismatch:
Abramo Bagnara6206d532010-06-05 05:09:32 +000078 case Decl::AccessSpec:
Douglas Gregor08688ac2010-04-23 02:02:43 +000079 case Decl::LinkageSpec:
80 case Decl::ObjCPropertyImpl:
Douglas Gregor08688ac2010-04-23 02:02:43 +000081 case Decl::FileScopeAsm:
82 case Decl::Friend:
83 case Decl::FriendTemplate:
84 case Decl::Block:
Tareq A. Siraj6afcf882013-04-16 19:37:38 +000085 case Decl::Captured:
Francois Pichetaf0f4d02011-08-14 03:52:19 +000086 case Decl::ClassScopeFunctionSpecialization:
David Blaikie9faebd22013-05-20 04:58:53 +000087 case Decl::UsingShadow:
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -070088 case Decl::ConstructorUsingShadow:
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -080089 case Decl::ObjCTypeParam:
David Blaikieb219cfc2011-09-23 05:06:16 +000090 llvm_unreachable("Declaration should not be in declstmts!");
Reid Spencer5f016e22007-07-11 17:01:13 +000091 case Decl::Function: // void X();
Argyrios Kyrtzidis35bc0822008-10-15 00:42:39 +000092 case Decl::Record: // struct/union/class X;
Reid Spencer5f016e22007-07-11 17:01:13 +000093 case Decl::Enum: // enum X;
Mike Stump1eb44332009-09-09 15:08:12 +000094 case Decl::EnumConstant: // enum ? { X = ? }
Argyrios Kyrtzidis35bc0822008-10-15 00:42:39 +000095 case Decl::CXXRecord: // struct/union/class X; [C++]
Anders Carlsson7b0ca3f2009-12-03 17:26:31 +000096 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
Chris Lattner4ae493c2011-02-18 02:08:43 +000097 case Decl::Label: // __label__ x;
Douglas Gregor15de72c2011-12-02 23:23:56 +000098 case Decl::Import:
Alexey Bataevc6400582013-03-22 06:34:35 +000099 case Decl::OMPThreadPrivate:
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700100 case Decl::OMPCapturedExpr:
Michael Han684aa732013-02-22 17:15:32 +0000101 case Decl::Empty:
Reid Spencer5f016e22007-07-11 17:01:13 +0000102 // None of these decls require codegen support.
103 return;
David Blaikiec8c24272013-02-02 00:39:32 +0000104
David Blaikiefc46ebc2013-05-20 22:50:41 +0000105 case Decl::NamespaceAlias:
106 if (CGDebugInfo *DI = getDebugInfo())
107 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
108 return;
David Blaikie9faebd22013-05-20 04:58:53 +0000109 case Decl::Using: // using X; [C++]
110 if (CGDebugInfo *DI = getDebugInfo())
111 DI->EmitUsingDecl(cast<UsingDecl>(D));
112 return;
David Blaikie957dac52013-04-22 06:13:21 +0000113 case Decl::UsingDirective: // using namespace X; [C++]
114 if (CGDebugInfo *DI = getDebugInfo())
115 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
116 return;
Daniel Dunbar662174c82008-08-29 17:28:43 +0000117 case Decl::Var: {
118 const VarDecl &VD = cast<VarDecl>(D);
John McCallb6bbcc92010-10-15 04:57:14 +0000119 assert(VD.isLocalVarDecl() &&
Daniel Dunbar662174c82008-08-29 17:28:43 +0000120 "Should not see file-scope variables inside a function!");
John McCallb6bbcc92010-10-15 04:57:14 +0000121 return EmitVarDecl(VD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000122 }
Mike Stump1eb44332009-09-09 15:08:12 +0000123
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700124 case Decl::OMPDeclareReduction:
125 return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
126
Richard Smith162e1c12011-04-15 14:24:37 +0000127 case Decl::Typedef: // typedef int X;
128 case Decl::TypeAlias: { // using X = int; [C++0x]
129 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000130 QualType Ty = TD.getUnderlyingType();
Mike Stump1eb44332009-09-09 15:08:12 +0000131
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000132 if (Ty->isVariablyModifiedType())
John McCallbc8d40d2011-06-24 21:55:10 +0000133 EmitVariablyModifiedType(Ty);
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000134 }
Daniel Dunbar662174c82008-08-29 17:28:43 +0000135 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000136}
137
John McCallb6bbcc92010-10-15 04:57:14 +0000138/// EmitVarDecl - This method handles emission of any variable declaration
Reid Spencer5f016e22007-07-11 17:01:13 +0000139/// inside a function, including static vars etc.
John McCallb6bbcc92010-10-15 04:57:14 +0000140void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Enea Zaffanella713e3f22013-05-16 11:27:56 +0000141 if (D.isStaticLocal()) {
Eric Christophere1f54902011-08-23 22:38:00 +0000142 llvm::GlobalValue::LinkageTypes Linkage =
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700143 CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000144
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700145 // FIXME: We need to force the emission/use of a guard variable for
146 // some variables even if we can constant-evaluate them because
147 // we can't guarantee every translation unit will constant-evaluate them.
Eric Christophere1f54902011-08-23 22:38:00 +0000148
John McCallb6bbcc92010-10-15 04:57:14 +0000149 return EmitStaticVarDecl(D, Linkage);
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000150 }
Enea Zaffanella713e3f22013-05-16 11:27:56 +0000151
152 if (D.hasExternalStorage())
Lauro Ramos Venanciofea90b82008-02-16 22:30:38 +0000153 // Don't emit it now, allow it to be emitted lazily on its first use.
154 return;
Daniel Dunbar5466c7b2009-04-14 02:25:56 +0000155
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800156 if (D.getType().getAddressSpace() == LangAS::opencl_local)
Enea Zaffanella713e3f22013-05-16 11:27:56 +0000157 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
158
159 assert(D.hasLocalStorage());
160 return EmitAutoVarDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000161}
162
Stephen Hines176edba2014-12-01 14:53:08 -0800163static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
164 if (CGM.getLangOpts().CPlusPlus)
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700165 return CGM.getMangledName(&D).str();
166
Stephen Hines176edba2014-12-01 14:53:08 -0800167 // If this isn't C++, we don't need a mangled name, just a pretty one.
168 assert(!D.isExternallyVisible() && "name shouldn't matter");
169 std::string ContextName;
170 const DeclContext *DC = D.getDeclContext();
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -0700171 if (auto *CD = dyn_cast<CapturedDecl>(DC))
172 DC = cast<DeclContext>(CD->getNonClosureContext());
Stephen Hines176edba2014-12-01 14:53:08 -0800173 if (const auto *FD = dyn_cast<FunctionDecl>(DC))
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700174 ContextName = CGM.getMangledName(FD);
Stephen Hines176edba2014-12-01 14:53:08 -0800175 else if (const auto *BD = dyn_cast<BlockDecl>(DC))
176 ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
177 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
178 ContextName = OMD->getSelector().getAsString();
Chris Lattner761acc12009-12-05 08:22:11 +0000179 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000180 llvm_unreachable("Unknown context for static var decl");
Eric Christophere1f54902011-08-23 22:38:00 +0000181
Stephen Hines176edba2014-12-01 14:53:08 -0800182 ContextName += "." + D.getNameAsString();
183 return ContextName;
Chris Lattner761acc12009-12-05 08:22:11 +0000184}
185
Stephen Hines176edba2014-12-01 14:53:08 -0800186llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
187 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
188 // In general, we don't always emit static var decls once before we reference
189 // them. It is possible to reference them before emitting the function that
190 // contains them, and it is possible to emit the containing function multiple
191 // times.
192 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
193 return ExistingGV;
194
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000195 QualType Ty = D.getType();
Eli Friedman3c2b3172008-02-15 12:20:59 +0000196 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000197
Benjamin Kramer5c247db2011-11-20 21:05:04 +0000198 // Use the label if the variable is renamed with the asm-label extension.
199 std::string Name;
Benjamin Kramerc3c8f222011-11-21 15:47:23 +0000200 if (D.hasAttr<AsmLabelAttr>())
Stephen Hines176edba2014-12-01 14:53:08 -0800201 Name = getMangledName(&D);
Benjamin Kramerc3c8f222011-11-21 15:47:23 +0000202 else
Stephen Hines176edba2014-12-01 14:53:08 -0800203 Name = getStaticDeclName(*this, D);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000204
Stephen Hines176edba2014-12-01 14:53:08 -0800205 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
Peter Collingbourne1aba7782012-08-28 20:37:10 +0000206 unsigned AddrSpace =
Stephen Hines176edba2014-12-01 14:53:08 -0800207 GetGlobalVarAddressSpace(&D, getContext().getTargetAddressSpace(Ty));
208
209 // Local address space cannot have an initializer.
210 llvm::Constant *Init = nullptr;
211 if (Ty.getAddressSpace() != LangAS::opencl_local)
212 Init = EmitNullConstant(Ty);
213 else
214 Init = llvm::UndefValue::get(LTy);
215
Anders Carlsson41f8a132009-09-26 18:16:06 +0000216 llvm::GlobalVariable *GV =
Stephen Hines176edba2014-12-01 14:53:08 -0800217 new llvm::GlobalVariable(getModule(), LTy,
Anders Carlsson41f8a132009-09-26 18:16:06 +0000218 Ty.isConstant(getContext()), Linkage,
Stephen Hines176edba2014-12-01 14:53:08 -0800219 Init, Name, nullptr,
Hans Wennborgde981f32012-06-28 08:01:44 +0000220 llvm::GlobalVariable::NotThreadLocal,
Peter Collingbourne1aba7782012-08-28 20:37:10 +0000221 AddrSpace);
Ken Dyck8b752f12010-01-27 17:10:57 +0000222 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Stephen Hines176edba2014-12-01 14:53:08 -0800223 setGlobalVisibility(GV, &D);
Hans Wennborgde981f32012-06-28 08:01:44 +0000224
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700225 if (supportsCOMDAT() && GV->isWeakForLinker())
226 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
227
Richard Smith38afbc72013-04-13 02:43:54 +0000228 if (D.getTLSKind())
Stephen Hines176edba2014-12-01 14:53:08 -0800229 setTLSMode(GV, D);
Hans Wennborgde981f32012-06-28 08:01:44 +0000230
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700231 if (D.isExternallyVisible()) {
232 if (D.hasAttr<DLLImportAttr>())
233 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
234 else if (D.hasAttr<DLLExportAttr>())
235 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
236 }
237
Stephen Hines651f13c2014-04-23 16:59:28 -0700238 // Make sure the result is of the correct type.
Stephen Hines176edba2014-12-01 14:53:08 -0800239 unsigned ExpectedAddrSpace = getContext().getTargetAddressSpace(Ty);
240 llvm::Constant *Addr = GV;
Stephen Hines651f13c2014-04-23 16:59:28 -0700241 if (AddrSpace != ExpectedAddrSpace) {
242 llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace);
Stephen Hines176edba2014-12-01 14:53:08 -0800243 Addr = llvm::ConstantExpr::getAddrSpaceCast(GV, PTy);
Stephen Hines651f13c2014-04-23 16:59:28 -0700244 }
245
Stephen Hines176edba2014-12-01 14:53:08 -0800246 setStaticLocalDeclAddress(&D, Addr);
247
248 // Ensure that the static local gets initialized by making sure the parent
249 // function gets emitted eventually.
250 const Decl *DC = cast<Decl>(D.getDeclContext());
251
252 // We can't name blocks or captured statements directly, so try to emit their
253 // parents.
254 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
255 DC = DC->getNonClosureContext();
256 // FIXME: Ensure that global blocks get emitted.
257 if (!DC)
258 return Addr;
259 }
260
261 GlobalDecl GD;
262 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
263 GD = GlobalDecl(CD, Ctor_Base);
264 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
265 GD = GlobalDecl(DD, Dtor_Base);
266 else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
267 GD = GlobalDecl(FD);
268 else {
269 // Don't do anything for Obj-C method decls or global closures. We should
270 // never defer them.
271 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
272 }
273 if (GD.getDecl())
274 (void)GetAddrOfGlobal(GD);
275
276 return Addr;
Daniel Dunbar0096acf2009-02-25 19:24:29 +0000277}
278
Richard Smith7ca48502012-02-13 22:16:19 +0000279/// hasNontrivialDestruction - Determine whether a type's destruction is
280/// non-trivial. If so, and the variable uses static initialization, we must
281/// register its destructor to run on exit.
282static bool hasNontrivialDestruction(QualType T) {
283 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
284 return RD && !RD->hasTrivialDestructor();
285}
286
Chandler Carruth0f30a122012-03-30 19:44:53 +0000287/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
288/// global variable that has already been created for it. If the initializer
289/// has a different type than GV does, this may free GV and return a different
290/// one. Otherwise it just returns GV.
291llvm::GlobalVariable *
John McCallb6bbcc92010-10-15 04:57:14 +0000292CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
Chandler Carruth0f30a122012-03-30 19:44:53 +0000293 llvm::GlobalVariable *GV) {
294 llvm::Constant *Init = CGM.EmitConstantInit(D, this);
John McCallbf40cb52010-07-15 23:40:35 +0000295
Chris Lattner761acc12009-12-05 08:22:11 +0000296 // If constant emission failed, then this should be a C++ static
297 // initializer.
Chandler Carruth0f30a122012-03-30 19:44:53 +0000298 if (!Init) {
Richard Smith7edf9e32012-11-01 22:30:59 +0000299 if (!getLangOpts().CPlusPlus)
Chris Lattner761acc12009-12-05 08:22:11 +0000300 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
John McCall5cd91b52010-09-08 01:44:27 +0000301 else if (Builder.GetInsertBlock()) {
Eric Christophere1f54902011-08-23 22:38:00 +0000302 // Since we have a static initializer, this global variable can't
Anders Carlsson071c8102010-01-26 04:02:23 +0000303 // be constant.
Chandler Carruth0f30a122012-03-30 19:44:53 +0000304 GV->setConstant(false);
John McCall5cd91b52010-09-08 01:44:27 +0000305
Chandler Carruth0f30a122012-03-30 19:44:53 +0000306 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
Anders Carlsson071c8102010-01-26 04:02:23 +0000307 }
Chandler Carruth0f30a122012-03-30 19:44:53 +0000308 return GV;
Chris Lattner761acc12009-12-05 08:22:11 +0000309 }
John McCallbf40cb52010-07-15 23:40:35 +0000310
Chris Lattner761acc12009-12-05 08:22:11 +0000311 // The initializer may differ in type from the global. Rewrite
312 // the global to match the initializer. (We have to do this
313 // because some types, like unions, can't be completely represented
314 // in the LLVM type system.)
Chandler Carruth0f30a122012-03-30 19:44:53 +0000315 if (GV->getType()->getElementType() != Init->getType()) {
316 llvm::GlobalVariable *OldGV = GV;
317
318 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
319 OldGV->isConstant(),
320 OldGV->getLinkage(), Init, "",
321 /*InsertBefore*/ OldGV,
Hans Wennborg5e2d5de2012-06-23 11:51:46 +0000322 OldGV->getThreadLocalMode(),
Chandler Carruth0f30a122012-03-30 19:44:53 +0000323 CGM.getContext().getTargetAddressSpace(D.getType()));
324 GV->setVisibility(OldGV->getVisibility());
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800325 GV->setComdat(OldGV->getComdat());
Eric Christophere1f54902011-08-23 22:38:00 +0000326
Chris Lattner761acc12009-12-05 08:22:11 +0000327 // Steal the name of the old global
Chandler Carruth0f30a122012-03-30 19:44:53 +0000328 GV->takeName(OldGV);
Eric Christophere1f54902011-08-23 22:38:00 +0000329
Chris Lattner761acc12009-12-05 08:22:11 +0000330 // Replace all uses of the old global with the new global
Chandler Carruth0f30a122012-03-30 19:44:53 +0000331 llvm::Constant *NewPtrForOldDecl =
332 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
333 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eric Christophere1f54902011-08-23 22:38:00 +0000334
Chris Lattner761acc12009-12-05 08:22:11 +0000335 // Erase the old global, since it is no longer used.
Chandler Carruth0f30a122012-03-30 19:44:53 +0000336 OldGV->eraseFromParent();
Chris Lattner761acc12009-12-05 08:22:11 +0000337 }
Eric Christophere1f54902011-08-23 22:38:00 +0000338
Chandler Carruth0f30a122012-03-30 19:44:53 +0000339 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
340 GV->setInitializer(Init);
Richard Smith7ca48502012-02-13 22:16:19 +0000341
342 if (hasNontrivialDestruction(D.getType())) {
343 // We have a constant initializer, but a nontrivial destructor. We still
344 // need to perform a guarded "initialization" in order to register the
Richard Smitha9b21d22012-02-17 06:48:11 +0000345 // destructor.
Chandler Carruth0f30a122012-03-30 19:44:53 +0000346 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
Richard Smith7ca48502012-02-13 22:16:19 +0000347 }
348
Chandler Carruth0f30a122012-03-30 19:44:53 +0000349 return GV;
Chris Lattner761acc12009-12-05 08:22:11 +0000350}
351
John McCallb6bbcc92010-10-15 04:57:14 +0000352void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000353 llvm::GlobalValue::LinkageTypes Linkage) {
John McCall355bba72012-03-30 21:00:39 +0000354 // Check to see if we already have a global variable for this
355 // declaration. This can happen when double-emitting function
356 // bodies, e.g. with complete and base constructors.
Stephen Hines176edba2014-12-01 14:53:08 -0800357 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800358 CharUnits alignment = getContext().getDeclAlign(&D);
Daniel Dunbara985b312009-02-25 19:45:19 +0000359
Daniel Dunbare5731f82009-02-25 20:08:33 +0000360 // Store into LocalDeclMap before generating initializer to handle
361 // circular references.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800362 setAddrOfLocalVar(&D, Address(addr, alignment));
Daniel Dunbare5731f82009-02-25 20:08:33 +0000363
John McCallfe67f3b2010-05-04 20:45:42 +0000364 // We can't have a VLA here, but we can have a pointer to a VLA,
365 // even though that doesn't really make any sense.
Eli Friedmanc62aad82009-04-20 03:54:15 +0000366 // Make sure to evaluate VLA bounds now so that we have them for later.
367 if (D.getType()->isVariablyModifiedType())
John McCallbc8d40d2011-06-24 21:55:10 +0000368 EmitVariablyModifiedType(D.getType());
Eric Christophere1f54902011-08-23 22:38:00 +0000369
John McCall355bba72012-03-30 21:00:39 +0000370 // Save the type in case adding the initializer forces a type change.
371 llvm::Type *expectedType = addr->getType();
Eli Friedmanc62aad82009-04-20 03:54:15 +0000372
Stephen Hines651f13c2014-04-23 16:59:28 -0700373 llvm::GlobalVariable *var =
374 cast<llvm::GlobalVariable>(addr->stripPointerCasts());
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700375
376 // CUDA's local and local static __shared__ variables should not
377 // have any non-empty initializers. This is ensured by Sema.
378 // Whatever initializer such variable may have when it gets here is
379 // a no-op and should not be emitted.
380 bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
381 D.hasAttr<CUDASharedAttr>();
Chris Lattner761acc12009-12-05 08:22:11 +0000382 // If this value has an initializer, emit it.
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700383 if (D.getInit() && !isCudaSharedVar)
John McCall355bba72012-03-30 21:00:39 +0000384 var = AddInitializerToStaticVarDecl(D, var);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000385
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800386 var->setAlignment(alignment.getQuantity());
Chris Lattner0af95232010-03-10 23:59:59 +0000387
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000388 if (D.hasAttr<AnnotateAttr>())
John McCall355bba72012-03-30 21:00:39 +0000389 CGM.AddGlobalAnnotations(&D, var);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000390
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000391 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
John McCall355bba72012-03-30 21:00:39 +0000392 var->setSection(SA->getName());
Mike Stump1eb44332009-09-09 15:08:12 +0000393
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000394 if (D.hasAttr<UsedAttr>())
Stephen Hines651f13c2014-04-23 16:59:28 -0700395 CGM.addUsedGlobal(var);
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000396
Chandler Carruth0f30a122012-03-30 19:44:53 +0000397 // We may have to cast the constant because of the initializer
398 // mismatch above.
399 //
400 // FIXME: It is really dangerous to store this in the map; if anyone
401 // RAUW's the GV uses of this constant will be invalid.
Stephen Hines651f13c2014-04-23 16:59:28 -0700402 llvm::Constant *castedAddr =
403 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800404 if (var != castedAddr)
405 LocalDeclMap.find(&D)->second = Address(castedAddr, alignment);
John McCall355bba72012-03-30 21:00:39 +0000406 CGM.setStaticLocalDeclAddress(&D, castedAddr);
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000407
Stephen Hines176edba2014-12-01 14:53:08 -0800408 CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700409
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000410 // Emit global variable debug descriptor for static vars.
Anders Carlssone896d982009-02-13 08:11:52 +0000411 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonovfd00eec2012-05-04 07:39:27 +0000412 if (DI &&
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700413 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000414 DI->setLocation(D.getLocation());
John McCall355bba72012-03-30 21:00:39 +0000415 DI->EmitGlobalVariable(var, &D);
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000416 }
Anders Carlsson1a86b332007-10-17 00:52:43 +0000417}
Mike Stump1eb44332009-09-09 15:08:12 +0000418
John McCallda65ea82010-07-13 20:32:21 +0000419namespace {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800420 struct DestroyObject final : EHScopeStack::Cleanup {
421 DestroyObject(Address addr, QualType type,
John McCall2673c682011-07-11 08:38:19 +0000422 CodeGenFunction::Destroyer *destroyer,
423 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000424 : addr(addr), type(type), destroyer(destroyer),
John McCall2673c682011-07-11 08:38:19 +0000425 useEHCleanupForArray(useEHCleanupForArray) {}
John McCallda65ea82010-07-13 20:32:21 +0000426
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800427 Address addr;
John McCallbdc4d802011-07-09 01:37:26 +0000428 QualType type;
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000429 CodeGenFunction::Destroyer *destroyer;
John McCall2673c682011-07-11 08:38:19 +0000430 bool useEHCleanupForArray;
John McCallda65ea82010-07-13 20:32:21 +0000431
Stephen Hines651f13c2014-04-23 16:59:28 -0700432 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall2673c682011-07-11 08:38:19 +0000433 // Don't use an EH cleanup recursively from an EH cleanup.
John McCallad346f42011-07-12 20:27:29 +0000434 bool useEHCleanupForArray =
435 flags.isForNormalCleanup() && this->useEHCleanupForArray;
John McCall2673c682011-07-11 08:38:19 +0000436
437 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
John McCallda65ea82010-07-13 20:32:21 +0000438 }
439 };
440
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800441 struct DestroyNRVOVariable final : EHScopeStack::Cleanup {
442 DestroyNRVOVariable(Address addr,
John McCallbdc4d802011-07-09 01:37:26 +0000443 const CXXDestructorDecl *Dtor,
444 llvm::Value *NRVOFlag)
445 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
John McCallda65ea82010-07-13 20:32:21 +0000446
447 const CXXDestructorDecl *Dtor;
448 llvm::Value *NRVOFlag;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800449 Address Loc;
John McCallda65ea82010-07-13 20:32:21 +0000450
Stephen Hines651f13c2014-04-23 16:59:28 -0700451 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallda65ea82010-07-13 20:32:21 +0000452 // Along the exceptions path we always execute the dtor.
John McCallad346f42011-07-12 20:27:29 +0000453 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
John McCallda65ea82010-07-13 20:32:21 +0000454
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700455 llvm::BasicBlock *SkipDtorBB = nullptr;
John McCallda65ea82010-07-13 20:32:21 +0000456 if (NRVO) {
457 // If we exited via NRVO, we skip the destructor call.
458 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
459 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800460 llvm::Value *DidNRVO =
461 CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
John McCallda65ea82010-07-13 20:32:21 +0000462 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
463 CGF.EmitBlock(RunDtorBB);
464 }
Eric Christophere1f54902011-08-23 22:38:00 +0000465
John McCallda65ea82010-07-13 20:32:21 +0000466 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor378e1e72013-01-31 05:50:40 +0000467 /*ForVirtualBase=*/false,
468 /*Delegating=*/false,
469 Loc);
John McCallda65ea82010-07-13 20:32:21 +0000470
471 if (NRVO) CGF.EmitBlock(SkipDtorBB);
472 }
473 };
John McCallda65ea82010-07-13 20:32:21 +0000474
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800475 struct CallStackRestore final : EHScopeStack::Cleanup {
476 Address Stack;
477 CallStackRestore(Address Stack) : Stack(Stack) {}
Stephen Hines651f13c2014-04-23 16:59:28 -0700478 void Emit(CodeGenFunction &CGF, Flags flags) override {
Benjamin Kramer578faa82011-09-27 21:06:10 +0000479 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
John McCalld8715092010-07-21 06:13:08 +0000480 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
481 CGF.Builder.CreateCall(F, V);
482 }
483 };
484
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800485 struct ExtendGCLifetime final : EHScopeStack::Cleanup {
John McCall0c24c802011-06-24 23:21:27 +0000486 const VarDecl &Var;
487 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
488
Stephen Hines651f13c2014-04-23 16:59:28 -0700489 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall0c24c802011-06-24 23:21:27 +0000490 // Compute the address of the local variable, in case it's a
491 // byref or something.
John McCallf4b88a42012-03-10 09:33:50 +0000492 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
493 Var.getType(), VK_LValue, SourceLocation());
Nick Lewycky4ee7dc22013-10-02 02:29:49 +0000494 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
495 SourceLocation());
John McCall0c24c802011-06-24 23:21:27 +0000496 CGF.EmitExtendGCLifetime(value);
497 }
498 };
499
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800500 struct CallCleanupFunction final : EHScopeStack::Cleanup {
John McCalld8715092010-07-21 06:13:08 +0000501 llvm::Constant *CleanupFn;
502 const CGFunctionInfo &FnInfo;
John McCalld8715092010-07-21 06:13:08 +0000503 const VarDecl &Var;
Eric Christophere1f54902011-08-23 22:38:00 +0000504
John McCalld8715092010-07-21 06:13:08 +0000505 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCall34695852011-02-22 06:44:22 +0000506 const VarDecl *Var)
507 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalld8715092010-07-21 06:13:08 +0000508
Stephen Hines651f13c2014-04-23 16:59:28 -0700509 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf4b88a42012-03-10 09:33:50 +0000510 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
511 Var.getType(), VK_LValue, SourceLocation());
John McCall34695852011-02-22 06:44:22 +0000512 // Compute the address of the local variable, in case it's a byref
513 // or something.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800514 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer();
John McCall34695852011-02-22 06:44:22 +0000515
John McCalld8715092010-07-21 06:13:08 +0000516 // In some cases, the type of the function argument will be different from
517 // the type of the pointer. An example of this is
518 // void f(void* arg);
519 // __attribute__((cleanup(f))) void *g;
520 //
521 // To fix this we insert a bitcast here.
522 QualType ArgTy = FnInfo.arg_begin()->type;
523 llvm::Value *Arg =
524 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
525
526 CallArgList Args;
Eli Friedman04c9a492011-05-02 17:57:46 +0000527 Args.add(RValue::get(Arg),
528 CGF.getContext().getPointerType(Var.getType()));
John McCalld8715092010-07-21 06:13:08 +0000529 CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
530 }
531 };
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700532} // end anonymous namespace
John McCalld8715092010-07-21 06:13:08 +0000533
John McCallf85e1932011-06-15 23:02:42 +0000534/// EmitAutoVarWithLifetime - Does the setup required for an automatic
535/// variable with lifetime.
536static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800537 Address addr,
John McCallf85e1932011-06-15 23:02:42 +0000538 Qualifiers::ObjCLifetime lifetime) {
539 switch (lifetime) {
540 case Qualifiers::OCL_None:
541 llvm_unreachable("present but none");
542
543 case Qualifiers::OCL_ExplicitNone:
544 // nothing to do
545 break;
546
547 case Qualifiers::OCL_Strong: {
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000548 CodeGenFunction::Destroyer *destroyer =
John McCall9928c482011-07-12 16:41:08 +0000549 (var.hasAttr<ObjCPreciseLifetimeAttr>()
550 ? CodeGenFunction::destroyARCStrongPrecise
551 : CodeGenFunction::destroyARCStrongImprecise);
552
553 CleanupKind cleanupKind = CGF.getARCCleanupKind();
554 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
555 cleanupKind & EHCleanup);
John McCallf85e1932011-06-15 23:02:42 +0000556 break;
557 }
558 case Qualifiers::OCL_Autoreleasing:
559 // nothing to do
560 break;
Eric Christophere1f54902011-08-23 22:38:00 +0000561
John McCallf85e1932011-06-15 23:02:42 +0000562 case Qualifiers::OCL_Weak:
563 // __weak objects always get EH cleanups; otherwise, exceptions
564 // could cause really nasty crashes instead of mere leaks.
John McCall9928c482011-07-12 16:41:08 +0000565 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
566 CodeGenFunction::destroyARCWeak,
567 /*useEHCleanup*/ true);
John McCallf85e1932011-06-15 23:02:42 +0000568 break;
569 }
570}
571
572static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
573 if (const Expr *e = dyn_cast<Expr>(s)) {
574 // Skip the most common kinds of expressions that make
575 // hierarchy-walking expensive.
576 s = e = e->IgnoreParenCasts();
577
578 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
579 return (ref->getDecl() == &var);
Fariborz Jahanianddfc8a12012-06-19 20:53:26 +0000580 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
581 const BlockDecl *block = be->getBlockDecl();
Stephen Hines651f13c2014-04-23 16:59:28 -0700582 for (const auto &I : block->captures()) {
583 if (I.getVariable() == &var)
Fariborz Jahanianddfc8a12012-06-19 20:53:26 +0000584 return true;
585 }
586 }
John McCallf85e1932011-06-15 23:02:42 +0000587 }
588
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800589 for (const Stmt *SubStmt : s->children())
590 // SubStmt might be null; as in missing decl or conditional of an if-stmt.
591 if (SubStmt && isAccessedBy(var, SubStmt))
John McCallf85e1932011-06-15 23:02:42 +0000592 return true;
593
594 return false;
595}
596
597static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
598 if (!decl) return false;
599 if (!isa<VarDecl>(decl)) return false;
600 const VarDecl *var = cast<VarDecl>(decl);
601 return isAccessedBy(*var, e);
602}
603
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800604static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
605 const LValue &destLV, const Expr *init) {
606 bool needsCast = false;
607
608 while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
609 switch (castExpr->getCastKind()) {
610 // Look through casts that don't require representation changes.
611 case CK_NoOp:
612 case CK_BitCast:
613 case CK_BlockPointerToObjCPointerCast:
614 needsCast = true;
615 break;
616
617 // If we find an l-value to r-value cast from a __weak variable,
618 // emit this operation as a copy or move.
619 case CK_LValueToRValue: {
620 const Expr *srcExpr = castExpr->getSubExpr();
621 if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
622 return false;
623
624 // Emit the source l-value.
625 LValue srcLV = CGF.EmitLValue(srcExpr);
626
627 // Handle a formal type change to avoid asserting.
628 auto srcAddr = srcLV.getAddress();
629 if (needsCast) {
630 srcAddr = CGF.Builder.CreateElementBitCast(srcAddr,
631 destLV.getAddress().getElementType());
632 }
633
634 // If it was an l-value, use objc_copyWeak.
635 if (srcExpr->getValueKind() == VK_LValue) {
636 CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr);
637 } else {
638 assert(srcExpr->getValueKind() == VK_XValue);
639 CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr);
640 }
641 return true;
642 }
643
644 // Stop at anything else.
645 default:
646 return false;
647 }
648
649 init = castExpr->getSubExpr();
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800650 }
651 return false;
652}
653
John McCalla07398e2011-06-16 04:16:24 +0000654static void drillIntoBlockVariable(CodeGenFunction &CGF,
655 LValue &lvalue,
656 const VarDecl *var) {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800657 lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var));
John McCalla07398e2011-06-16 04:16:24 +0000658}
659
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700660void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
661 LValue lvalue, bool capturedByInit) {
John McCalla07398e2011-06-16 04:16:24 +0000662 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
John McCallf85e1932011-06-15 23:02:42 +0000663 if (!lifetime) {
664 llvm::Value *value = EmitScalarExpr(init);
John McCalla07398e2011-06-16 04:16:24 +0000665 if (capturedByInit)
666 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Chisnall7a7ee302012-01-16 17:27:18 +0000667 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
John McCallf85e1932011-06-15 23:02:42 +0000668 return;
669 }
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700670
Stephen Hines651f13c2014-04-23 16:59:28 -0700671 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
672 init = DIE->getExpr();
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700673
John McCallf85e1932011-06-15 23:02:42 +0000674 // If we're emitting a value with lifetime, we have to do the
675 // initialization *before* we leave the cleanup scopes.
John McCall1a343eb2011-11-10 08:15:53 +0000676 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
677 enterFullExpression(ewc);
John McCallf85e1932011-06-15 23:02:42 +0000678 init = ewc->getSubExpr();
John McCall1a343eb2011-11-10 08:15:53 +0000679 }
680 CodeGenFunction::RunCleanupsScope Scope(*this);
John McCallf85e1932011-06-15 23:02:42 +0000681
682 // We have to maintain the illusion that the variable is
683 // zero-initialized. If the variable might be accessed in its
684 // initializer, zero-initialize before running the initializer, then
685 // actually perform the initialization with an assign.
686 bool accessedByInit = false;
687 if (lifetime != Qualifiers::OCL_ExplicitNone)
John McCallfb720812011-07-28 07:23:35 +0000688 accessedByInit = (capturedByInit || isAccessedBy(D, init));
John McCallf85e1932011-06-15 23:02:42 +0000689 if (accessedByInit) {
John McCalla07398e2011-06-16 04:16:24 +0000690 LValue tempLV = lvalue;
John McCallf85e1932011-06-15 23:02:42 +0000691 // Drill down to the __block object if necessary.
John McCallf85e1932011-06-15 23:02:42 +0000692 if (capturedByInit) {
693 // We can use a simple GEP for this because it can't have been
694 // moved yet.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800695 tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(),
696 cast<VarDecl>(D),
697 /*follow*/ false));
John McCallf85e1932011-06-15 23:02:42 +0000698 }
699
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800700 auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType());
John McCallf85e1932011-06-15 23:02:42 +0000701 llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
Eric Christophere1f54902011-08-23 22:38:00 +0000702
John McCallf85e1932011-06-15 23:02:42 +0000703 // If __weak, we want to use a barrier under certain conditions.
704 if (lifetime == Qualifiers::OCL_Weak)
John McCalla07398e2011-06-16 04:16:24 +0000705 EmitARCInitWeak(tempLV.getAddress(), zero);
John McCallf85e1932011-06-15 23:02:42 +0000706
707 // Otherwise just do a simple store.
708 else
David Chisnall7a7ee302012-01-16 17:27:18 +0000709 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
John McCallf85e1932011-06-15 23:02:42 +0000710 }
711
712 // Emit the initializer.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700713 llvm::Value *value = nullptr;
John McCallf85e1932011-06-15 23:02:42 +0000714
715 switch (lifetime) {
716 case Qualifiers::OCL_None:
717 llvm_unreachable("present but none");
718
719 case Qualifiers::OCL_ExplicitNone:
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700720 value = EmitARCUnsafeUnretainedScalarExpr(init);
John McCallf85e1932011-06-15 23:02:42 +0000721 break;
722
723 case Qualifiers::OCL_Strong: {
724 value = EmitARCRetainScalarExpr(init);
725 break;
726 }
727
728 case Qualifiers::OCL_Weak: {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800729 // If it's not accessed by the initializer, try to emit the
730 // initialization with a copy or move.
731 if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
732 return;
733 }
734
John McCallf85e1932011-06-15 23:02:42 +0000735 // No way to optimize a producing initializer into this. It's not
736 // worth optimizing for, because the value will immediately
737 // disappear in the common case.
738 value = EmitScalarExpr(init);
739
John McCalla07398e2011-06-16 04:16:24 +0000740 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCallf85e1932011-06-15 23:02:42 +0000741 if (accessedByInit)
John McCalla07398e2011-06-16 04:16:24 +0000742 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
John McCallf85e1932011-06-15 23:02:42 +0000743 else
John McCalla07398e2011-06-16 04:16:24 +0000744 EmitARCInitWeak(lvalue.getAddress(), value);
John McCallf85e1932011-06-15 23:02:42 +0000745 return;
746 }
747
748 case Qualifiers::OCL_Autoreleasing:
749 value = EmitARCRetainAutoreleaseScalarExpr(init);
750 break;
751 }
752
John McCalla07398e2011-06-16 04:16:24 +0000753 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCallf85e1932011-06-15 23:02:42 +0000754
755 // If the variable might have been accessed by its initializer, we
756 // might have to initialize with a barrier. We have to do this for
757 // both __weak and __strong, but __weak got filtered out above.
758 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
Nick Lewycky4ee7dc22013-10-02 02:29:49 +0000759 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
David Chisnall7a7ee302012-01-16 17:27:18 +0000760 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCall5b07e802013-03-13 03:10:54 +0000761 EmitARCRelease(oldValue, ARCImpreciseLifetime);
John McCallf85e1932011-06-15 23:02:42 +0000762 return;
763 }
764
David Chisnall7a7ee302012-01-16 17:27:18 +0000765 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCallf85e1932011-06-15 23:02:42 +0000766}
Chris Lattner94cd0112010-12-01 02:05:19 +0000767
John McCall7acddac2011-06-17 06:42:21 +0000768/// EmitScalarInit - Initialize the given lvalue with the given object.
769void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
770 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
771 if (!lifetime)
David Chisnall7a7ee302012-01-16 17:27:18 +0000772 return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
John McCall7acddac2011-06-17 06:42:21 +0000773
774 switch (lifetime) {
775 case Qualifiers::OCL_None:
776 llvm_unreachable("present but none");
777
778 case Qualifiers::OCL_ExplicitNone:
779 // nothing to do
780 break;
781
782 case Qualifiers::OCL_Strong:
783 init = EmitARCRetain(lvalue.getType(), init);
784 break;
785
786 case Qualifiers::OCL_Weak:
787 // Initialize and then skip the primitive store.
788 EmitARCInitWeak(lvalue.getAddress(), init);
789 return;
790
791 case Qualifiers::OCL_Autoreleasing:
792 init = EmitARCRetainAutorelease(lvalue.getType(), init);
793 break;
794 }
795
David Chisnall7a7ee302012-01-16 17:27:18 +0000796 EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
John McCall7acddac2011-06-17 06:42:21 +0000797}
798
Chris Lattner94cd0112010-12-01 02:05:19 +0000799/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
800/// non-zero parts of the specified initializer with equal or fewer than
801/// NumStores scalar stores.
802static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
803 unsigned &NumStores) {
Chris Lattner70b02942010-12-02 01:58:41 +0000804 // Zero and Undef never requires any extra stores.
805 if (isa<llvm::ConstantAggregateZero>(Init) ||
806 isa<llvm::ConstantPointerNull>(Init) ||
807 isa<llvm::UndefValue>(Init))
808 return true;
809 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
810 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
811 isa<llvm::ConstantExpr>(Init))
812 return Init->isNullValue() || NumStores--;
813
814 // See if we can emit each element.
815 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
816 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
817 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
818 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
819 return false;
820 }
821 return true;
822 }
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700823
Chris Lattnerf492cb12012-01-31 04:36:19 +0000824 if (llvm::ConstantDataSequential *CDS =
825 dyn_cast<llvm::ConstantDataSequential>(Init)) {
826 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
827 llvm::Constant *Elt = CDS->getElementAsConstant(i);
828 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
829 return false;
830 }
831 return true;
832 }
Eric Christophere1f54902011-08-23 22:38:00 +0000833
Chris Lattner94cd0112010-12-01 02:05:19 +0000834 // Anything else is hard and scary.
835 return false;
836}
837
838/// emitStoresForInitAfterMemset - For inits that
839/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
840/// stores that would be required.
841static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
John McCall34695852011-02-22 06:44:22 +0000842 bool isVolatile, CGBuilderTy &Builder) {
Benjamin Kramer06d43682012-08-27 22:07:02 +0000843 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
844 "called emitStoresForInitAfterMemset for zero or undef value.");
Eric Christophere1f54902011-08-23 22:38:00 +0000845
Chris Lattner70b02942010-12-02 01:58:41 +0000846 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
847 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
848 isa<llvm::ConstantExpr>(Init)) {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800849 Builder.CreateDefaultAlignedStore(Init, Loc, isVolatile);
Chris Lattnerf492cb12012-01-31 04:36:19 +0000850 return;
851 }
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700852
853 if (llvm::ConstantDataSequential *CDS =
854 dyn_cast<llvm::ConstantDataSequential>(Init)) {
Chris Lattnerf492cb12012-01-31 04:36:19 +0000855 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
856 llvm::Constant *Elt = CDS->getElementAsConstant(i);
Benjamin Kramercfa07e32012-08-27 21:35:58 +0000857
858 // If necessary, get a pointer to the element and emit it.
859 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -0700860 emitStoresForInitAfterMemset(
861 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
862 isVolatile, Builder);
Chris Lattnerf492cb12012-01-31 04:36:19 +0000863 }
Chris Lattner70b02942010-12-02 01:58:41 +0000864 return;
865 }
Eric Christophere1f54902011-08-23 22:38:00 +0000866
Chris Lattner70b02942010-12-02 01:58:41 +0000867 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
868 "Unknown value type!");
Eric Christophere1f54902011-08-23 22:38:00 +0000869
Chris Lattner70b02942010-12-02 01:58:41 +0000870 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
871 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
Benjamin Kramercfa07e32012-08-27 21:35:58 +0000872
873 // If necessary, get a pointer to the element and emit it.
874 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -0700875 emitStoresForInitAfterMemset(
876 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
877 isVolatile, Builder);
Chris Lattner70b02942010-12-02 01:58:41 +0000878 }
Chris Lattner94cd0112010-12-01 02:05:19 +0000879}
880
Chris Lattner94cd0112010-12-01 02:05:19 +0000881/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
882/// plus some stores to initialize a local variable instead of using a memcpy
883/// from a constant global. It is beneficial to use memset if the global is all
884/// zeros, or mostly zeros and large.
885static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
886 uint64_t GlobalSize) {
887 // If a global is all zeros, always use a memset.
888 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
889
Chris Lattner94cd0112010-12-01 02:05:19 +0000890 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
891 // do it if it will require 6 or fewer scalar stores.
892 // TODO: Should budget depends on the size? Avoiding a large global warrants
893 // plopping in more stores.
894 unsigned StoreBudget = 6;
895 uint64_t SizeLimit = 32;
Eric Christophere1f54902011-08-23 22:38:00 +0000896
897 return GlobalSize > SizeLimit &&
Chris Lattner94cd0112010-12-01 02:05:19 +0000898 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
899}
900
Nick Lewyckya9de3fa2010-12-30 20:21:55 +0000901/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Reid Spencer5f016e22007-07-11 17:01:13 +0000902/// variable declaration with auto, register, or no storage class specifier.
Chris Lattner2621fd12008-05-08 05:58:21 +0000903/// These turn into simple stack objects, or GlobalValues depending on target.
John McCall34695852011-02-22 06:44:22 +0000904void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
905 AutoVarEmission emission = EmitAutoVarAlloca(D);
906 EmitAutoVarInit(emission);
907 EmitAutoVarCleanups(emission);
908}
Reid Spencer5f016e22007-07-11 17:01:13 +0000909
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700910/// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time
911/// markers.
912static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts,
913 const LangOptions &LangOpts) {
914 // Asan uses markers for use-after-scope checks.
915 if (CGOpts.SanitizeAddressUseAfterScope)
916 return true;
917
918 // Disable lifetime markers in msan builds.
919 // FIXME: Remove this when msan works with lifetime markers.
920 if (LangOpts.Sanitize.has(SanitizerKind::Memory))
921 return false;
922
923 // For now, only in optimized builds.
924 return CGOpts.OptimizationLevel != 0;
925}
926
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -0700927/// Emit a lifetime.begin marker if some criteria are satisfied.
928/// \return a pointer to the temporary size Value if a marker was emitted, null
929/// otherwise
930llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
931 llvm::Value *Addr) {
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700932 if (!shouldEmitLifetimeMarkers(CGM.getCodeGenOpts(), getLangOpts()))
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -0700933 return nullptr;
934
935 llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
936 Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
937 llvm::CallInst *C =
938 Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
939 C->setDoesNotThrow();
940 return SizeV;
941}
942
943void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
944 Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
945 llvm::CallInst *C =
946 Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
947 C->setDoesNotThrow();
948}
949
John McCall34695852011-02-22 06:44:22 +0000950/// EmitAutoVarAlloca - Emit the alloca and debug information for a
Stephen Hines651f13c2014-04-23 16:59:28 -0700951/// local variable. Does not emit initialization or destruction.
John McCall34695852011-02-22 06:44:22 +0000952CodeGenFunction::AutoVarEmission
953CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
954 QualType Ty = D.getType();
955
956 AutoVarEmission emission(D);
957
958 bool isByRef = D.hasAttr<BlocksAttr>();
959 emission.IsByRef = isByRef;
960
961 CharUnits alignment = getContext().getDeclAlign(&D);
John McCall34695852011-02-22 06:44:22 +0000962
John McCallbc8d40d2011-06-24 21:55:10 +0000963 // If the type is variably-modified, emit all the VLA sizes for it.
964 if (Ty->isVariablyModifiedType())
965 EmitVariablyModifiedType(Ty);
966
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800967 Address address = Address::invalid();
Eli Friedman3c2b3172008-02-15 12:20:59 +0000968 if (Ty->isConstantSizeType()) {
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000969 bool NRVO = getLangOpts().ElideConstructors &&
970 D.isNRVOVariable();
John McCall34695852011-02-22 06:44:22 +0000971
Richard Smithe67ca582013-06-02 00:09:52 +0000972 // If this value is an array or struct with a statically determinable
973 // constant initializer, there are optimizations we can do.
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000974 //
975 // TODO: We should constant-evaluate the initializer of any variable,
976 // as long as it is initialized by a constant expression. Currently,
977 // isConstantInitializer produces wrong answers for structs with
978 // reference or bitfield members, and a few other cases, and checking
979 // for POD-ness protects us from some of these.
Richard Smithe67ca582013-06-02 00:09:52 +0000980 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
981 (D.isConstexpr() ||
982 ((Ty.isPODType(getContext()) ||
983 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
984 D.getInit()->isConstantInitializer(getContext(), false)))) {
John McCall34695852011-02-22 06:44:22 +0000985
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000986 // If the variable's a const type, and it's neither an NRVO
987 // candidate nor a __block variable and has no mutable members,
988 // emit it as a global instead.
989 if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
990 CGM.isTypeConstant(Ty, true)) {
991 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCall34695852011-02-22 06:44:22 +0000992
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800993 // Signal this condition to later callbacks.
994 emission.Addr = Address::invalid();
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000995 assert(emission.wasEmittedAsGlobal());
996 return emission;
Tanya Lattner59876c22009-11-04 01:18:09 +0000997 }
Eric Christophere1f54902011-08-23 22:38:00 +0000998
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000999 // Otherwise, tell the initialization code that we're in this case.
1000 emission.IsConstantAggregate = true;
1001 }
Eric Christophere1f54902011-08-23 22:38:00 +00001002
Rafael Espindola6c82fc62013-03-26 18:41:47 +00001003 // A normal fixed sized variable becomes an alloca in the entry block,
1004 // unless it's an NRVO variable.
Eric Christophere1f54902011-08-23 22:38:00 +00001005
Rafael Espindola6c82fc62013-03-26 18:41:47 +00001006 if (NRVO) {
1007 // The named return value optimization: allocate this variable in the
1008 // return slot, so that we can elide the copy when returning this
1009 // variable (C++0x [class.copy]p34).
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001010 address = ReturnValue;
Eric Christophere1f54902011-08-23 22:38:00 +00001011
Rafael Espindola6c82fc62013-03-26 18:41:47 +00001012 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1013 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
1014 // Create a flag that is used to indicate when the NRVO was applied
1015 // to this variable. Set it to zero to indicate that NRVO was not
1016 // applied.
1017 llvm::Value *Zero = Builder.getFalse();
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001018 Address NRVOFlag =
1019 CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
Rafael Espindola6c82fc62013-03-26 18:41:47 +00001020 EnsureInsertPoint();
1021 Builder.CreateStore(Zero, NRVOFlag);
Eric Christophere1f54902011-08-23 22:38:00 +00001022
Rafael Espindola6c82fc62013-03-26 18:41:47 +00001023 // Record the NRVO flag for this variable.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001024 NRVOFlags[&D] = NRVOFlag.getPointer();
1025 emission.NRVOFlag = NRVOFlag.getPointer();
Nadav Rotem495cfa42013-03-23 06:43:35 +00001026 }
Douglas Gregord86c4772010-05-15 06:46:45 +00001027 }
Chris Lattner2621fd12008-05-08 05:58:21 +00001028 } else {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001029 CharUnits allocaAlignment;
1030 llvm::Type *allocaTy;
1031 if (isByRef) {
1032 auto &byrefInfo = getBlockByrefInfo(&D);
1033 allocaTy = byrefInfo.Type;
1034 allocaAlignment = byrefInfo.ByrefAlignment;
1035 } else {
1036 allocaTy = ConvertTypeForMem(Ty);
1037 allocaAlignment = alignment;
1038 }
Rafael Espindola6c82fc62013-03-26 18:41:47 +00001039
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001040 // Create the alloca. Note that we set the name separately from
1041 // building the instruction so that it's there even in no-asserts
1042 // builds.
1043 address = CreateTempAlloca(allocaTy, allocaAlignment);
1044 address.getPointer()->setName(D.getName());
Rafael Espindola6c82fc62013-03-26 18:41:47 +00001045
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001046 // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1047 // the catch parameter starts in the catchpad instruction, and we can't
1048 // insert code in those basic blocks.
1049 bool IsMSCatchParam =
1050 D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
Rafael Espindola6c82fc62013-03-26 18:41:47 +00001051
1052 // Emit a lifetime intrinsic if meaningful. There's no point
1053 // in doing this if we don't have a valid insertion point (?).
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001054 if (HaveInsertPoint() && !IsMSCatchParam) {
1055 uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
1056 emission.SizeForLifetimeMarkers =
1057 EmitLifetimeStart(size, address.getPointer());
Rafael Espindola6c82fc62013-03-26 18:41:47 +00001058 } else {
1059 assert(!emission.useLifetimeMarkers());
1060 }
Chris Lattner2621fd12008-05-08 05:58:21 +00001061 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001062 } else {
Daniel Dunbard286f052009-07-19 06:58:07 +00001063 EnsureInsertPoint();
1064
Anders Carlsson5ecb1b92009-02-09 20:41:50 +00001065 if (!DidCallStackSave) {
Anders Carlsson5d463152008-12-12 07:38:43 +00001066 // Save the stack.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001067 Address Stack =
1068 CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
Mike Stump1eb44332009-09-09 15:08:12 +00001069
Anders Carlsson5d463152008-12-12 07:38:43 +00001070 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001071 llvm::Value *V = Builder.CreateCall(F);
Anders Carlsson5d463152008-12-12 07:38:43 +00001072 Builder.CreateStore(V, Stack);
Anders Carlsson5ecb1b92009-02-09 20:41:50 +00001073
1074 DidCallStackSave = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001075
John McCalld8715092010-07-21 06:13:08 +00001076 // Push a cleanup block and restore the stack there.
John McCall3ad32c82011-01-28 08:37:24 +00001077 // FIXME: in general circumstances, this should be an EH cleanup.
Stephen Hines651f13c2014-04-23 16:59:28 -07001078 pushStackRestore(NormalCleanup, Stack);
Anders Carlsson5d463152008-12-12 07:38:43 +00001079 }
Mike Stump1eb44332009-09-09 15:08:12 +00001080
John McCallbc8d40d2011-06-24 21:55:10 +00001081 llvm::Value *elementCount;
1082 QualType elementType;
Stephen Hines651f13c2014-04-23 16:59:28 -07001083 std::tie(elementCount, elementType) = getVLASize(Ty);
Anders Carlsson5d463152008-12-12 07:38:43 +00001084
Chris Lattner2acc6e32011-07-18 04:24:23 +00001085 llvm::Type *llvmTy = ConvertTypeForMem(elementType);
Anders Carlsson5d463152008-12-12 07:38:43 +00001086
1087 // Allocate memory for the array.
John McCallbc8d40d2011-06-24 21:55:10 +00001088 llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
1089 vla->setAlignment(alignment.getQuantity());
Anders Carlsson41f8a132009-09-26 18:16:06 +00001090
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001091 address = Address(vla, alignment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001092 }
Eli Friedman8f39f5e2008-12-20 23:11:59 +00001093
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001094 setAddrOfLocalVar(&D, address);
1095 emission.Addr = address;
Sanjiv Guptacc9b1632008-05-30 10:30:31 +00001096
1097 // Emit debug info for local var declaration.
Devang Patelc594abd2011-06-03 19:21:47 +00001098 if (HaveInsertPoint())
1099 if (CGDebugInfo *DI = getDebugInfo()) {
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001100 if (CGM.getCodeGenOpts().getDebugInfo() >=
1101 codegenoptions::LimitedDebugInfo) {
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001102 DI->setLocation(D.getLocation());
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001103 DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001104 }
Devang Patelc594abd2011-06-03 19:21:47 +00001105 }
Sanjiv Guptacc9b1632008-05-30 10:30:31 +00001106
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001107 if (D.hasAttr<AnnotateAttr>())
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001108 EmitVarAnnotations(&D, address.getPointer());
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001109
John McCall34695852011-02-22 06:44:22 +00001110 return emission;
1111}
1112
1113/// Determines whether the given __block variable is potentially
1114/// captured by the given expression.
1115static bool isCapturedBy(const VarDecl &var, const Expr *e) {
1116 // Skip the most common kinds of expressions that make
1117 // hierarchy-walking expensive.
1118 e = e->IgnoreParenCasts();
1119
1120 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
1121 const BlockDecl *block = be->getBlockDecl();
Stephen Hines651f13c2014-04-23 16:59:28 -07001122 for (const auto &I : block->captures()) {
1123 if (I.getVariable() == &var)
John McCall34695852011-02-22 06:44:22 +00001124 return true;
1125 }
1126
1127 // No need to walk into the subexpressions.
1128 return false;
1129 }
1130
Fariborz Jahanian5033be12011-08-23 16:47:15 +00001131 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1132 const CompoundStmt *CS = SE->getSubStmt();
Stephen Hines651f13c2014-04-23 16:59:28 -07001133 for (const auto *BI : CS->body())
1134 if (const auto *E = dyn_cast<Expr>(BI)) {
Fariborz Jahanian5033be12011-08-23 16:47:15 +00001135 if (isCapturedBy(var, E))
1136 return true;
Fariborz Jahanian045c8422011-08-25 00:06:26 +00001137 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001138 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
Fariborz Jahanian045c8422011-08-25 00:06:26 +00001139 // special case declarations
Stephen Hines651f13c2014-04-23 16:59:28 -07001140 for (const auto *I : DS->decls()) {
1141 if (const auto *VD = dyn_cast<VarDecl>((I))) {
1142 const Expr *Init = VD->getInit();
Fariborz Jahanian045c8422011-08-25 00:06:26 +00001143 if (Init && isCapturedBy(var, Init))
1144 return true;
1145 }
1146 }
1147 }
1148 else
1149 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1150 // Later, provide code to poke into statements for capture analysis.
1151 return true;
Fariborz Jahanian5033be12011-08-23 16:47:15 +00001152 return false;
1153 }
Eric Christophere1f54902011-08-23 22:38:00 +00001154
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001155 for (const Stmt *SubStmt : e->children())
1156 if (isCapturedBy(var, cast<Expr>(SubStmt)))
John McCall34695852011-02-22 06:44:22 +00001157 return true;
1158
1159 return false;
1160}
1161
Douglas Gregorbcc3e662011-07-01 21:08:19 +00001162/// \brief Determine whether the given initializer is trivial in the sense
1163/// that it requires no code to be generated.
Stephen Hines176edba2014-12-01 14:53:08 -08001164bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
Douglas Gregorbcc3e662011-07-01 21:08:19 +00001165 if (!Init)
1166 return true;
Eric Christophere1f54902011-08-23 22:38:00 +00001167
Douglas Gregorbcc3e662011-07-01 21:08:19 +00001168 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1169 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1170 if (Constructor->isTrivial() &&
1171 Constructor->isDefaultConstructor() &&
1172 !Construct->requiresZeroInitialization())
1173 return true;
Eric Christophere1f54902011-08-23 22:38:00 +00001174
Douglas Gregorbcc3e662011-07-01 21:08:19 +00001175 return false;
1176}
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001177
John McCall34695852011-02-22 06:44:22 +00001178void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall57b3b6a2011-02-22 07:16:58 +00001179 assert(emission.Variable && "emission was not valid!");
1180
John McCall34695852011-02-22 06:44:22 +00001181 // If this was emitted as a global constant, we're done.
1182 if (emission.wasEmittedAsGlobal()) return;
1183
John McCall57b3b6a2011-02-22 07:16:58 +00001184 const VarDecl &D = *emission.Variable;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001185 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
John McCall34695852011-02-22 06:44:22 +00001186 QualType type = D.getType();
1187
Chris Lattner19785962007-07-12 00:39:48 +00001188 // If this local has an initializer, emit it now.
Daniel Dunbard286f052009-07-19 06:58:07 +00001189 const Expr *Init = D.getInit();
1190
1191 // If we are at an unreachable point, we don't need to emit the initializer
1192 // unless it contains a label.
1193 if (!HaveInsertPoint()) {
John McCall34695852011-02-22 06:44:22 +00001194 if (!Init || !ContainsLabel(Init)) return;
1195 EnsureInsertPoint();
Daniel Dunbard286f052009-07-19 06:58:07 +00001196 }
1197
John McCall5af02db2011-03-31 01:59:53 +00001198 // Initialize the structure of a __block variable.
1199 if (emission.IsByRef)
1200 emitByrefStructureInit(emission);
Anders Carlsson69c68b72009-02-07 23:51:38 +00001201
Douglas Gregorbcc3e662011-07-01 21:08:19 +00001202 if (isTrivialInitializer(Init))
1203 return;
Eric Christophere1f54902011-08-23 22:38:00 +00001204
John McCall34695852011-02-22 06:44:22 +00001205 // Check whether this is a byref variable that's potentially
1206 // captured and moved by its own initializer. If so, we'll need to
1207 // emit the initializer first, then copy into the variable.
1208 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1209
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001210 Address Loc =
1211 capturedByInit ? emission.Addr : emission.getObjectAddress(*this);
John McCall34695852011-02-22 06:44:22 +00001212
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001213 llvm::Constant *constant = nullptr;
Richard Smithe67ca582013-06-02 00:09:52 +00001214 if (emission.IsConstantAggregate || D.isConstexpr()) {
Richard Smith51201882011-12-30 21:15:51 +00001215 assert(!capturedByInit && "constant init contains a capturing block?");
Richard Smith2d6a5672012-01-14 04:30:29 +00001216 constant = CGM.EmitConstantInit(D, this);
Richard Smith51201882011-12-30 21:15:51 +00001217 }
1218
1219 if (!constant) {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001220 LValue lv = MakeAddrLValue(Loc, type);
John McCalla07398e2011-06-16 04:16:24 +00001221 lv.setNonGC(true);
1222 return EmitExprAsInit(Init, &D, lv, capturedByInit);
1223 }
John McCall60d33652011-03-08 09:11:50 +00001224
Richard Smithe67ca582013-06-02 00:09:52 +00001225 if (!emission.IsConstantAggregate) {
1226 // For simple scalar/complex initialization, store the value directly.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001227 LValue lv = MakeAddrLValue(Loc, type);
Richard Smithe67ca582013-06-02 00:09:52 +00001228 lv.setNonGC(true);
1229 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1230 }
1231
John McCall34695852011-02-22 06:44:22 +00001232 // If this is a simple aggregate initialization, we can optimize it
1233 // in various ways.
John McCall60d33652011-03-08 09:11:50 +00001234 bool isVolatile = type.isVolatileQualified();
John McCall34695852011-02-22 06:44:22 +00001235
John McCall60d33652011-03-08 09:11:50 +00001236 llvm::Value *SizeVal =
Eric Christophere1f54902011-08-23 22:38:00 +00001237 llvm::ConstantInt::get(IntPtrTy,
John McCall60d33652011-03-08 09:11:50 +00001238 getContext().getTypeSizeInChars(type).getQuantity());
John McCall34695852011-02-22 06:44:22 +00001239
Chris Lattner2acc6e32011-07-18 04:24:23 +00001240 llvm::Type *BP = Int8PtrTy;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001241 if (Loc.getType() != BP)
Benjamin Kramer578faa82011-09-27 21:06:10 +00001242 Loc = Builder.CreateBitCast(Loc, BP);
Mon P Wang3ecd7852010-04-04 03:10:52 +00001243
John McCall60d33652011-03-08 09:11:50 +00001244 // If the initializer is all or mostly zeros, codegen with memset then do
1245 // a few stores afterward.
Eric Christophere1f54902011-08-23 22:38:00 +00001246 if (shouldUseMemSetPlusStoresToInitialize(constant,
Micah Villmow25a6a842012-10-08 16:25:52 +00001247 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
John McCall60d33652011-03-08 09:11:50 +00001248 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001249 isVolatile);
Benjamin Kramer06d43682012-08-27 22:07:02 +00001250 // Zero and undef don't require a stores.
1251 if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
John McCall60d33652011-03-08 09:11:50 +00001252 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001253 emitStoresForInitAfterMemset(constant, Loc.getPointer(),
1254 isVolatile, Builder);
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +00001255 }
John McCall60d33652011-03-08 09:11:50 +00001256 } else {
Eric Christophere1f54902011-08-23 22:38:00 +00001257 // Otherwise, create a temporary global with the initializer then
John McCall60d33652011-03-08 09:11:50 +00001258 // memcpy from the global to the alloca.
Stephen Hines176edba2014-12-01 14:53:08 -08001259 std::string Name = getStaticDeclName(CGM, D);
John McCall60d33652011-03-08 09:11:50 +00001260 llvm::GlobalVariable *GV =
1261 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
Eric Christopher736a9c22011-08-24 00:33:55 +00001262 llvm::GlobalValue::PrivateLinkage,
Hans Wennborg5e2d5de2012-06-23 11:51:46 +00001263 constant, Name);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001264 GV->setAlignment(Loc.getAlignment().getQuantity());
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001265 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Eric Christophere1f54902011-08-23 22:38:00 +00001266
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001267 Address SrcPtr = Address(GV, Loc.getAlignment());
1268 if (SrcPtr.getType() != BP)
Benjamin Kramer578faa82011-09-27 21:06:10 +00001269 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
John McCall60d33652011-03-08 09:11:50 +00001270
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001271 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, isVolatile);
John McCall60d33652011-03-08 09:11:50 +00001272 }
1273}
1274
1275/// Emit an expression as an initializer for a variable at the given
1276/// location. The expression is not necessarily the normal
1277/// initializer for the variable, and the address is not necessarily
1278/// its normal location.
1279///
1280/// \param init the initializing expression
1281/// \param var the variable to act as if we're initializing
1282/// \param loc the address to initialize; its type is a pointer
1283/// to the LLVM mapping of the variable's type
1284/// \param alignment the alignment of the address
1285/// \param capturedByInit true if the variable is a __block variable
1286/// whose address is potentially changed by the initializer
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001287void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
1288 LValue lvalue, bool capturedByInit) {
John McCallf85e1932011-06-15 23:02:42 +00001289 QualType type = D->getType();
John McCall60d33652011-03-08 09:11:50 +00001290
1291 if (type->isReferenceType()) {
Richard Smithd4ec5622013-06-12 23:38:09 +00001292 RValue rvalue = EmitReferenceBindingToExpr(init);
Eric Christophere1f54902011-08-23 22:38:00 +00001293 if (capturedByInit)
John McCalla07398e2011-06-16 04:16:24 +00001294 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Chisnall7a7ee302012-01-16 17:27:18 +00001295 EmitStoreThroughLValue(rvalue, lvalue, true);
John McCall9d232c82013-03-07 21:37:08 +00001296 return;
1297 }
1298 switch (getEvaluationKind(type)) {
1299 case TEK_Scalar:
John McCalla07398e2011-06-16 04:16:24 +00001300 EmitScalarInit(init, D, lvalue, capturedByInit);
John McCall9d232c82013-03-07 21:37:08 +00001301 return;
1302 case TEK_Complex: {
John McCall60d33652011-03-08 09:11:50 +00001303 ComplexPairTy complex = EmitComplexExpr(init);
John McCalla07398e2011-06-16 04:16:24 +00001304 if (capturedByInit)
1305 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall9d232c82013-03-07 21:37:08 +00001306 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
1307 return;
1308 }
1309 case TEK_Aggregate:
John McCall9eda3ab2013-03-07 21:37:17 +00001310 if (type->isAtomicType()) {
1311 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1312 } else {
1313 // TODO: how can we delay here if D is captured by its initializer?
1314 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
Chad Rosier649b4a12012-03-29 17:37:10 +00001315 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001316 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001317 AggValueSlot::IsNotAliased));
John McCall9eda3ab2013-03-07 21:37:17 +00001318 }
John McCall9d232c82013-03-07 21:37:08 +00001319 return;
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +00001320 }
John McCall9d232c82013-03-07 21:37:08 +00001321 llvm_unreachable("bad evaluation kind");
John McCall34695852011-02-22 06:44:22 +00001322}
John McCallf1549f62010-07-06 01:34:17 +00001323
John McCallbdc4d802011-07-09 01:37:26 +00001324/// Enter a destroy cleanup for the given local variable.
1325void CodeGenFunction::emitAutoVarTypeCleanup(
1326 const CodeGenFunction::AutoVarEmission &emission,
1327 QualType::DestructionKind dtorKind) {
1328 assert(dtorKind != QualType::DK_none);
1329
1330 // Note that for __block variables, we want to destroy the
1331 // original stack object, not the possibly forwarded object.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001332 Address addr = emission.getObjectAddress(*this);
John McCallbdc4d802011-07-09 01:37:26 +00001333
1334 const VarDecl *var = emission.Variable;
1335 QualType type = var->getType();
1336
1337 CleanupKind cleanupKind = NormalAndEHCleanup;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001338 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCallbdc4d802011-07-09 01:37:26 +00001339
1340 switch (dtorKind) {
1341 case QualType::DK_none:
1342 llvm_unreachable("no cleanup for trivially-destructible variable");
1343
1344 case QualType::DK_cxx_destructor:
1345 // If there's an NRVO flag on the emission, we need a different
1346 // cleanup.
1347 if (emission.NRVOFlag) {
1348 assert(!type->isArrayType());
1349 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001350 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr,
1351 dtor, emission.NRVOFlag);
John McCallbdc4d802011-07-09 01:37:26 +00001352 return;
1353 }
1354 break;
1355
1356 case QualType::DK_objc_strong_lifetime:
1357 // Suppress cleanups for pseudo-strong variables.
1358 if (var->isARCPseudoStrong()) return;
Eric Christophere1f54902011-08-23 22:38:00 +00001359
John McCallbdc4d802011-07-09 01:37:26 +00001360 // Otherwise, consider whether to use an EH cleanup or not.
1361 cleanupKind = getARCCleanupKind();
1362
1363 // Use the imprecise destroyer by default.
1364 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1365 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1366 break;
1367
1368 case QualType::DK_objc_weak_lifetime:
1369 break;
1370 }
1371
1372 // If we haven't chosen a more specific destroyer, use the default.
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001373 if (!destroyer) destroyer = getDestroyer(dtorKind);
John McCall2673c682011-07-11 08:38:19 +00001374
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00001375 // Use an EH cleanup in array destructors iff the destructor itself
John McCall2673c682011-07-11 08:38:19 +00001376 // is being pushed as an EH cleanup.
1377 bool useEHCleanup = (cleanupKind & EHCleanup);
1378 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1379 useEHCleanup);
John McCallbdc4d802011-07-09 01:37:26 +00001380}
1381
John McCall34695852011-02-22 06:44:22 +00001382void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall57b3b6a2011-02-22 07:16:58 +00001383 assert(emission.Variable && "emission was not valid!");
1384
John McCall34695852011-02-22 06:44:22 +00001385 // If this was emitted as a global constant, we're done.
1386 if (emission.wasEmittedAsGlobal()) return;
1387
John McCall38baeab2012-04-13 18:44:05 +00001388 // If we don't have an insertion point, we're done. Sema prevents
1389 // us from jumping into any of these scopes anyway.
1390 if (!HaveInsertPoint()) return;
1391
John McCall57b3b6a2011-02-22 07:16:58 +00001392 const VarDecl &D = *emission.Variable;
John McCall34695852011-02-22 06:44:22 +00001393
Nadav Rotem495cfa42013-03-23 06:43:35 +00001394 // Make sure we call @llvm.lifetime.end. This needs to happen
1395 // *last*, so the cleanup needs to be pushed *first*.
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001396 if (emission.useLifetimeMarkers())
1397 EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
Nadav Rotem495cfa42013-03-23 06:43:35 +00001398 emission.getAllocatedAddress(),
1399 emission.getSizeForLifetimeMarkers());
Nadav Rotem495cfa42013-03-23 06:43:35 +00001400
John McCallbdc4d802011-07-09 01:37:26 +00001401 // Check the type for a cleanup.
1402 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1403 emitAutoVarTypeCleanup(emission, dtorKind);
John McCallf85e1932011-06-15 23:02:42 +00001404
John McCall0c24c802011-06-24 23:21:27 +00001405 // In GC mode, honor objc_precise_lifetime.
David Blaikie4e4d0842012-03-11 07:00:24 +00001406 if (getLangOpts().getGC() != LangOptions::NonGC &&
John McCall0c24c802011-06-24 23:21:27 +00001407 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1408 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1409 }
1410
John McCall34695852011-02-22 06:44:22 +00001411 // Handle the cleanup attribute.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001412 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlsson69c68b72009-02-07 23:51:38 +00001413 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001414
John McCall34695852011-02-22 06:44:22 +00001415 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlsson69c68b72009-02-07 23:51:38 +00001416 assert(F && "Could not find function!");
Mike Stump1eb44332009-09-09 15:08:12 +00001417
John McCallde5d3c72012-02-17 03:33:10 +00001418 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
John McCall34695852011-02-22 06:44:22 +00001419 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlsson69c68b72009-02-07 23:51:38 +00001420 }
Mike Stump797b6322009-03-05 01:23:13 +00001421
John McCall34695852011-02-22 06:44:22 +00001422 // If this is a block variable, call _Block_object_destroy
1423 // (on the unforwarded address).
John McCall5af02db2011-03-31 01:59:53 +00001424 if (emission.IsByRef)
1425 enterByrefCleanup(emission);
Reid Spencer5f016e22007-07-11 17:01:13 +00001426}
1427
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001428CodeGenFunction::Destroyer *
John McCallbdc4d802011-07-09 01:37:26 +00001429CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1430 switch (kind) {
1431 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
John McCall0850e8d2011-07-09 09:09:00 +00001432 case QualType::DK_cxx_destructor:
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001433 return destroyCXXObject;
John McCall0850e8d2011-07-09 09:09:00 +00001434 case QualType::DK_objc_strong_lifetime:
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001435 return destroyARCStrongPrecise;
John McCall0850e8d2011-07-09 09:09:00 +00001436 case QualType::DK_objc_weak_lifetime:
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001437 return destroyARCWeak;
John McCallbdc4d802011-07-09 01:37:26 +00001438 }
Matt Beaumont-Gayba4be252012-01-27 00:46:27 +00001439 llvm_unreachable("Unknown DestructionKind");
John McCallbdc4d802011-07-09 01:37:26 +00001440}
1441
John McCall074cae02013-02-01 05:11:40 +00001442/// pushEHDestroy - Push the standard destructor for the given type as
1443/// an EH-only cleanup.
1444void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001445 Address addr, QualType type) {
John McCall074cae02013-02-01 05:11:40 +00001446 assert(dtorKind && "cannot push destructor for trivial type");
1447 assert(needsEHCleanup(dtorKind));
1448
1449 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1450}
1451
1452/// pushDestroy - Push the standard destructor for the given type as
1453/// at least a normal cleanup.
John McCall9928c482011-07-12 16:41:08 +00001454void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001455 Address addr, QualType type) {
John McCall9928c482011-07-12 16:41:08 +00001456 assert(dtorKind && "cannot push destructor for trivial type");
1457
1458 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1459 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1460 cleanupKind & EHCleanup);
1461}
1462
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001463void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001464 QualType type, Destroyer *destroyer,
John McCall2673c682011-07-11 08:38:19 +00001465 bool useEHCleanupForArray) {
John McCall9928c482011-07-12 16:41:08 +00001466 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1467 destroyer, useEHCleanupForArray);
John McCallbdc4d802011-07-09 01:37:26 +00001468}
1469
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001470void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001471 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
1472}
1473
Richard Smith8a07cd32013-06-12 20:42:33 +00001474void CodeGenFunction::pushLifetimeExtendedDestroy(
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001475 CleanupKind cleanupKind, Address addr, QualType type,
Richard Smith8a07cd32013-06-12 20:42:33 +00001476 Destroyer *destroyer, bool useEHCleanupForArray) {
1477 assert(!isInConditionalBranch() &&
1478 "performing lifetime extension from within conditional");
1479
1480 // Push an EH-only cleanup for the object now.
1481 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1482 // around in case a temporary's destructor throws an exception.
1483 if (cleanupKind & EHCleanup)
1484 EHStack.pushCleanup<DestroyObject>(
1485 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1486 destroyer, useEHCleanupForArray);
1487
1488 // Remember that we need to push a full cleanup for the object at the
1489 // end of the full-expression.
1490 pushCleanupAfterFullExpr<DestroyObject>(
1491 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1492}
1493
John McCall2673c682011-07-11 08:38:19 +00001494/// emitDestroy - Immediately perform the destruction of the given
1495/// object.
1496///
1497/// \param addr - the address of the object; a type*
1498/// \param type - the type of the object; if an array type, all
1499/// objects are destroyed in reverse order
1500/// \param destroyer - the function to call to destroy individual
1501/// elements
1502/// \param useEHCleanupForArray - whether an EH cleanup should be
1503/// used when destroying array elements, in case one of the
1504/// destructions throws an exception
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001505void CodeGenFunction::emitDestroy(Address addr, QualType type,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001506 Destroyer *destroyer,
John McCall2673c682011-07-11 08:38:19 +00001507 bool useEHCleanupForArray) {
John McCallbdc4d802011-07-09 01:37:26 +00001508 const ArrayType *arrayType = getContext().getAsArrayType(type);
1509 if (!arrayType)
1510 return destroyer(*this, addr, type);
1511
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001512 llvm::Value *length = emitArrayLength(arrayType, type, addr);
1513
1514 CharUnits elementAlign =
1515 addr.getAlignment()
1516 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
John McCallfbf780a2011-07-13 08:09:46 +00001517
1518 // Normally we have to check whether the array is zero-length.
1519 bool checkZeroLength = true;
1520
1521 // But if the array length is constant, we can suppress that.
1522 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1523 // ...and if it's constant zero, we can just skip the entire thing.
1524 if (constLength->isZero()) return;
1525 checkZeroLength = false;
1526 }
1527
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001528 llvm::Value *begin = addr.getPointer();
John McCallbdc4d802011-07-09 01:37:26 +00001529 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001530 emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCallfbf780a2011-07-13 08:09:46 +00001531 checkZeroLength, useEHCleanupForArray);
John McCallbdc4d802011-07-09 01:37:26 +00001532}
1533
John McCall2673c682011-07-11 08:38:19 +00001534/// emitArrayDestroy - Destroys all the elements of the given array,
1535/// beginning from last to first. The array cannot be zero-length.
1536///
1537/// \param begin - a type* denoting the first element of the array
1538/// \param end - a type* denoting one past the end of the array
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001539/// \param elementType - the element type of the array
John McCall2673c682011-07-11 08:38:19 +00001540/// \param destroyer - the function to call to destroy elements
1541/// \param useEHCleanup - whether to push an EH cleanup to destroy
1542/// the remaining elements in case the destruction of a single
1543/// element throws
John McCallbdc4d802011-07-09 01:37:26 +00001544void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1545 llvm::Value *end,
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001546 QualType elementType,
1547 CharUnits elementAlign,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001548 Destroyer *destroyer,
John McCallfbf780a2011-07-13 08:09:46 +00001549 bool checkZeroLength,
John McCall2673c682011-07-11 08:38:19 +00001550 bool useEHCleanup) {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001551 assert(!elementType->isArrayType());
John McCallbdc4d802011-07-09 01:37:26 +00001552
1553 // The basic structure here is a do-while loop, because we don't
1554 // need to check for the zero-element case.
1555 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1556 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1557
John McCallfbf780a2011-07-13 08:09:46 +00001558 if (checkZeroLength) {
1559 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1560 "arraydestroy.isempty");
1561 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1562 }
1563
John McCallbdc4d802011-07-09 01:37:26 +00001564 // Enter the loop body, making that address the current address.
1565 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1566 EmitBlock(bodyBB);
1567 llvm::PHINode *elementPast =
1568 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1569 elementPast->addIncoming(end, entryBB);
1570
1571 // Shift the address back by one element.
1572 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1573 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1574 "arraydestroy.element");
1575
John McCall2673c682011-07-11 08:38:19 +00001576 if (useEHCleanup)
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001577 pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
1578 destroyer);
John McCall2673c682011-07-11 08:38:19 +00001579
John McCallbdc4d802011-07-09 01:37:26 +00001580 // Perform the actual destruction there.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001581 destroyer(*this, Address(element, elementAlign), elementType);
John McCallbdc4d802011-07-09 01:37:26 +00001582
John McCall2673c682011-07-11 08:38:19 +00001583 if (useEHCleanup)
1584 PopCleanupBlock();
1585
John McCallbdc4d802011-07-09 01:37:26 +00001586 // Check whether we've reached the end.
1587 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1588 Builder.CreateCondBr(done, doneBB, bodyBB);
1589 elementPast->addIncoming(element, Builder.GetInsertBlock());
1590
1591 // Done.
1592 EmitBlock(doneBB);
1593}
1594
John McCall2673c682011-07-11 08:38:19 +00001595/// Perform partial array destruction as if in an EH cleanup. Unlike
1596/// emitArrayDestroy, the element type here may still be an array type.
John McCall2673c682011-07-11 08:38:19 +00001597static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1598 llvm::Value *begin, llvm::Value *end,
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001599 QualType type, CharUnits elementAlign,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001600 CodeGenFunction::Destroyer *destroyer) {
John McCall2673c682011-07-11 08:38:19 +00001601 // If the element type is itself an array, drill down.
John McCallfbf780a2011-07-13 08:09:46 +00001602 unsigned arrayDepth = 0;
John McCall2673c682011-07-11 08:38:19 +00001603 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1604 // VLAs don't require a GEP index to walk into.
1605 if (!isa<VariableArrayType>(arrayType))
John McCallfbf780a2011-07-13 08:09:46 +00001606 arrayDepth++;
John McCall2673c682011-07-11 08:38:19 +00001607 type = arrayType->getElementType();
1608 }
John McCallfbf780a2011-07-13 08:09:46 +00001609
1610 if (arrayDepth) {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001611 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
John McCallfbf780a2011-07-13 08:09:46 +00001612
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001613 SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
Jay Foad0f6ac7c2011-07-22 08:16:57 +00001614 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1615 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
John McCall2673c682011-07-11 08:38:19 +00001616 }
1617
John McCallfbf780a2011-07-13 08:09:46 +00001618 // Destroy the array. We don't ever need an EH cleanup because we
1619 // assume that we're in an EH cleanup ourselves, so a throwing
1620 // destructor causes an immediate terminate.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001621 CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCallfbf780a2011-07-13 08:09:46 +00001622 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
John McCall2673c682011-07-11 08:38:19 +00001623}
1624
John McCallbdc4d802011-07-09 01:37:26 +00001625namespace {
John McCall2673c682011-07-11 08:38:19 +00001626 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1627 /// array destroy where the end pointer is regularly determined and
1628 /// does not need to be loaded from a local.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001629 class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall2673c682011-07-11 08:38:19 +00001630 llvm::Value *ArrayBegin;
1631 llvm::Value *ArrayEnd;
1632 QualType ElementType;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001633 CodeGenFunction::Destroyer *Destroyer;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001634 CharUnits ElementAlign;
John McCall2673c682011-07-11 08:38:19 +00001635 public:
1636 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001637 QualType elementType, CharUnits elementAlign,
John McCall2673c682011-07-11 08:38:19 +00001638 CodeGenFunction::Destroyer *destroyer)
1639 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001640 ElementType(elementType), Destroyer(destroyer),
1641 ElementAlign(elementAlign) {}
John McCall2673c682011-07-11 08:38:19 +00001642
Stephen Hines651f13c2014-04-23 16:59:28 -07001643 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall2673c682011-07-11 08:38:19 +00001644 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001645 ElementType, ElementAlign, Destroyer);
John McCall2673c682011-07-11 08:38:19 +00001646 }
1647 };
1648
1649 /// IrregularPartialArrayDestroy - a cleanup which performs a
1650 /// partial array destroy where the end pointer is irregularly
1651 /// determined and must be loaded from a local.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001652 class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCallbdc4d802011-07-09 01:37:26 +00001653 llvm::Value *ArrayBegin;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001654 Address ArrayEndPointer;
John McCallbdc4d802011-07-09 01:37:26 +00001655 QualType ElementType;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001656 CodeGenFunction::Destroyer *Destroyer;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001657 CharUnits ElementAlign;
John McCallbdc4d802011-07-09 01:37:26 +00001658 public:
John McCall2673c682011-07-11 08:38:19 +00001659 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001660 Address arrayEndPointer,
John McCall2673c682011-07-11 08:38:19 +00001661 QualType elementType,
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001662 CharUnits elementAlign,
John McCall2673c682011-07-11 08:38:19 +00001663 CodeGenFunction::Destroyer *destroyer)
John McCallbdc4d802011-07-09 01:37:26 +00001664 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001665 ElementType(elementType), Destroyer(destroyer),
1666 ElementAlign(elementAlign) {}
John McCallbdc4d802011-07-09 01:37:26 +00001667
Stephen Hines651f13c2014-04-23 16:59:28 -07001668 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallbdc4d802011-07-09 01:37:26 +00001669 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
John McCall2673c682011-07-11 08:38:19 +00001670 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001671 ElementType, ElementAlign, Destroyer);
John McCallbdc4d802011-07-09 01:37:26 +00001672 }
1673 };
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001674} // end anonymous namespace
John McCallbdc4d802011-07-09 01:37:26 +00001675
John McCall2673c682011-07-11 08:38:19 +00001676/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
John McCallbdc4d802011-07-09 01:37:26 +00001677/// already-constructed elements of the given array. The cleanup
John McCall2673c682011-07-11 08:38:19 +00001678/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christophere1f54902011-08-23 22:38:00 +00001679///
John McCallbdc4d802011-07-09 01:37:26 +00001680/// \param elementType - the immediate element type of the array;
1681/// possibly still an array type
John McCall9928c482011-07-12 16:41:08 +00001682void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001683 Address arrayEndPointer,
John McCall2673c682011-07-11 08:38:19 +00001684 QualType elementType,
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001685 CharUnits elementAlign,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001686 Destroyer *destroyer) {
John McCall9928c482011-07-12 16:41:08 +00001687 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1688 arrayBegin, arrayEndPointer,
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001689 elementType, elementAlign,
1690 destroyer);
John McCall2673c682011-07-11 08:38:19 +00001691}
1692
1693/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1694/// already-constructed elements of the given array. The cleanup
1695/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christophere1f54902011-08-23 22:38:00 +00001696///
John McCall2673c682011-07-11 08:38:19 +00001697/// \param elementType - the immediate element type of the array;
1698/// possibly still an array type
John McCall2673c682011-07-11 08:38:19 +00001699void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1700 llvm::Value *arrayEnd,
1701 QualType elementType,
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001702 CharUnits elementAlign,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001703 Destroyer *destroyer) {
John McCall9928c482011-07-12 16:41:08 +00001704 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
John McCall2673c682011-07-11 08:38:19 +00001705 arrayBegin, arrayEnd,
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001706 elementType, elementAlign,
1707 destroyer);
John McCallbdc4d802011-07-09 01:37:26 +00001708}
1709
Nadav Rotem495cfa42013-03-23 06:43:35 +00001710/// Lazily declare the @llvm.lifetime.start intrinsic.
1711llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
1712 if (LifetimeStartFn) return LifetimeStartFn;
1713 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1714 llvm::Intrinsic::lifetime_start);
1715 return LifetimeStartFn;
1716}
1717
1718/// Lazily declare the @llvm.lifetime.end intrinsic.
1719llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
1720 if (LifetimeEndFn) return LifetimeEndFn;
1721 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1722 llvm::Intrinsic::lifetime_end);
1723 return LifetimeEndFn;
1724}
1725
John McCallf85e1932011-06-15 23:02:42 +00001726namespace {
1727 /// A cleanup to perform a release of an object at the end of a
1728 /// function. This is used to balance out the incoming +1 of a
1729 /// ns_consumed argument when we can't reasonably do that just by
1730 /// not doing the initial retain for a __block argument.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001731 struct ConsumeARCParameter final : EHScopeStack::Cleanup {
John McCall5b07e802013-03-13 03:10:54 +00001732 ConsumeARCParameter(llvm::Value *param,
1733 ARCPreciseLifetime_t precise)
1734 : Param(param), Precise(precise) {}
John McCallf85e1932011-06-15 23:02:42 +00001735
1736 llvm::Value *Param;
John McCall5b07e802013-03-13 03:10:54 +00001737 ARCPreciseLifetime_t Precise;
John McCallf85e1932011-06-15 23:02:42 +00001738
Stephen Hines651f13c2014-04-23 16:59:28 -07001739 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall5b07e802013-03-13 03:10:54 +00001740 CGF.EmitARCRelease(Param, Precise);
John McCallf85e1932011-06-15 23:02:42 +00001741 }
1742 };
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001743} // end anonymous namespace
John McCallf85e1932011-06-15 23:02:42 +00001744
Mike Stump1eb44332009-09-09 15:08:12 +00001745/// Emit an alloca (or GlobalValue depending on target)
Chris Lattner2621fd12008-05-08 05:58:21 +00001746/// for the specified parameter and set up LocalDeclMap.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001747void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
1748 unsigned ArgNo) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001749 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Gupta31fc07d2008-10-31 09:52:39 +00001750 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001751 "Invalid argument to EmitParmDecl");
John McCall8178df32011-02-22 22:38:33 +00001752
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001753 Arg.getAnyValue()->setName(D.getName());
John McCall8178df32011-02-22 22:38:33 +00001754
Adrian Prantl836e7c92013-03-14 17:53:33 +00001755 QualType Ty = D.getType();
1756
John McCall8178df32011-02-22 22:38:33 +00001757 // Use better IR generation for certain implicit parameters.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001758 if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
John McCall8178df32011-02-22 22:38:33 +00001759 // The only implicit argument a block has is its literal.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001760 // We assume this is always passed directly.
John McCall8178df32011-02-22 22:38:33 +00001761 if (BlockInfo) {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001762 setBlockContextParameter(IPD, ArgNo, Arg.getDirectValue());
John McCall8178df32011-02-22 22:38:33 +00001763 return;
1764 }
1765 }
1766
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001767 Address DeclPtr = Address::invalid();
Stephen Hines651f13c2014-04-23 16:59:28 -07001768 bool DoStore = false;
1769 bool IsScalar = hasScalarEvaluationKind(Ty);
Stephen Hines651f13c2014-04-23 16:59:28 -07001770 // If we already have a pointer to the argument, reuse the input pointer.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001771 if (Arg.isIndirect()) {
1772 DeclPtr = Arg.getIndirectAddress();
Stephen Hines651f13c2014-04-23 16:59:28 -07001773 // If we have a prettier pointer type at this point, bitcast to that.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001774 unsigned AS = DeclPtr.getType()->getAddressSpace();
Stephen Hines651f13c2014-04-23 16:59:28 -07001775 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001776 if (DeclPtr.getType() != IRTy)
1777 DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
1778
Reid Kleckner9b601952013-06-21 12:45:15 +00001779 // Push a destructor cleanup for this parameter if the ABI requires it.
Stephen Hines176edba2014-12-01 14:53:08 -08001780 // Don't push a cleanup in a thunk for a method that will also emit a
1781 // cleanup.
1782 if (!IsScalar && !CurFuncIsThunk &&
Stephen Hines651f13c2014-04-23 16:59:28 -07001783 getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
1784 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
1785 if (RD && RD->hasNonTrivialDestructor())
1786 pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
Reid Kleckner9b601952013-06-21 12:45:15 +00001787 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001788 } else {
Daniel Dunbare86bcf02010-02-08 22:53:07 +00001789 // Otherwise, create a temporary to hold the value.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001790 DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
1791 D.getName() + ".addr");
Stephen Hines651f13c2014-04-23 16:59:28 -07001792 DoStore = true;
1793 }
Mike Stump1eb44332009-09-09 15:08:12 +00001794
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001795 llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
1796
1797 LValue lv = MakeAddrLValue(DeclPtr, Ty);
Stephen Hines651f13c2014-04-23 16:59:28 -07001798 if (IsScalar) {
John McCallf85e1932011-06-15 23:02:42 +00001799 Qualifiers qs = Ty.getQualifiers();
John McCallf85e1932011-06-15 23:02:42 +00001800 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1801 // We honor __attribute__((ns_consumed)) for types with lifetime.
1802 // For __strong, it's handled by just skipping the initial retain;
1803 // otherwise we have to balance out the initial +1 with an extra
1804 // cleanup to do the release at the end of the function.
1805 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1806
1807 // 'self' is always formally __strong, but if this is not an
1808 // init method then we don't want to retain it.
John McCall7acddac2011-06-17 06:42:21 +00001809 if (D.isARCPseudoStrong()) {
John McCallf85e1932011-06-15 23:02:42 +00001810 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1811 assert(&D == method->getSelfDecl());
John McCall7acddac2011-06-17 06:42:21 +00001812 assert(lt == Qualifiers::OCL_Strong);
1813 assert(qs.hasConst());
John McCallf85e1932011-06-15 23:02:42 +00001814 assert(method->getMethodFamily() != OMF_init);
John McCall175d6592011-06-15 23:40:09 +00001815 (void) method;
John McCallf85e1932011-06-15 23:02:42 +00001816 lt = Qualifiers::OCL_ExplicitNone;
1817 }
1818
1819 if (lt == Qualifiers::OCL_Strong) {
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001820 if (!isConsumed) {
1821 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1822 // use objc_storeStrong(&dest, value) for retaining the
1823 // object. But first, store a null into 'dest' because
1824 // objc_storeStrong attempts to release its old value.
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001825 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001826 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001827 EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
Stephen Hines651f13c2014-04-23 16:59:28 -07001828 DoStore = false;
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001829 }
1830 else
John McCallf85e1932011-06-15 23:02:42 +00001831 // Don't use objc_retainBlock for block pointers, because we
1832 // don't want to Block_copy something just because we got it
1833 // as a parameter.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001834 ArgVal = EmitARCRetainNonBlock(ArgVal);
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001835 }
John McCallf85e1932011-06-15 23:02:42 +00001836 } else {
1837 // Push the cleanup for a consumed parameter.
John McCall5b07e802013-03-13 03:10:54 +00001838 if (isConsumed) {
1839 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1840 ? ARCPreciseLifetime : ARCImpreciseLifetime);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001841 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
John McCall5b07e802013-03-13 03:10:54 +00001842 precise);
1843 }
John McCallf85e1932011-06-15 23:02:42 +00001844
1845 if (lt == Qualifiers::OCL_Weak) {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001846 EmitARCInitWeak(DeclPtr, ArgVal);
Stephen Hines651f13c2014-04-23 16:59:28 -07001847 DoStore = false; // The weak init is a store, no need to do two.
John McCallf85e1932011-06-15 23:02:42 +00001848 }
1849 }
1850
1851 // Enter the cleanup scope.
1852 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1853 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001854 }
1855
Stephen Hines651f13c2014-04-23 16:59:28 -07001856 // Store the initial value into the alloca.
1857 if (DoStore)
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001858 EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
Stephen Hines651f13c2014-04-23 16:59:28 -07001859
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001860 setAddrOfLocalVar(&D, DeclPtr);
Sanjiv Guptacc9b1632008-05-30 10:30:31 +00001861
1862 // Emit debug info for param declaration.
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001863 if (CGDebugInfo *DI = getDebugInfo()) {
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001864 if (CGM.getCodeGenOpts().getDebugInfo() >=
1865 codegenoptions::LimitedDebugInfo) {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001866 DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001867 }
1868 }
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001869
1870 if (D.hasAttr<AnnotateAttr>())
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001871 EmitVarAnnotations(&D, DeclPtr.getPointer());
Reid Spencer5f016e22007-07-11 17:01:13 +00001872}
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001873
1874void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
1875 CodeGenFunction *CGF) {
1876 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
1877 return;
1878 getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
1879}