blob: 75a135031e50a678689c9f3cb3b4d5509e6e5aec [file] [log] [blame]
Chris Lattner84915fa2007-06-02 04:16:21 +00001//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner84915fa2007-06-02 04:16:21 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Decl nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
John McCall7f416cc2015-09-08 08:05:57 +000014#include "CGBlocks.h"
Reid Klecknere5a321b2016-09-07 18:21:30 +000015#include "CGCXXABI.h"
David Majnemerdc012fa2015-04-22 21:38:15 +000016#include "CGCleanup.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "CGDebugInfo.h"
Peter Collingbourne2dbb7082011-09-19 21:14:35 +000018#include "CGOpenCLRuntime.h"
Alexey Bataevc5b1d322016-03-04 09:22:22 +000019#include "CGOpenMPRuntime.h"
Yaxun Liu6d96f1632017-05-18 18:51:09 +000020#include "CodeGenFunction.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "CodeGenModule.h"
John McCallde0fe072017-08-15 21:42:52 +000022#include "ConstantEmitter.h"
Yaxun Liu6d96f1632017-05-18 18:51:09 +000023#include "TargetInfo.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000024#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000025#include "clang/AST/CharUnits.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000026#include "clang/AST/Decl.h"
Anders Carlsson4c03d982008-08-25 01:38:19 +000027#include "clang/AST/DeclObjC.h"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000028#include "clang/AST/DeclOpenMP.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000029#include "clang/Basic/SourceManager.h"
Chris Lattnerb781dc792008-05-08 05:58:21 +000030#include "clang/Basic/TargetInfo.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000031#include "clang/CodeGen/CGFunctionInfo.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000032#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000033#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/GlobalVariable.h"
35#include "llvm/IR/Intrinsics.h"
36#include "llvm/IR/Type.h"
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +000037
Chris Lattner84915fa2007-06-02 04:16:21 +000038using namespace clang;
39using namespace CodeGen;
40
Chris Lattner1ad38f82007-06-09 01:20:56 +000041void CodeGenFunction::EmitDecl(const Decl &D) {
Chris Lattner1ad38f82007-06-09 01:20:56 +000042 switch (D.getKind()) {
David Majnemerd9b1a4f2015-11-04 03:40:30 +000043 case Decl::BuiltinTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000044 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +000045 case Decl::ExternCContext:
Douglas Gregor19043f02010-04-23 02:02:43 +000046 case Decl::Namespace:
47 case Decl::UnresolvedUsingTypename:
48 case Decl::ClassTemplateSpecialization:
49 case Decl::ClassTemplatePartialSpecialization:
Larisse Voufo39a1e502013-08-06 01:03:05 +000050 case Decl::VarTemplateSpecialization:
51 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor19043f02010-04-23 02:02:43 +000052 case Decl::TemplateTypeParm:
53 case Decl::UnresolvedUsingValue:
Alexis Hunted053252010-05-30 07:21:58 +000054 case Decl::NonTypeTemplateParm:
Richard Smithbc491202017-02-17 20:05:37 +000055 case Decl::CXXDeductionGuide:
Douglas Gregor19043f02010-04-23 02:02:43 +000056 case Decl::CXXMethod:
57 case Decl::CXXConstructor:
58 case Decl::CXXDestructor:
59 case Decl::CXXConversion:
60 case Decl::Field:
John McCall5e77d762013-04-16 07:28:30 +000061 case Decl::MSProperty:
Francois Pichetdf946c32010-11-21 06:49:41 +000062 case Decl::IndirectField:
Douglas Gregor19043f02010-04-23 02:02:43 +000063 case Decl::ObjCIvar:
Eric Christopher31ab1302011-08-23 22:38:00 +000064 case Decl::ObjCAtDefsField:
Chris Lattnerba9dddb2007-10-08 21:37:32 +000065 case Decl::ParmVar:
Douglas Gregor19043f02010-04-23 02:02:43 +000066 case Decl::ImplicitParam:
67 case Decl::ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +000068 case Decl::VarTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000069 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +000070 case Decl::TypeAliasTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000071 case Decl::TemplateTemplateParm:
72 case Decl::ObjCMethod:
73 case Decl::ObjCCategory:
74 case Decl::ObjCProtocol:
75 case Decl::ObjCInterface:
76 case Decl::ObjCCategoryImpl:
77 case Decl::ObjCImplementation:
78 case Decl::ObjCProperty:
79 case Decl::ObjCCompatibleAlias:
Nico Weber66220292016-03-02 17:28:48 +000080 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +000081 case Decl::PragmaDetectMismatch:
Abramo Bagnarad7340582010-06-05 05:09:32 +000082 case Decl::AccessSpec:
Douglas Gregor19043f02010-04-23 02:02:43 +000083 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +000084 case Decl::Export:
Douglas Gregor19043f02010-04-23 02:02:43 +000085 case Decl::ObjCPropertyImpl:
Douglas Gregor19043f02010-04-23 02:02:43 +000086 case Decl::FileScopeAsm:
87 case Decl::Friend:
88 case Decl::FriendTemplate:
89 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +000090 case Decl::Captured:
Francois Pichet00c7e6c2011-08-14 03:52:19 +000091 case Decl::ClassScopeFunctionSpecialization:
David Blaikiebd483762013-05-20 04:58:53 +000092 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +000093 case Decl::ConstructorUsingShadow:
Douglas Gregor85f3f952015-07-07 03:57:15 +000094 case Decl::ObjCTypeParam:
Richard Smithda383632016-08-15 01:33:41 +000095 case Decl::Binding:
David Blaikie83d382b2011-09-23 05:06:16 +000096 llvm_unreachable("Declaration should not be in declstmts!");
Amjad Abouddc4531e2016-04-30 01:44:38 +000097 case Decl::Function: // void X();
98 case Decl::Record: // struct/union/class X;
99 case Decl::Enum: // enum X;
100 case Decl::EnumConstant: // enum ? { X = ? }
101 case Decl::CXXRecord: // struct/union/class X; [C++]
Anders Carlssonce2cd012009-12-03 17:26:31 +0000102 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
Chris Lattner43e7f312011-02-18 02:08:43 +0000103 case Decl::Label: // __label__ x;
Douglas Gregorba345522011-12-02 23:23:56 +0000104 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +0000105 case Decl::OMPThreadPrivate:
Alexey Bataev4244be22016-02-11 05:35:55 +0000106 case Decl::OMPCapturedExpr:
Michael Han84324352013-02-22 17:15:32 +0000107 case Decl::Empty:
Chris Lattner84915fa2007-06-02 04:16:21 +0000108 // None of these decls require codegen support.
109 return;
David Blaikieb7d1e1f2013-02-02 00:39:32 +0000110
David Blaikief121b932013-05-20 22:50:41 +0000111 case Decl::NamespaceAlias:
112 if (CGDebugInfo *DI = getDebugInfo())
Amjad Abouddc4531e2016-04-30 01:44:38 +0000113 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
David Blaikief121b932013-05-20 22:50:41 +0000114 return;
David Blaikiebd483762013-05-20 04:58:53 +0000115 case Decl::Using: // using X; [C++]
116 if (CGDebugInfo *DI = getDebugInfo())
Amjad Abouddc4531e2016-04-30 01:44:38 +0000117 DI->EmitUsingDecl(cast<UsingDecl>(D));
David Blaikiebd483762013-05-20 04:58:53 +0000118 return;
Richard Smith151c4562016-12-20 21:35:28 +0000119 case Decl::UsingPack:
120 for (auto *Using : cast<UsingPackDecl>(D).expansions())
121 EmitDecl(*Using);
122 return;
David Blaikie9f88fe82013-04-22 06:13:21 +0000123 case Decl::UsingDirective: // using namespace X; [C++]
124 if (CGDebugInfo *DI = getDebugInfo())
125 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
126 return;
Richard Smithbdb84f32016-07-22 23:36:59 +0000127 case Decl::Var:
128 case Decl::Decomposition: {
Daniel Dunbara7998072008-08-29 17:28:43 +0000129 const VarDecl &VD = cast<VarDecl>(D);
John McCall1c9c3fd2010-10-15 04:57:14 +0000130 assert(VD.isLocalVarDecl() &&
Daniel Dunbara7998072008-08-29 17:28:43 +0000131 "Should not see file-scope variables inside a function!");
Richard Smithda383632016-08-15 01:33:41 +0000132 EmitVarDecl(VD);
133 if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
134 for (auto *B : DD->bindings())
135 if (auto *HD = B->getHoldingVar())
136 EmitVarDecl(*HD);
137 return;
Chris Lattner84915fa2007-06-02 04:16:21 +0000138 }
Mike Stump11289f42009-09-09 15:08:12 +0000139
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000140 case Decl::OMPDeclareReduction:
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000141 return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000142
Richard Smithdda56e42011-04-15 14:24:37 +0000143 case Decl::Typedef: // typedef int X;
144 case Decl::TypeAlias: { // using X = int; [C++0x]
145 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000146 QualType Ty = TD.getUnderlyingType();
Mike Stump11289f42009-09-09 15:08:12 +0000147
Anders Carlsson5d985f52008-12-20 21:51:53 +0000148 if (Ty->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000149 EmitVariablyModifiedType(Ty);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000150 }
Daniel Dunbara7998072008-08-29 17:28:43 +0000151 }
Chris Lattner84915fa2007-06-02 04:16:21 +0000152}
Chris Lattner03df1222007-06-02 04:53:11 +0000153
John McCall1c9c3fd2010-10-15 04:57:14 +0000154/// EmitVarDecl - This method handles emission of any variable declaration
Chris Lattner03df1222007-06-02 04:53:11 +0000155/// inside a function, including static vars etc.
John McCall1c9c3fd2010-10-15 04:57:14 +0000156void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Yaxun Liu4f33b3d2017-05-15 14:47:47 +0000157 if (D.hasExternalStorage())
158 // Don't emit it now, allow it to be emitted lazily on its first use.
159 return;
160
161 // Some function-scope variable does not have static storage but still
162 // needs to be emitted like a static variable, e.g. a function-scope
163 // variable in constant address space in OpenCL.
164 if (D.getStorageDuration() != SD_Automatic) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000165 llvm::GlobalValue::LinkageTypes Linkage =
David Majnemer27d69db2014-04-28 22:17:59 +0000166 CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000167
David Majnemer27d69db2014-04-28 22:17:59 +0000168 // FIXME: We need to force the emission/use of a guard variable for
169 // some variables even if we can constant-evaluate them because
170 // we can't guarantee every translation unit will constant-evaluate them.
Eric Christopher31ab1302011-08-23 22:38:00 +0000171
John McCall1c9c3fd2010-10-15 04:57:14 +0000172 return EmitStaticVarDecl(D, Linkage);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000173 }
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000174
Anastasia Stulovabcea6962015-09-30 14:08:20 +0000175 if (D.getType().getAddressSpace() == LangAS::opencl_local)
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000176 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
177
178 assert(D.hasLocalStorage());
179 return EmitAutoVarDecl(D);
Chris Lattner03df1222007-06-02 04:53:11 +0000180}
181
Reid Kleckner453e0562014-10-08 01:07:54 +0000182static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
183 if (CGM.getLangOpts().CPlusPlus)
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000184 return CGM.getMangledName(&D).str();
185
Reid Kleckner453e0562014-10-08 01:07:54 +0000186 // If this isn't C++, we don't need a mangled name, just a pretty one.
187 assert(!D.isExternallyVisible() && "name shouldn't matter");
188 std::string ContextName;
189 const DeclContext *DC = D.getDeclContext();
Alexey Bataev43f74392015-05-07 06:28:46 +0000190 if (auto *CD = dyn_cast<CapturedDecl>(DC))
191 DC = cast<DeclContext>(CD->getNonClosureContext());
Reid Kleckner453e0562014-10-08 01:07:54 +0000192 if (const auto *FD = dyn_cast<FunctionDecl>(DC))
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000193 ContextName = CGM.getMangledName(FD);
Reid Kleckner453e0562014-10-08 01:07:54 +0000194 else if (const auto *BD = dyn_cast<BlockDecl>(DC))
195 ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
196 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
197 ContextName = OMD->getSelector().getAsString();
Chris Lattnere99c1102009-12-05 08:22:11 +0000198 else
David Blaikie83d382b2011-09-23 05:06:16 +0000199 llvm_unreachable("Unknown context for static var decl");
Eric Christopher31ab1302011-08-23 22:38:00 +0000200
Reid Kleckner453e0562014-10-08 01:07:54 +0000201 ContextName += "." + D.getNameAsString();
202 return ContextName;
Chris Lattnere99c1102009-12-05 08:22:11 +0000203}
204
Reid Kleckner453e0562014-10-08 01:07:54 +0000205llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
206 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
207 // In general, we don't always emit static var decls once before we reference
208 // them. It is possible to reference them before emitting the function that
209 // contains them, and it is possible to emit the containing function multiple
210 // times.
211 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
212 return ExistingGV;
213
Chris Lattnerfc4379f2008-04-06 23:10:54 +0000214 QualType Ty = D.getType();
Eli Friedmana682d392008-02-15 12:20:59 +0000215 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begemanfaae0812008-04-19 04:17:09 +0000216
Benjamin Kramerddbb2b82011-11-20 21:05:04 +0000217 // Use the label if the variable is renamed with the asm-label extension.
218 std::string Name;
Benjamin Kramer5642e192011-11-21 15:47:23 +0000219 if (D.hasAttr<AsmLabelAttr>())
Reid Kleckner453e0562014-10-08 01:07:54 +0000220 Name = getMangledName(&D);
Benjamin Kramer5642e192011-11-21 15:47:23 +0000221 else
Reid Kleckner453e0562014-10-08 01:07:54 +0000222 Name = getStaticDeclName(*this, D);
Nate Begemanfaae0812008-04-19 04:17:09 +0000223
Reid Kleckner453e0562014-10-08 01:07:54 +0000224 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
Yaxun Liucbf647c2017-07-08 13:24:52 +0000225 unsigned AS = GetGlobalVarAddressSpace(&D);
226 unsigned TargetAS = getContext().getTargetAddressSpace(AS);
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000227
228 // Local address space cannot have an initializer.
229 llvm::Constant *Init = nullptr;
230 if (Ty.getAddressSpace() != LangAS::opencl_local)
231 Init = EmitNullConstant(Ty);
232 else
233 Init = llvm::UndefValue::get(LTy);
234
Yaxun Liucbf647c2017-07-08 13:24:52 +0000235 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
236 getModule(), LTy, Ty.isConstant(getContext()), Linkage, Init, Name,
237 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
Ken Dyck160146e2010-01-27 17:10:57 +0000238 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Reid Kleckner453e0562014-10-08 01:07:54 +0000239 setGlobalVisibility(GV, &D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000240
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +0000241 if (supportsCOMDAT() && GV->isWeakForLinker())
242 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Rafael Espindola0d4fb982015-01-12 22:13:53 +0000243
Richard Smithfd3834f2013-04-13 02:43:54 +0000244 if (D.getTLSKind())
Reid Kleckner453e0562014-10-08 01:07:54 +0000245 setTLSMode(GV, D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000246
Hans Wennborgef2272c2014-06-18 15:55:13 +0000247 if (D.isExternallyVisible()) {
248 if (D.hasAttr<DLLImportAttr>())
249 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
250 else if (D.hasAttr<DLLExportAttr>())
251 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
252 }
253
Eli Benderskycb399432014-03-24 22:05:38 +0000254 // Make sure the result is of the correct type.
Yaxun Liucbf647c2017-07-08 13:24:52 +0000255 unsigned ExpectedAS = Ty.getAddressSpace();
Reid Kleckner453e0562014-10-08 01:07:54 +0000256 llvm::Constant *Addr = GV;
Yaxun Liucbf647c2017-07-08 13:24:52 +0000257 if (AS != ExpectedAS) {
258 Addr = getTargetCodeGenInfo().performAddrSpaceCast(
259 *this, GV, AS, ExpectedAS,
260 LTy->getPointerTo(getContext().getTargetAddressSpace(ExpectedAS)));
Eli Benderskycb399432014-03-24 22:05:38 +0000261 }
262
Reid Kleckner453e0562014-10-08 01:07:54 +0000263 setStaticLocalDeclAddress(&D, Addr);
264
265 // Ensure that the static local gets initialized by making sure the parent
266 // function gets emitted eventually.
267 const Decl *DC = cast<Decl>(D.getDeclContext());
268
269 // We can't name blocks or captured statements directly, so try to emit their
270 // parents.
271 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
272 DC = DC->getNonClosureContext();
273 // FIXME: Ensure that global blocks get emitted.
274 if (!DC)
275 return Addr;
276 }
277
278 GlobalDecl GD;
279 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
280 GD = GlobalDecl(CD, Ctor_Base);
281 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
282 GD = GlobalDecl(DD, Dtor_Base);
283 else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
284 GD = GlobalDecl(FD);
285 else {
286 // Don't do anything for Obj-C method decls or global closures. We should
287 // never defer them.
288 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
289 }
290 if (GD.getDecl())
291 (void)GetAddrOfGlobal(GD);
292
293 return Addr;
Daniel Dunbar22a87f92009-02-25 19:24:29 +0000294}
295
Richard Smith6331c402012-02-13 22:16:19 +0000296/// hasNontrivialDestruction - Determine whether a type's destruction is
297/// non-trivial. If so, and the variable uses static initialization, we must
298/// register its destructor to run on exit.
299static bool hasNontrivialDestruction(QualType T) {
300 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
301 return RD && !RD->hasTrivialDestructor();
302}
303
Chandler Carruth84537952012-03-30 19:44:53 +0000304/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
305/// global variable that has already been created for it. If the initializer
306/// has a different type than GV does, this may free GV and return a different
307/// one. Otherwise it just returns GV.
308llvm::GlobalVariable *
John McCall1c9c3fd2010-10-15 04:57:14 +0000309CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
Chandler Carruth84537952012-03-30 19:44:53 +0000310 llvm::GlobalVariable *GV) {
John McCallde0fe072017-08-15 21:42:52 +0000311 ConstantEmitter emitter(*this);
312 llvm::Constant *Init = emitter.tryEmitForInitializer(D);
John McCall70013b62010-07-15 23:40:35 +0000313
Chris Lattnere99c1102009-12-05 08:22:11 +0000314 // If constant emission failed, then this should be a C++ static
315 // initializer.
Chandler Carruth84537952012-03-30 19:44:53 +0000316 if (!Init) {
Richard Smith9c6890a2012-11-01 22:30:59 +0000317 if (!getLangOpts().CPlusPlus)
Chris Lattnere99c1102009-12-05 08:22:11 +0000318 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
Matthias Braun44bfe032017-01-10 17:43:01 +0000319 else if (HaveInsertPoint()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000320 // Since we have a static initializer, this global variable can't
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000321 // be constant.
Chandler Carruth84537952012-03-30 19:44:53 +0000322 GV->setConstant(false);
John McCall68ff0372010-09-08 01:44:27 +0000323
Chandler Carruth84537952012-03-30 19:44:53 +0000324 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000325 }
Chandler Carruth84537952012-03-30 19:44:53 +0000326 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000327 }
John McCall70013b62010-07-15 23:40:35 +0000328
Chris Lattnere99c1102009-12-05 08:22:11 +0000329 // The initializer may differ in type from the global. Rewrite
330 // the global to match the initializer. (We have to do this
331 // because some types, like unions, can't be completely represented
332 // in the LLVM type system.)
Chandler Carruth84537952012-03-30 19:44:53 +0000333 if (GV->getType()->getElementType() != Init->getType()) {
334 llvm::GlobalVariable *OldGV = GV;
335
336 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
337 OldGV->isConstant(),
338 OldGV->getLinkage(), Init, "",
339 /*InsertBefore*/ OldGV,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +0000340 OldGV->getThreadLocalMode(),
Chandler Carruth84537952012-03-30 19:44:53 +0000341 CGM.getContext().getTargetAddressSpace(D.getType()));
342 GV->setVisibility(OldGV->getVisibility());
Reid Klecknereab97d32015-07-20 20:35:30 +0000343 GV->setComdat(OldGV->getComdat());
Eric Christopher31ab1302011-08-23 22:38:00 +0000344
Chris Lattnere99c1102009-12-05 08:22:11 +0000345 // Steal the name of the old global
Chandler Carruth84537952012-03-30 19:44:53 +0000346 GV->takeName(OldGV);
Eric Christopher31ab1302011-08-23 22:38:00 +0000347
Chris Lattnere99c1102009-12-05 08:22:11 +0000348 // Replace all uses of the old global with the new global
Chandler Carruth84537952012-03-30 19:44:53 +0000349 llvm::Constant *NewPtrForOldDecl =
350 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
351 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eric Christopher31ab1302011-08-23 22:38:00 +0000352
Chris Lattnere99c1102009-12-05 08:22:11 +0000353 // Erase the old global, since it is no longer used.
Chandler Carruth84537952012-03-30 19:44:53 +0000354 OldGV->eraseFromParent();
Chris Lattnere99c1102009-12-05 08:22:11 +0000355 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000356
Chandler Carruth84537952012-03-30 19:44:53 +0000357 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
358 GV->setInitializer(Init);
Richard Smith6331c402012-02-13 22:16:19 +0000359
John McCallde0fe072017-08-15 21:42:52 +0000360 emitter.finalize(GV);
361
Matthias Braun44bfe032017-01-10 17:43:01 +0000362 if (hasNontrivialDestruction(D.getType()) && HaveInsertPoint()) {
Richard Smith6331c402012-02-13 22:16:19 +0000363 // We have a constant initializer, but a nontrivial destructor. We still
364 // need to perform a guarded "initialization" in order to register the
Richard Smithe070fd22012-02-17 06:48:11 +0000365 // destructor.
Chandler Carruth84537952012-03-30 19:44:53 +0000366 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
Richard Smith6331c402012-02-13 22:16:19 +0000367 }
368
Chandler Carruth84537952012-03-30 19:44:53 +0000369 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000370}
371
John McCall1c9c3fd2010-10-15 04:57:14 +0000372void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000373 llvm::GlobalValue::LinkageTypes Linkage) {
John McCallb88a5662012-03-30 21:00:39 +0000374 // Check to see if we already have a global variable for this
375 // declaration. This can happen when double-emitting function
376 // bodies, e.g. with complete and base constructors.
Reid Kleckner453e0562014-10-08 01:07:54 +0000377 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
John McCall7f416cc2015-09-08 08:05:57 +0000378 CharUnits alignment = getContext().getDeclAlign(&D);
Daniel Dunbara374e602009-02-25 19:45:19 +0000379
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000380 // Store into LocalDeclMap before generating initializer to handle
381 // circular references.
John McCall7f416cc2015-09-08 08:05:57 +0000382 setAddrOfLocalVar(&D, Address(addr, alignment));
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000383
John McCall4a39ab82010-05-04 20:45:42 +0000384 // We can't have a VLA here, but we can have a pointer to a VLA,
385 // even though that doesn't really make any sense.
Eli Friedmanbc633be2009-04-20 03:54:15 +0000386 // Make sure to evaluate VLA bounds now so that we have them for later.
387 if (D.getType()->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000388 EmitVariablyModifiedType(D.getType());
Eric Christopher31ab1302011-08-23 22:38:00 +0000389
John McCallb88a5662012-03-30 21:00:39 +0000390 // Save the type in case adding the initializer forces a type change.
391 llvm::Type *expectedType = addr->getType();
Eli Friedmanbc633be2009-04-20 03:54:15 +0000392
Eli Benderskycb399432014-03-24 22:05:38 +0000393 llvm::GlobalVariable *var =
394 cast<llvm::GlobalVariable>(addr->stripPointerCasts());
Artem Belevich4d430ba2016-05-09 22:09:56 +0000395
396 // CUDA's local and local static __shared__ variables should not
397 // have any non-empty initializers. This is ensured by Sema.
398 // Whatever initializer such variable may have when it gets here is
399 // a no-op and should not be emitted.
400 bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
401 D.hasAttr<CUDASharedAttr>();
Chris Lattnere99c1102009-12-05 08:22:11 +0000402 // If this value has an initializer, emit it.
Artem Belevich4d430ba2016-05-09 22:09:56 +0000403 if (D.getInit() && !isCudaSharedVar)
John McCallb88a5662012-03-30 21:00:39 +0000404 var = AddInitializerToStaticVarDecl(D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000405
John McCall7f416cc2015-09-08 08:05:57 +0000406 var->setAlignment(alignment.getQuantity());
Chris Lattner4d941092010-03-10 23:59:59 +0000407
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000408 if (D.hasAttr<AnnotateAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000409 CGM.AddGlobalAnnotations(&D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000410
Javed Absar2a67c9e2017-06-05 10:11:57 +0000411 if (auto *SA = D.getAttr<PragmaClangBSSSectionAttr>())
412 var->addAttribute("bss-section", SA->getName());
413 if (auto *SA = D.getAttr<PragmaClangDataSectionAttr>())
414 var->addAttribute("data-section", SA->getName());
415 if (auto *SA = D.getAttr<PragmaClangRodataSectionAttr>())
416 var->addAttribute("rodata-section", SA->getName());
417
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000418 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000419 var->setSection(SA->getName());
Mike Stump11289f42009-09-09 15:08:12 +0000420
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000421 if (D.hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +0000422 CGM.addUsedGlobal(var);
Daniel Dunbar128a1382009-02-13 22:08:43 +0000423
Chandler Carruth84537952012-03-30 19:44:53 +0000424 // We may have to cast the constant because of the initializer
425 // mismatch above.
426 //
427 // FIXME: It is really dangerous to store this in the map; if anyone
428 // RAUW's the GV uses of this constant will be invalid.
Eli Benderskycb399432014-03-24 22:05:38 +0000429 llvm::Constant *castedAddr =
430 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
John McCall7f416cc2015-09-08 08:05:57 +0000431 if (var != castedAddr)
432 LocalDeclMap.find(&D)->second = Address(castedAddr, alignment);
John McCallb88a5662012-03-30 21:00:39 +0000433 CGM.setStaticLocalDeclAddress(&D, castedAddr);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000434
Alexey Samsonov4b8de112014-08-01 21:35:28 +0000435 CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000436
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000437 // Emit global variable debug descriptor for static vars.
Anders Carlsson63784f42009-02-13 08:11:52 +0000438 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov74a38682012-05-04 07:39:27 +0000439 if (DI &&
Benjamin Kramer8c305922016-02-02 11:06:51 +0000440 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
Daniel Dunbarb9fd9022008-10-17 16:15:48 +0000441 DI->setLocation(D.getLocation());
John McCallb88a5662012-03-30 21:00:39 +0000442 DI->EmitGlobalVariable(var, &D);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000443 }
Anders Carlssonf94cd1f2007-10-17 00:52:43 +0000444}
Mike Stump11289f42009-09-09 15:08:12 +0000445
John McCall2b7fc382010-07-13 20:32:21 +0000446namespace {
David Blaikie7e70d682015-08-18 22:40:54 +0000447 struct DestroyObject final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000448 DestroyObject(Address addr, QualType type,
John McCall178360e2011-07-11 08:38:19 +0000449 CodeGenFunction::Destroyer *destroyer,
450 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +0000451 : addr(addr), type(type), destroyer(destroyer),
John McCall178360e2011-07-11 08:38:19 +0000452 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall2b7fc382010-07-13 20:32:21 +0000453
John McCall7f416cc2015-09-08 08:05:57 +0000454 Address addr;
John McCall82fe67b2011-07-09 01:37:26 +0000455 QualType type;
Peter Collingbourne1425b452012-01-26 03:33:36 +0000456 CodeGenFunction::Destroyer *destroyer;
John McCall178360e2011-07-11 08:38:19 +0000457 bool useEHCleanupForArray;
John McCall2b7fc382010-07-13 20:32:21 +0000458
Craig Topper4f12f102014-03-12 06:41:41 +0000459 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +0000460 // Don't use an EH cleanup recursively from an EH cleanup.
John McCall30317fd2011-07-12 20:27:29 +0000461 bool useEHCleanupForArray =
462 flags.isForNormalCleanup() && this->useEHCleanupForArray;
John McCall178360e2011-07-11 08:38:19 +0000463
464 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
John McCall2b7fc382010-07-13 20:32:21 +0000465 }
466 };
467
David Blaikie7e70d682015-08-18 22:40:54 +0000468 struct DestroyNRVOVariable final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000469 DestroyNRVOVariable(Address addr,
John McCall82fe67b2011-07-09 01:37:26 +0000470 const CXXDestructorDecl *Dtor,
471 llvm::Value *NRVOFlag)
472 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
John McCall2b7fc382010-07-13 20:32:21 +0000473
474 const CXXDestructorDecl *Dtor;
475 llvm::Value *NRVOFlag;
John McCall7f416cc2015-09-08 08:05:57 +0000476 Address Loc;
John McCall2b7fc382010-07-13 20:32:21 +0000477
Craig Topper4f12f102014-03-12 06:41:41 +0000478 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall2b7fc382010-07-13 20:32:21 +0000479 // Along the exceptions path we always execute the dtor.
John McCall30317fd2011-07-12 20:27:29 +0000480 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
John McCall2b7fc382010-07-13 20:32:21 +0000481
Craig Topper8a13c412014-05-21 05:09:00 +0000482 llvm::BasicBlock *SkipDtorBB = nullptr;
John McCall2b7fc382010-07-13 20:32:21 +0000483 if (NRVO) {
484 // If we exited via NRVO, we skip the destructor call.
485 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
486 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
John McCall7f416cc2015-09-08 08:05:57 +0000487 llvm::Value *DidNRVO =
488 CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
John McCall2b7fc382010-07-13 20:32:21 +0000489 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
490 CGF.EmitBlock(RunDtorBB);
491 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000492
John McCall2b7fc382010-07-13 20:32:21 +0000493 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +0000494 /*ForVirtualBase=*/false,
495 /*Delegating=*/false,
496 Loc);
John McCall2b7fc382010-07-13 20:32:21 +0000497
498 if (NRVO) CGF.EmitBlock(SkipDtorBB);
499 }
500 };
John McCall2b7fc382010-07-13 20:32:21 +0000501
David Blaikie7e70d682015-08-18 22:40:54 +0000502 struct CallStackRestore final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000503 Address Stack;
504 CallStackRestore(Address Stack) : Stack(Stack) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000505 void Emit(CodeGenFunction &CGF, Flags flags) override {
Benjamin Kramer76399eb2011-09-27 21:06:10 +0000506 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
John McCalla464ff92010-07-21 06:13:08 +0000507 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
508 CGF.Builder.CreateCall(F, V);
509 }
510 };
511
David Blaikie7e70d682015-08-18 22:40:54 +0000512 struct ExtendGCLifetime final : EHScopeStack::Cleanup {
John McCall1bd25562011-06-24 23:21:27 +0000513 const VarDecl &Var;
514 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
515
Craig Topper4f12f102014-03-12 06:41:41 +0000516 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1bd25562011-06-24 23:21:27 +0000517 // Compute the address of the local variable, in case it's a
518 // byref or something.
John McCall113bee02012-03-10 09:33:50 +0000519 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
520 Var.getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +0000521 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
522 SourceLocation());
John McCall1bd25562011-06-24 23:21:27 +0000523 CGF.EmitExtendGCLifetime(value);
524 }
525 };
526
David Blaikie7e70d682015-08-18 22:40:54 +0000527 struct CallCleanupFunction final : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000528 llvm::Constant *CleanupFn;
529 const CGFunctionInfo &FnInfo;
John McCalla464ff92010-07-21 06:13:08 +0000530 const VarDecl &Var;
Eric Christopher31ab1302011-08-23 22:38:00 +0000531
John McCalla464ff92010-07-21 06:13:08 +0000532 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCallc533cb72011-02-22 06:44:22 +0000533 const VarDecl *Var)
534 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalla464ff92010-07-21 06:13:08 +0000535
Craig Topper4f12f102014-03-12 06:41:41 +0000536 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall113bee02012-03-10 09:33:50 +0000537 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
538 Var.getType(), VK_LValue, SourceLocation());
John McCallc533cb72011-02-22 06:44:22 +0000539 // Compute the address of the local variable, in case it's a byref
540 // or something.
John McCall7f416cc2015-09-08 08:05:57 +0000541 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer();
John McCallc533cb72011-02-22 06:44:22 +0000542
John McCalla464ff92010-07-21 06:13:08 +0000543 // In some cases, the type of the function argument will be different from
544 // the type of the pointer. An example of this is
545 // void f(void* arg);
546 // __attribute__((cleanup(f))) void *g;
547 //
548 // To fix this we insert a bitcast here.
549 QualType ArgTy = FnInfo.arg_begin()->type;
550 llvm::Value *Arg =
551 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
552
553 CallArgList Args;
Eli Friedman43dca6a2011-05-02 17:57:46 +0000554 Args.add(RValue::get(Arg),
555 CGF.getContext().getPointerType(Var.getType()));
John McCallb92ab1a2016-10-26 23:46:34 +0000556 auto Callee = CGCallee::forDirect(CleanupFn);
557 CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
John McCalla464ff92010-07-21 06:13:08 +0000558 }
559 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000560} // end anonymous namespace
John McCalla464ff92010-07-21 06:13:08 +0000561
John McCall31168b02011-06-15 23:02:42 +0000562/// EmitAutoVarWithLifetime - Does the setup required for an automatic
563/// variable with lifetime.
564static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
John McCall7f416cc2015-09-08 08:05:57 +0000565 Address addr,
John McCall31168b02011-06-15 23:02:42 +0000566 Qualifiers::ObjCLifetime lifetime) {
567 switch (lifetime) {
568 case Qualifiers::OCL_None:
569 llvm_unreachable("present but none");
570
571 case Qualifiers::OCL_ExplicitNone:
572 // nothing to do
573 break;
574
575 case Qualifiers::OCL_Strong: {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000576 CodeGenFunction::Destroyer *destroyer =
John McCall4bd0fb12011-07-12 16:41:08 +0000577 (var.hasAttr<ObjCPreciseLifetimeAttr>()
578 ? CodeGenFunction::destroyARCStrongPrecise
579 : CodeGenFunction::destroyARCStrongImprecise);
580
581 CleanupKind cleanupKind = CGF.getARCCleanupKind();
582 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
583 cleanupKind & EHCleanup);
John McCall31168b02011-06-15 23:02:42 +0000584 break;
585 }
586 case Qualifiers::OCL_Autoreleasing:
587 // nothing to do
588 break;
Eric Christopher31ab1302011-08-23 22:38:00 +0000589
John McCall31168b02011-06-15 23:02:42 +0000590 case Qualifiers::OCL_Weak:
591 // __weak objects always get EH cleanups; otherwise, exceptions
592 // could cause really nasty crashes instead of mere leaks.
John McCall4bd0fb12011-07-12 16:41:08 +0000593 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
594 CodeGenFunction::destroyARCWeak,
595 /*useEHCleanup*/ true);
John McCall31168b02011-06-15 23:02:42 +0000596 break;
597 }
598}
599
600static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
601 if (const Expr *e = dyn_cast<Expr>(s)) {
602 // Skip the most common kinds of expressions that make
603 // hierarchy-walking expensive.
604 s = e = e->IgnoreParenCasts();
605
606 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
607 return (ref->getDecl() == &var);
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000608 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
609 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +0000610 for (const auto &I : block->captures()) {
611 if (I.getVariable() == &var)
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000612 return true;
613 }
614 }
John McCall31168b02011-06-15 23:02:42 +0000615 }
616
Benjamin Kramer642f1732015-07-02 21:03:14 +0000617 for (const Stmt *SubStmt : s->children())
618 // SubStmt might be null; as in missing decl or conditional of an if-stmt.
619 if (SubStmt && isAccessedBy(var, SubStmt))
John McCall31168b02011-06-15 23:02:42 +0000620 return true;
621
622 return false;
623}
624
625static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
626 if (!decl) return false;
627 if (!isa<VarDecl>(decl)) return false;
628 const VarDecl *var = cast<VarDecl>(decl);
629 return isAccessedBy(*var, e);
630}
631
John McCallf8a9b662015-10-21 18:06:31 +0000632static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
633 const LValue &destLV, const Expr *init) {
John McCall0204e342015-11-16 22:11:41 +0000634 bool needsCast = false;
635
John McCallf8a9b662015-10-21 18:06:31 +0000636 while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
637 switch (castExpr->getCastKind()) {
638 // Look through casts that don't require representation changes.
639 case CK_NoOp:
640 case CK_BitCast:
641 case CK_BlockPointerToObjCPointerCast:
John McCall0204e342015-11-16 22:11:41 +0000642 needsCast = true;
John McCallf8a9b662015-10-21 18:06:31 +0000643 break;
644
645 // If we find an l-value to r-value cast from a __weak variable,
646 // emit this operation as a copy or move.
647 case CK_LValueToRValue: {
648 const Expr *srcExpr = castExpr->getSubExpr();
649 if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
650 return false;
651
652 // Emit the source l-value.
653 LValue srcLV = CGF.EmitLValue(srcExpr);
654
John McCall0204e342015-11-16 22:11:41 +0000655 // Handle a formal type change to avoid asserting.
656 auto srcAddr = srcLV.getAddress();
657 if (needsCast) {
658 srcAddr = CGF.Builder.CreateElementBitCast(srcAddr,
659 destLV.getAddress().getElementType());
660 }
661
John McCallf8a9b662015-10-21 18:06:31 +0000662 // If it was an l-value, use objc_copyWeak.
663 if (srcExpr->getValueKind() == VK_LValue) {
John McCall0204e342015-11-16 22:11:41 +0000664 CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr);
John McCallf8a9b662015-10-21 18:06:31 +0000665 } else {
666 assert(srcExpr->getValueKind() == VK_XValue);
John McCall0204e342015-11-16 22:11:41 +0000667 CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr);
John McCallf8a9b662015-10-21 18:06:31 +0000668 }
669 return true;
670 }
671
672 // Stop at anything else.
673 default:
674 return false;
675 }
676
677 init = castExpr->getSubExpr();
John McCallf8a9b662015-10-21 18:06:31 +0000678 }
679 return false;
680}
681
John McCall1553b192011-06-16 04:16:24 +0000682static void drillIntoBlockVariable(CodeGenFunction &CGF,
683 LValue &lvalue,
684 const VarDecl *var) {
John McCall7f416cc2015-09-08 08:05:57 +0000685 lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var));
John McCall1553b192011-06-16 04:16:24 +0000686}
687
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000688void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS,
689 SourceLocation Loc) {
690 if (!SanOpts.has(SanitizerKind::NullabilityAssign))
691 return;
692
693 auto Nullability = LHS.getType()->getNullability(getContext());
694 if (!Nullability || *Nullability != NullabilityKind::NonNull)
695 return;
696
697 // Check if the right hand side of the assignment is nonnull, if the left
698 // hand side must be nonnull.
699 SanitizerScope SanScope(this);
700 llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS);
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000701 llvm::Constant *StaticData[] = {
702 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(LHS.getType()),
Simon Pilgrim2df19982017-03-14 21:43:52 +0000703 llvm::ConstantInt::get(Int8Ty, 0), // The LogAlignment info is unused.
Vedant Kumar2b9f48a2017-03-14 16:48:29 +0000704 llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)};
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000705 EmitCheck({{IsNotNull, SanitizerKind::NullabilityAssign}},
706 SanitizerHandler::TypeMismatch, StaticData, RHS);
707}
708
David Blaikie73ca5692014-12-09 00:32:22 +0000709void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +0000710 LValue lvalue, bool capturedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000711 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +0000712 if (!lifetime) {
713 llvm::Value *value = EmitScalarExpr(init);
John McCall1553b192011-06-16 04:16:24 +0000714 if (capturedByInit)
715 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000716 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
David Blaikie66e41972015-01-14 07:38:27 +0000717 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
John McCall31168b02011-06-15 23:02:42 +0000718 return;
719 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000720
Fariborz Jahaniana5a469e2014-03-14 15:40:54 +0000721 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
722 init = DIE->getExpr();
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000723
John McCall31168b02011-06-15 23:02:42 +0000724 // If we're emitting a value with lifetime, we have to do the
725 // initialization *before* we leave the cleanup scopes.
John McCall08ef4662011-11-10 08:15:53 +0000726 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
727 enterFullExpression(ewc);
John McCall31168b02011-06-15 23:02:42 +0000728 init = ewc->getSubExpr();
John McCall08ef4662011-11-10 08:15:53 +0000729 }
730 CodeGenFunction::RunCleanupsScope Scope(*this);
John McCall31168b02011-06-15 23:02:42 +0000731
732 // We have to maintain the illusion that the variable is
733 // zero-initialized. If the variable might be accessed in its
734 // initializer, zero-initialize before running the initializer, then
735 // actually perform the initialization with an assign.
736 bool accessedByInit = false;
737 if (lifetime != Qualifiers::OCL_ExplicitNone)
John McCallb726a552011-07-28 07:23:35 +0000738 accessedByInit = (capturedByInit || isAccessedBy(D, init));
John McCall31168b02011-06-15 23:02:42 +0000739 if (accessedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000740 LValue tempLV = lvalue;
John McCall31168b02011-06-15 23:02:42 +0000741 // Drill down to the __block object if necessary.
John McCall31168b02011-06-15 23:02:42 +0000742 if (capturedByInit) {
743 // We can use a simple GEP for this because it can't have been
744 // moved yet.
John McCall7f416cc2015-09-08 08:05:57 +0000745 tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(),
746 cast<VarDecl>(D),
747 /*follow*/ false));
John McCall31168b02011-06-15 23:02:42 +0000748 }
749
John McCall7f416cc2015-09-08 08:05:57 +0000750 auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType());
Yaxun Liu402804b2016-12-15 08:09:08 +0000751 llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());
Eric Christopher31ab1302011-08-23 22:38:00 +0000752
John McCall31168b02011-06-15 23:02:42 +0000753 // If __weak, we want to use a barrier under certain conditions.
754 if (lifetime == Qualifiers::OCL_Weak)
John McCall1553b192011-06-16 04:16:24 +0000755 EmitARCInitWeak(tempLV.getAddress(), zero);
John McCall31168b02011-06-15 23:02:42 +0000756
757 // Otherwise just do a simple store.
758 else
David Chisnallfa35df62012-01-16 17:27:18 +0000759 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000760 }
761
762 // Emit the initializer.
Craig Topper8a13c412014-05-21 05:09:00 +0000763 llvm::Value *value = nullptr;
John McCall31168b02011-06-15 23:02:42 +0000764
765 switch (lifetime) {
766 case Qualifiers::OCL_None:
767 llvm_unreachable("present but none");
768
769 case Qualifiers::OCL_ExplicitNone:
John McCalle399e5b2016-01-27 18:32:30 +0000770 value = EmitARCUnsafeUnretainedScalarExpr(init);
John McCall31168b02011-06-15 23:02:42 +0000771 break;
772
773 case Qualifiers::OCL_Strong: {
774 value = EmitARCRetainScalarExpr(init);
775 break;
776 }
777
778 case Qualifiers::OCL_Weak: {
John McCallf8a9b662015-10-21 18:06:31 +0000779 // If it's not accessed by the initializer, try to emit the
780 // initialization with a copy or move.
781 if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
782 return;
783 }
784
John McCall31168b02011-06-15 23:02:42 +0000785 // No way to optimize a producing initializer into this. It's not
786 // worth optimizing for, because the value will immediately
787 // disappear in the common case.
788 value = EmitScalarExpr(init);
789
John McCall1553b192011-06-16 04:16:24 +0000790 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000791 if (accessedByInit)
John McCall1553b192011-06-16 04:16:24 +0000792 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +0000793 else
John McCall1553b192011-06-16 04:16:24 +0000794 EmitARCInitWeak(lvalue.getAddress(), value);
John McCall31168b02011-06-15 23:02:42 +0000795 return;
796 }
797
798 case Qualifiers::OCL_Autoreleasing:
799 value = EmitARCRetainAutoreleaseScalarExpr(init);
800 break;
801 }
802
John McCall1553b192011-06-16 04:16:24 +0000803 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000804
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000805 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
806
John McCall31168b02011-06-15 23:02:42 +0000807 // If the variable might have been accessed by its initializer, we
808 // might have to initialize with a barrier. We have to do this for
809 // both __weak and __strong, but __weak got filtered out above.
810 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000811 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
David Chisnallfa35df62012-01-16 17:27:18 +0000812 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCallcdda29c2013-03-13 03:10:54 +0000813 EmitARCRelease(oldValue, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +0000814 return;
815 }
816
David Chisnallfa35df62012-01-16 17:27:18 +0000817 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000818}
Chris Lattnerb85025f2010-12-01 02:05:19 +0000819
820/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
821/// non-zero parts of the specified initializer with equal or fewer than
822/// NumStores scalar stores.
823static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
824 unsigned &NumStores) {
Chris Lattnere6af8862010-12-02 01:58:41 +0000825 // Zero and Undef never requires any extra stores.
826 if (isa<llvm::ConstantAggregateZero>(Init) ||
827 isa<llvm::ConstantPointerNull>(Init) ||
828 isa<llvm::UndefValue>(Init))
829 return true;
830 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
831 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
832 isa<llvm::ConstantExpr>(Init))
833 return Init->isNullValue() || NumStores--;
834
835 // See if we can emit each element.
836 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
837 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
838 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
839 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
840 return false;
841 }
842 return true;
843 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000844
Chris Lattner236b3572012-01-31 04:36:19 +0000845 if (llvm::ConstantDataSequential *CDS =
846 dyn_cast<llvm::ConstantDataSequential>(Init)) {
847 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
848 llvm::Constant *Elt = CDS->getElementAsConstant(i);
849 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
850 return false;
851 }
852 return true;
853 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000854
Chris Lattnerb85025f2010-12-01 02:05:19 +0000855 // Anything else is hard and scary.
856 return false;
857}
858
859/// emitStoresForInitAfterMemset - For inits that
860/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
861/// stores that would be required.
862static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
John McCallc533cb72011-02-22 06:44:22 +0000863 bool isVolatile, CGBuilderTy &Builder) {
Benjamin Kramer29f9a002012-08-27 22:07:02 +0000864 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
865 "called emitStoresForInitAfterMemset for zero or undef value.");
Eric Christopher31ab1302011-08-23 22:38:00 +0000866
Chris Lattnere6af8862010-12-02 01:58:41 +0000867 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
868 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
869 isa<llvm::ConstantExpr>(Init)) {
John McCall7f416cc2015-09-08 08:05:57 +0000870 Builder.CreateDefaultAlignedStore(Init, Loc, isVolatile);
Chris Lattner236b3572012-01-31 04:36:19 +0000871 return;
872 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000873
874 if (llvm::ConstantDataSequential *CDS =
875 dyn_cast<llvm::ConstantDataSequential>(Init)) {
Chris Lattner236b3572012-01-31 04:36:19 +0000876 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
877 llvm::Constant *Elt = CDS->getElementAsConstant(i);
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000878
879 // If necessary, get a pointer to the element and emit it.
880 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
David Blaikie17ea2662015-04-04 21:07:17 +0000881 emitStoresForInitAfterMemset(
882 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
883 isVolatile, Builder);
Chris Lattner236b3572012-01-31 04:36:19 +0000884 }
Chris Lattnere6af8862010-12-02 01:58:41 +0000885 return;
886 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000887
Chris Lattnere6af8862010-12-02 01:58:41 +0000888 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
889 "Unknown value type!");
Eric Christopher31ab1302011-08-23 22:38:00 +0000890
Chris Lattnere6af8862010-12-02 01:58:41 +0000891 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
892 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000893
894 // If necessary, get a pointer to the element and emit it.
895 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
David Blaikie17ea2662015-04-04 21:07:17 +0000896 emitStoresForInitAfterMemset(
897 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
898 isVolatile, Builder);
Chris Lattnere6af8862010-12-02 01:58:41 +0000899 }
Chris Lattnerb85025f2010-12-01 02:05:19 +0000900}
901
Chris Lattnerb85025f2010-12-01 02:05:19 +0000902/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
903/// plus some stores to initialize a local variable instead of using a memcpy
904/// from a constant global. It is beneficial to use memset if the global is all
905/// zeros, or mostly zeros and large.
906static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
907 uint64_t GlobalSize) {
908 // If a global is all zeros, always use a memset.
909 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
910
Chris Lattnerb85025f2010-12-01 02:05:19 +0000911 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
912 // do it if it will require 6 or fewer scalar stores.
913 // TODO: Should budget depends on the size? Avoiding a large global warrants
914 // plopping in more stores.
915 unsigned StoreBudget = 6;
916 uint64_t SizeLimit = 32;
Eric Christopher31ab1302011-08-23 22:38:00 +0000917
918 return GlobalSize > SizeLimit &&
Chris Lattnerb85025f2010-12-01 02:05:19 +0000919 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
920}
921
Nick Lewycky8a7d90b2010-12-30 20:21:55 +0000922/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Chris Lattner03df1222007-06-02 04:53:11 +0000923/// variable declaration with auto, register, or no storage class specifier.
Chris Lattnerb781dc792008-05-08 05:58:21 +0000924/// These turn into simple stack objects, or GlobalValues depending on target.
John McCallc533cb72011-02-22 06:44:22 +0000925void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
926 AutoVarEmission emission = EmitAutoVarAlloca(D);
927 EmitAutoVarInit(emission);
928 EmitAutoVarCleanups(emission);
929}
Chris Lattner03df1222007-06-02 04:53:11 +0000930
David Majnemerdc012fa2015-04-22 21:38:15 +0000931/// Emit a lifetime.begin marker if some criteria are satisfied.
932/// \return a pointer to the temporary size Value if a marker was emitted, null
933/// otherwise
934llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
935 llvm::Value *Addr) {
Vitaly Buka1c943322016-10-26 01:59:57 +0000936 if (!ShouldEmitLifetimeMarkers)
Reid Kleckner1ef49212015-04-23 18:07:13 +0000937 return nullptr;
938
David Majnemerdc012fa2015-04-22 21:38:15 +0000939 llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
Yaxun Liu7f7f3232017-04-17 20:03:11 +0000940 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
Alexey Samsonovd918ff62015-06-12 22:31:32 +0000941 llvm::CallInst *C =
942 Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +0000943 C->setDoesNotThrow();
944 return SizeV;
945}
946
947void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
Yaxun Liu7f7f3232017-04-17 20:03:11 +0000948 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
Alexey Samsonovd918ff62015-06-12 22:31:32 +0000949 llvm::CallInst *C =
950 Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +0000951 C->setDoesNotThrow();
952}
953
John McCallc533cb72011-02-22 06:44:22 +0000954/// EmitAutoVarAlloca - Emit the alloca and debug information for a
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000955/// local variable. Does not emit initialization or destruction.
John McCallc533cb72011-02-22 06:44:22 +0000956CodeGenFunction::AutoVarEmission
957CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
958 QualType Ty = D.getType();
Yaxun Liu84744c12017-06-19 17:03:41 +0000959 assert(Ty.getAddressSpace() == LangAS::Default);
John McCallc533cb72011-02-22 06:44:22 +0000960
961 AutoVarEmission emission(D);
962
963 bool isByRef = D.hasAttr<BlocksAttr>();
964 emission.IsByRef = isByRef;
965
966 CharUnits alignment = getContext().getDeclAlign(&D);
John McCallc533cb72011-02-22 06:44:22 +0000967
John McCall23c29fe2011-06-24 21:55:10 +0000968 // If the type is variably-modified, emit all the VLA sizes for it.
969 if (Ty->isVariablyModifiedType())
970 EmitVariablyModifiedType(Ty);
971
John McCall7f416cc2015-09-08 08:05:57 +0000972 Address address = Address::invalid();
Eli Friedmana682d392008-02-15 12:20:59 +0000973 if (Ty->isConstantSizeType()) {
Rafael Espindola609f5d92013-03-26 18:41:47 +0000974 bool NRVO = getLangOpts().ElideConstructors &&
975 D.isNRVOVariable();
John McCallc533cb72011-02-22 06:44:22 +0000976
Richard Smith2bcde3a2013-06-02 00:09:52 +0000977 // If this value is an array or struct with a statically determinable
978 // constant initializer, there are optimizations we can do.
Rafael Espindola609f5d92013-03-26 18:41:47 +0000979 //
980 // TODO: We should constant-evaluate the initializer of any variable,
981 // as long as it is initialized by a constant expression. Currently,
982 // isConstantInitializer produces wrong answers for structs with
983 // reference or bitfield members, and a few other cases, and checking
984 // for POD-ness protects us from some of these.
Richard Smith2bcde3a2013-06-02 00:09:52 +0000985 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
986 (D.isConstexpr() ||
987 ((Ty.isPODType(getContext()) ||
988 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
989 D.getInit()->isConstantInitializer(getContext(), false)))) {
John McCallc533cb72011-02-22 06:44:22 +0000990
Rafael Espindola609f5d92013-03-26 18:41:47 +0000991 // If the variable's a const type, and it's neither an NRVO
992 // candidate nor a __block variable and has no mutable members,
993 // emit it as a global instead.
Anastasia Stulovae4a1c382016-11-29 17:01:19 +0000994 // Exception is if a variable is located in non-constant address space
995 // in OpenCL.
996 if ((!getLangOpts().OpenCL ||
997 Ty.getAddressSpace() == LangAS::opencl_constant) &&
998 (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
999 CGM.isTypeConstant(Ty, true))) {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001000 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCallc533cb72011-02-22 06:44:22 +00001001
John McCall7f416cc2015-09-08 08:05:57 +00001002 // Signal this condition to later callbacks.
1003 emission.Addr = Address::invalid();
Rafael Espindola609f5d92013-03-26 18:41:47 +00001004 assert(emission.wasEmittedAsGlobal());
1005 return emission;
Tanya Lattnerf9d41df2009-11-04 01:18:09 +00001006 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001007
Rafael Espindola609f5d92013-03-26 18:41:47 +00001008 // Otherwise, tell the initialization code that we're in this case.
1009 emission.IsConstantAggregate = true;
1010 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001011
Rafael Espindola609f5d92013-03-26 18:41:47 +00001012 // A normal fixed sized variable becomes an alloca in the entry block,
1013 // unless it's an NRVO variable.
Eric Christopher31ab1302011-08-23 22:38:00 +00001014
Rafael Espindola609f5d92013-03-26 18:41:47 +00001015 if (NRVO) {
1016 // The named return value optimization: allocate this variable in the
1017 // return slot, so that we can elide the copy when returning this
1018 // variable (C++0x [class.copy]p34).
John McCall7f416cc2015-09-08 08:05:57 +00001019 address = ReturnValue;
Eric Christopher31ab1302011-08-23 22:38:00 +00001020
Rafael Espindola609f5d92013-03-26 18:41:47 +00001021 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1022 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
1023 // Create a flag that is used to indicate when the NRVO was applied
1024 // to this variable. Set it to zero to indicate that NRVO was not
1025 // applied.
1026 llvm::Value *Zero = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +00001027 Address NRVOFlag =
1028 CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
Rafael Espindola609f5d92013-03-26 18:41:47 +00001029 EnsureInsertPoint();
1030 Builder.CreateStore(Zero, NRVOFlag);
Eric Christopher31ab1302011-08-23 22:38:00 +00001031
Rafael Espindola609f5d92013-03-26 18:41:47 +00001032 // Record the NRVO flag for this variable.
John McCall7f416cc2015-09-08 08:05:57 +00001033 NRVOFlags[&D] = NRVOFlag.getPointer();
1034 emission.NRVOFlag = NRVOFlag.getPointer();
Nadav Rotem1da30942013-03-23 06:43:35 +00001035 }
Douglas Gregor290c93e2010-05-15 06:46:45 +00001036 }
Chris Lattnerb781dc792008-05-08 05:58:21 +00001037 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001038 CharUnits allocaAlignment;
1039 llvm::Type *allocaTy;
1040 if (isByRef) {
1041 auto &byrefInfo = getBlockByrefInfo(&D);
1042 allocaTy = byrefInfo.Type;
1043 allocaAlignment = byrefInfo.ByrefAlignment;
1044 } else {
1045 allocaTy = ConvertTypeForMem(Ty);
1046 allocaAlignment = alignment;
1047 }
Rafael Espindola609f5d92013-03-26 18:41:47 +00001048
John McCall999110f2015-09-08 09:18:30 +00001049 // Create the alloca. Note that we set the name separately from
1050 // building the instruction so that it's there even in no-asserts
1051 // builds.
Yaxun Liu84744c12017-06-19 17:03:41 +00001052 address = CreateTempAlloca(allocaTy, allocaAlignment, D.getName());
Rafael Espindola609f5d92013-03-26 18:41:47 +00001053
Reid Kleckner1f88e932015-10-07 21:03:41 +00001054 // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1055 // the catch parameter starts in the catchpad instruction, and we can't
1056 // insert code in those basic blocks.
1057 bool IsMSCatchParam =
1058 D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1059
Vitaly Buka64c80b42016-10-26 05:42:30 +00001060 // Emit a lifetime intrinsic if meaningful. There's no point in doing this
1061 // if we don't have a valid insertion point (?).
Reid Kleckner1f88e932015-10-07 21:03:41 +00001062 if (HaveInsertPoint() && !IsMSCatchParam) {
Akira Hatanakafdcd18b2017-01-25 22:55:13 +00001063 // If there's a jump into the lifetime of this variable, its lifetime
1064 // gets broken up into several regions in IR, which requires more work
1065 // to handle correctly. For now, just omit the intrinsics; this is a
1066 // rare case, and it's better to just be conservatively correct.
1067 // PR28267.
1068 //
1069 // We have to do this in all language modes if there's a jump past the
1070 // declaration. We also have to do it in C if there's a jump to an
1071 // earlier point in the current block because non-VLA lifetimes begin as
1072 // soon as the containing block is entered, not when its variables
1073 // actually come into scope; suppressing the lifetime annotations
1074 // completely in this case is unnecessarily pessimistic, but again, this
1075 // is rare.
1076 if (!Bypasses.IsBypassed(&D) &&
1077 !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
Vitaly Buka64c80b42016-10-26 05:42:30 +00001078 uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
1079 emission.SizeForLifetimeMarkers =
1080 EmitLifetimeStart(size, address.getPointer());
1081 }
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +00001082 } else {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001083 assert(!emission.useLifetimeMarkers());
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +00001084 }
Chris Lattnerb781dc792008-05-08 05:58:21 +00001085 }
Chris Lattner03df1222007-06-02 04:53:11 +00001086 } else {
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001087 EnsureInsertPoint();
1088
Anders Carlsson15949b32009-02-09 20:41:50 +00001089 if (!DidCallStackSave) {
Anders Carlsson30032882008-12-12 07:38:43 +00001090 // Save the stack.
John McCall7f416cc2015-09-08 08:05:57 +00001091 Address Stack =
1092 CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
Mike Stump11289f42009-09-09 15:08:12 +00001093
Anders Carlsson30032882008-12-12 07:38:43 +00001094 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
David Blaikie4ba525b2015-07-14 17:27:39 +00001095 llvm::Value *V = Builder.CreateCall(F);
Anders Carlsson30032882008-12-12 07:38:43 +00001096 Builder.CreateStore(V, Stack);
Anders Carlsson15949b32009-02-09 20:41:50 +00001097
1098 DidCallStackSave = true;
Mike Stump11289f42009-09-09 15:08:12 +00001099
John McCalla464ff92010-07-21 06:13:08 +00001100 // Push a cleanup block and restore the stack there.
John McCalle4df6c82011-01-28 08:37:24 +00001101 // FIXME: in general circumstances, this should be an EH cleanup.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001102 pushStackRestore(NormalCleanup, Stack);
Anders Carlsson30032882008-12-12 07:38:43 +00001103 }
Mike Stump11289f42009-09-09 15:08:12 +00001104
John McCall23c29fe2011-06-24 21:55:10 +00001105 llvm::Value *elementCount;
1106 QualType elementType;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001107 std::tie(elementCount, elementType) = getVLASize(Ty);
Anders Carlsson30032882008-12-12 07:38:43 +00001108
Chris Lattner2192fe52011-07-18 04:24:23 +00001109 llvm::Type *llvmTy = ConvertTypeForMem(elementType);
Anders Carlsson30032882008-12-12 07:38:43 +00001110
1111 // Allocate memory for the array.
Yaxun Liu84744c12017-06-19 17:03:41 +00001112 address = CreateTempAlloca(llvmTy, alignment, "vla", elementCount);
Chris Lattner03df1222007-06-02 04:53:11 +00001113 }
Eli Friedmanf4084702008-12-20 23:11:59 +00001114
John McCall7f416cc2015-09-08 08:05:57 +00001115 setAddrOfLocalVar(&D, address);
1116 emission.Addr = address;
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001117
1118 // Emit debug info for local var declaration.
Devang Patel887e2152011-06-03 19:21:47 +00001119 if (HaveInsertPoint())
1120 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001121 if (CGM.getCodeGenOpts().getDebugInfo() >=
1122 codegenoptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001123 DI->setLocation(D.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001124 DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001125 }
Devang Patel887e2152011-06-03 19:21:47 +00001126 }
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001127
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001128 if (D.hasAttr<AnnotateAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00001129 EmitVarAnnotations(&D, address.getPointer());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001130
Kuba Mracek5e5e4e72017-04-14 16:53:25 +00001131 // Make sure we call @llvm.lifetime.end.
1132 if (emission.useLifetimeMarkers())
1133 EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
1134 emission.getAllocatedAddress(),
1135 emission.getSizeForLifetimeMarkers());
1136
John McCallc533cb72011-02-22 06:44:22 +00001137 return emission;
1138}
1139
1140/// Determines whether the given __block variable is potentially
1141/// captured by the given expression.
1142static bool isCapturedBy(const VarDecl &var, const Expr *e) {
1143 // Skip the most common kinds of expressions that make
1144 // hierarchy-walking expensive.
1145 e = e->IgnoreParenCasts();
1146
1147 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
1148 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +00001149 for (const auto &I : block->captures()) {
1150 if (I.getVariable() == &var)
John McCallc533cb72011-02-22 06:44:22 +00001151 return true;
1152 }
1153
1154 // No need to walk into the subexpressions.
1155 return false;
1156 }
1157
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001158 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1159 const CompoundStmt *CS = SE->getSubStmt();
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001160 for (const auto *BI : CS->body())
1161 if (const auto *E = dyn_cast<Expr>(BI)) {
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001162 if (isCapturedBy(var, E))
1163 return true;
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001164 }
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001165 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001166 // special case declarations
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001167 for (const auto *I : DS->decls()) {
1168 if (const auto *VD = dyn_cast<VarDecl>((I))) {
1169 const Expr *Init = VD->getInit();
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001170 if (Init && isCapturedBy(var, Init))
1171 return true;
1172 }
1173 }
1174 }
1175 else
1176 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1177 // Later, provide code to poke into statements for capture analysis.
1178 return true;
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001179 return false;
1180 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001181
Benjamin Kramer642f1732015-07-02 21:03:14 +00001182 for (const Stmt *SubStmt : e->children())
1183 if (isCapturedBy(var, cast<Expr>(SubStmt)))
John McCallc533cb72011-02-22 06:44:22 +00001184 return true;
1185
1186 return false;
1187}
1188
Douglas Gregor82e1af22011-07-01 21:08:19 +00001189/// \brief Determine whether the given initializer is trivial in the sense
1190/// that it requires no code to be generated.
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001191bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
Douglas Gregor82e1af22011-07-01 21:08:19 +00001192 if (!Init)
1193 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001194
Douglas Gregor82e1af22011-07-01 21:08:19 +00001195 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1196 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1197 if (Constructor->isTrivial() &&
1198 Constructor->isDefaultConstructor() &&
1199 !Construct->requiresZeroInitialization())
1200 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001201
Douglas Gregor82e1af22011-07-01 21:08:19 +00001202 return false;
1203}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001204
John McCallc533cb72011-02-22 06:44:22 +00001205void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001206 assert(emission.Variable && "emission was not valid!");
1207
John McCallc533cb72011-02-22 06:44:22 +00001208 // If this was emitted as a global constant, we're done.
1209 if (emission.wasEmittedAsGlobal()) return;
1210
John McCall9e2e22f2011-02-22 07:16:58 +00001211 const VarDecl &D = *emission.Variable;
Adrian Prantl95b24e92015-02-03 20:00:54 +00001212 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
John McCallc533cb72011-02-22 06:44:22 +00001213 QualType type = D.getType();
1214
Chris Lattner07eb7332007-07-12 00:39:48 +00001215 // If this local has an initializer, emit it now.
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001216 const Expr *Init = D.getInit();
1217
1218 // If we are at an unreachable point, we don't need to emit the initializer
1219 // unless it contains a label.
1220 if (!HaveInsertPoint()) {
John McCallc533cb72011-02-22 06:44:22 +00001221 if (!Init || !ContainsLabel(Init)) return;
1222 EnsureInsertPoint();
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001223 }
1224
John McCall73064872011-03-31 01:59:53 +00001225 // Initialize the structure of a __block variable.
1226 if (emission.IsByRef)
1227 emitByrefStructureInit(emission);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001228
Douglas Gregor82e1af22011-07-01 21:08:19 +00001229 if (isTrivialInitializer(Init))
1230 return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001231
John McCallc533cb72011-02-22 06:44:22 +00001232 // Check whether this is a byref variable that's potentially
1233 // captured and moved by its own initializer. If so, we'll need to
1234 // emit the initializer first, then copy into the variable.
1235 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1236
John McCall7f416cc2015-09-08 08:05:57 +00001237 Address Loc =
1238 capturedByInit ? emission.Addr : emission.getObjectAddress(*this);
John McCallc533cb72011-02-22 06:44:22 +00001239
Craig Topper8a13c412014-05-21 05:09:00 +00001240 llvm::Constant *constant = nullptr;
Richard Smith2bcde3a2013-06-02 00:09:52 +00001241 if (emission.IsConstantAggregate || D.isConstexpr()) {
Richard Smithfddd3842011-12-30 21:15:51 +00001242 assert(!capturedByInit && "constant init contains a capturing block?");
John McCallde0fe072017-08-15 21:42:52 +00001243 constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(D);
Richard Smithfddd3842011-12-30 21:15:51 +00001244 }
1245
1246 if (!constant) {
John McCall7f416cc2015-09-08 08:05:57 +00001247 LValue lv = MakeAddrLValue(Loc, type);
John McCall1553b192011-06-16 04:16:24 +00001248 lv.setNonGC(true);
David Blaikie66e41972015-01-14 07:38:27 +00001249 return EmitExprAsInit(Init, &D, lv, capturedByInit);
John McCall1553b192011-06-16 04:16:24 +00001250 }
John McCall91ca10f2011-03-08 09:11:50 +00001251
Richard Smith2bcde3a2013-06-02 00:09:52 +00001252 if (!emission.IsConstantAggregate) {
1253 // For simple scalar/complex initialization, store the value directly.
John McCall7f416cc2015-09-08 08:05:57 +00001254 LValue lv = MakeAddrLValue(Loc, type);
Richard Smith2bcde3a2013-06-02 00:09:52 +00001255 lv.setNonGC(true);
1256 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1257 }
1258
John McCallc533cb72011-02-22 06:44:22 +00001259 // If this is a simple aggregate initialization, we can optimize it
1260 // in various ways.
John McCall91ca10f2011-03-08 09:11:50 +00001261 bool isVolatile = type.isVolatileQualified();
John McCallc533cb72011-02-22 06:44:22 +00001262
John McCall91ca10f2011-03-08 09:11:50 +00001263 llvm::Value *SizeVal =
Eric Christopher31ab1302011-08-23 22:38:00 +00001264 llvm::ConstantInt::get(IntPtrTy,
John McCall91ca10f2011-03-08 09:11:50 +00001265 getContext().getTypeSizeInChars(type).getQuantity());
John McCallc533cb72011-02-22 06:44:22 +00001266
Chris Lattner2192fe52011-07-18 04:24:23 +00001267 llvm::Type *BP = Int8PtrTy;
John McCall7f416cc2015-09-08 08:05:57 +00001268 if (Loc.getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001269 Loc = Builder.CreateBitCast(Loc, BP);
Mon P Wangcc2ab0c2010-04-04 03:10:52 +00001270
John McCall91ca10f2011-03-08 09:11:50 +00001271 // If the initializer is all or mostly zeros, codegen with memset then do
1272 // a few stores afterward.
Eric Christopher31ab1302011-08-23 22:38:00 +00001273 if (shouldUseMemSetPlusStoresToInitialize(constant,
Micah Villmowdd31ca12012-10-08 16:25:52 +00001274 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
John McCall91ca10f2011-03-08 09:11:50 +00001275 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
John McCall7f416cc2015-09-08 08:05:57 +00001276 isVolatile);
Benjamin Kramer29f9a002012-08-27 22:07:02 +00001277 // Zero and undef don't require a stores.
1278 if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
John McCall91ca10f2011-03-08 09:11:50 +00001279 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +00001280 emitStoresForInitAfterMemset(constant, Loc.getPointer(),
1281 isVolatile, Builder);
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001282 }
John McCall91ca10f2011-03-08 09:11:50 +00001283 } else {
Eric Christopher31ab1302011-08-23 22:38:00 +00001284 // Otherwise, create a temporary global with the initializer then
John McCall91ca10f2011-03-08 09:11:50 +00001285 // memcpy from the global to the alloca.
Reid Kleckner453e0562014-10-08 01:07:54 +00001286 std::string Name = getStaticDeclName(CGM, D);
Alexey Baderabdcfc12016-10-31 10:26:31 +00001287 unsigned AS = 0;
1288 if (getLangOpts().OpenCL) {
1289 AS = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
1290 BP = llvm::PointerType::getInt8PtrTy(getLLVMContext(), AS);
1291 }
John McCall91ca10f2011-03-08 09:11:50 +00001292 llvm::GlobalVariable *GV =
1293 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
Eric Christopherb58b3e82011-08-24 00:33:55 +00001294 llvm::GlobalValue::PrivateLinkage,
Alexey Baderabdcfc12016-10-31 10:26:31 +00001295 constant, Name, nullptr,
1296 llvm::GlobalValue::NotThreadLocal, AS);
John McCall7f416cc2015-09-08 08:05:57 +00001297 GV->setAlignment(Loc.getAlignment().getQuantity());
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001298 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Eric Christopher31ab1302011-08-23 22:38:00 +00001299
John McCall7f416cc2015-09-08 08:05:57 +00001300 Address SrcPtr = Address(GV, Loc.getAlignment());
1301 if (SrcPtr.getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001302 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
John McCall91ca10f2011-03-08 09:11:50 +00001303
John McCall7f416cc2015-09-08 08:05:57 +00001304 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, isVolatile);
John McCall91ca10f2011-03-08 09:11:50 +00001305 }
1306}
1307
1308/// Emit an expression as an initializer for a variable at the given
1309/// location. The expression is not necessarily the normal
1310/// initializer for the variable, and the address is not necessarily
1311/// its normal location.
1312///
1313/// \param init the initializing expression
1314/// \param var the variable to act as if we're initializing
1315/// \param loc the address to initialize; its type is a pointer
1316/// to the LLVM mapping of the variable's type
1317/// \param alignment the alignment of the address
1318/// \param capturedByInit true if the variable is a __block variable
1319/// whose address is potentially changed by the initializer
David Blaikie73ca5692014-12-09 00:32:22 +00001320void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +00001321 LValue lvalue, bool capturedByInit) {
John McCall31168b02011-06-15 23:02:42 +00001322 QualType type = D->getType();
John McCall91ca10f2011-03-08 09:11:50 +00001323
1324 if (type->isReferenceType()) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +00001325 RValue rvalue = EmitReferenceBindingToExpr(init);
Eric Christopher31ab1302011-08-23 22:38:00 +00001326 if (capturedByInit)
John McCall1553b192011-06-16 04:16:24 +00001327 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001328 EmitStoreThroughLValue(rvalue, lvalue, true);
John McCall47fb9502013-03-07 21:37:08 +00001329 return;
1330 }
1331 switch (getEvaluationKind(type)) {
1332 case TEK_Scalar:
David Blaikie66e41972015-01-14 07:38:27 +00001333 EmitScalarInit(init, D, lvalue, capturedByInit);
John McCall47fb9502013-03-07 21:37:08 +00001334 return;
1335 case TEK_Complex: {
John McCall91ca10f2011-03-08 09:11:50 +00001336 ComplexPairTy complex = EmitComplexExpr(init);
John McCall1553b192011-06-16 04:16:24 +00001337 if (capturedByInit)
1338 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001339 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
John McCall47fb9502013-03-07 21:37:08 +00001340 return;
1341 }
1342 case TEK_Aggregate:
John McCalla8ec7eb2013-03-07 21:37:17 +00001343 if (type->isAtomicType()) {
1344 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1345 } else {
1346 // TODO: how can we delay here if D is captured by its initializer?
1347 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001348 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001349 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001350 AggValueSlot::IsNotAliased));
John McCalla8ec7eb2013-03-07 21:37:17 +00001351 }
John McCall47fb9502013-03-07 21:37:08 +00001352 return;
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001353 }
John McCall47fb9502013-03-07 21:37:08 +00001354 llvm_unreachable("bad evaluation kind");
John McCallc533cb72011-02-22 06:44:22 +00001355}
John McCallbd309292010-07-06 01:34:17 +00001356
John McCall82fe67b2011-07-09 01:37:26 +00001357/// Enter a destroy cleanup for the given local variable.
1358void CodeGenFunction::emitAutoVarTypeCleanup(
1359 const CodeGenFunction::AutoVarEmission &emission,
1360 QualType::DestructionKind dtorKind) {
1361 assert(dtorKind != QualType::DK_none);
1362
1363 // Note that for __block variables, we want to destroy the
1364 // original stack object, not the possibly forwarded object.
John McCall7f416cc2015-09-08 08:05:57 +00001365 Address addr = emission.getObjectAddress(*this);
John McCall82fe67b2011-07-09 01:37:26 +00001366
1367 const VarDecl *var = emission.Variable;
1368 QualType type = var->getType();
1369
1370 CleanupKind cleanupKind = NormalAndEHCleanup;
Craig Topper8a13c412014-05-21 05:09:00 +00001371 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall82fe67b2011-07-09 01:37:26 +00001372
1373 switch (dtorKind) {
1374 case QualType::DK_none:
1375 llvm_unreachable("no cleanup for trivially-destructible variable");
1376
1377 case QualType::DK_cxx_destructor:
1378 // If there's an NRVO flag on the emission, we need a different
1379 // cleanup.
1380 if (emission.NRVOFlag) {
1381 assert(!type->isArrayType());
1382 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
John McCall7f416cc2015-09-08 08:05:57 +00001383 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr,
1384 dtor, emission.NRVOFlag);
John McCall82fe67b2011-07-09 01:37:26 +00001385 return;
1386 }
1387 break;
1388
1389 case QualType::DK_objc_strong_lifetime:
1390 // Suppress cleanups for pseudo-strong variables.
1391 if (var->isARCPseudoStrong()) return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001392
John McCall82fe67b2011-07-09 01:37:26 +00001393 // Otherwise, consider whether to use an EH cleanup or not.
1394 cleanupKind = getARCCleanupKind();
1395
1396 // Use the imprecise destroyer by default.
1397 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1398 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1399 break;
1400
1401 case QualType::DK_objc_weak_lifetime:
1402 break;
1403 }
1404
1405 // If we haven't chosen a more specific destroyer, use the default.
Peter Collingbourne1425b452012-01-26 03:33:36 +00001406 if (!destroyer) destroyer = getDestroyer(dtorKind);
John McCall178360e2011-07-11 08:38:19 +00001407
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001408 // Use an EH cleanup in array destructors iff the destructor itself
John McCall178360e2011-07-11 08:38:19 +00001409 // is being pushed as an EH cleanup.
1410 bool useEHCleanup = (cleanupKind & EHCleanup);
1411 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1412 useEHCleanup);
John McCall82fe67b2011-07-09 01:37:26 +00001413}
1414
John McCallc533cb72011-02-22 06:44:22 +00001415void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001416 assert(emission.Variable && "emission was not valid!");
1417
John McCallc533cb72011-02-22 06:44:22 +00001418 // If this was emitted as a global constant, we're done.
1419 if (emission.wasEmittedAsGlobal()) return;
1420
John McCall8c38d352012-04-13 18:44:05 +00001421 // If we don't have an insertion point, we're done. Sema prevents
1422 // us from jumping into any of these scopes anyway.
1423 if (!HaveInsertPoint()) return;
1424
John McCall9e2e22f2011-02-22 07:16:58 +00001425 const VarDecl &D = *emission.Variable;
John McCallc533cb72011-02-22 06:44:22 +00001426
John McCall82fe67b2011-07-09 01:37:26 +00001427 // Check the type for a cleanup.
1428 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1429 emitAutoVarTypeCleanup(emission, dtorKind);
John McCall31168b02011-06-15 23:02:42 +00001430
John McCall1bd25562011-06-24 23:21:27 +00001431 // In GC mode, honor objc_precise_lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001432 if (getLangOpts().getGC() != LangOptions::NonGC &&
John McCall1bd25562011-06-24 23:21:27 +00001433 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1434 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1435 }
1436
John McCallc533cb72011-02-22 06:44:22 +00001437 // Handle the cleanup attribute.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001438 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001439 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001440
John McCallc533cb72011-02-22 06:44:22 +00001441 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001442 assert(F && "Could not find function!");
Mike Stump11289f42009-09-09 15:08:12 +00001443
John McCalla729c622012-02-17 03:33:10 +00001444 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
John McCallc533cb72011-02-22 06:44:22 +00001445 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001446 }
Mike Stump626aecc2009-03-05 01:23:13 +00001447
John McCallc533cb72011-02-22 06:44:22 +00001448 // If this is a block variable, call _Block_object_destroy
1449 // (on the unforwarded address).
John McCall73064872011-03-31 01:59:53 +00001450 if (emission.IsByRef)
1451 enterByrefCleanup(emission);
Chris Lattner03df1222007-06-02 04:53:11 +00001452}
Chris Lattner53621a52007-06-13 20:44:40 +00001453
Peter Collingbourne1425b452012-01-26 03:33:36 +00001454CodeGenFunction::Destroyer *
John McCall82fe67b2011-07-09 01:37:26 +00001455CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1456 switch (kind) {
1457 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
John McCallc2f00012011-07-09 09:09:00 +00001458 case QualType::DK_cxx_destructor:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001459 return destroyCXXObject;
John McCallc2f00012011-07-09 09:09:00 +00001460 case QualType::DK_objc_strong_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001461 return destroyARCStrongPrecise;
John McCallc2f00012011-07-09 09:09:00 +00001462 case QualType::DK_objc_weak_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001463 return destroyARCWeak;
John McCall82fe67b2011-07-09 01:37:26 +00001464 }
Matt Beaumont-Gay934bbf52012-01-27 00:46:27 +00001465 llvm_unreachable("Unknown DestructionKind");
John McCall82fe67b2011-07-09 01:37:26 +00001466}
1467
John McCall12cc42a2013-02-01 05:11:40 +00001468/// pushEHDestroy - Push the standard destructor for the given type as
1469/// an EH-only cleanup.
1470void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00001471 Address addr, QualType type) {
John McCall12cc42a2013-02-01 05:11:40 +00001472 assert(dtorKind && "cannot push destructor for trivial type");
1473 assert(needsEHCleanup(dtorKind));
1474
1475 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1476}
1477
1478/// pushDestroy - Push the standard destructor for the given type as
1479/// at least a normal cleanup.
John McCall4bd0fb12011-07-12 16:41:08 +00001480void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00001481 Address addr, QualType type) {
John McCall4bd0fb12011-07-12 16:41:08 +00001482 assert(dtorKind && "cannot push destructor for trivial type");
1483
1484 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1485 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1486 cleanupKind & EHCleanup);
1487}
1488
John McCall7f416cc2015-09-08 08:05:57 +00001489void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001490 QualType type, Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001491 bool useEHCleanupForArray) {
John McCall4bd0fb12011-07-12 16:41:08 +00001492 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1493 destroyer, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001494}
1495
John McCall7f416cc2015-09-08 08:05:57 +00001496void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001497 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
1498}
1499
Richard Smith736a9472013-06-12 20:42:33 +00001500void CodeGenFunction::pushLifetimeExtendedDestroy(
John McCall7f416cc2015-09-08 08:05:57 +00001501 CleanupKind cleanupKind, Address addr, QualType type,
Richard Smith736a9472013-06-12 20:42:33 +00001502 Destroyer *destroyer, bool useEHCleanupForArray) {
1503 assert(!isInConditionalBranch() &&
1504 "performing lifetime extension from within conditional");
1505
1506 // Push an EH-only cleanup for the object now.
1507 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1508 // around in case a temporary's destructor throws an exception.
1509 if (cleanupKind & EHCleanup)
1510 EHStack.pushCleanup<DestroyObject>(
1511 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1512 destroyer, useEHCleanupForArray);
1513
1514 // Remember that we need to push a full cleanup for the object at the
1515 // end of the full-expression.
1516 pushCleanupAfterFullExpr<DestroyObject>(
1517 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1518}
1519
John McCall178360e2011-07-11 08:38:19 +00001520/// emitDestroy - Immediately perform the destruction of the given
1521/// object.
1522///
1523/// \param addr - the address of the object; a type*
1524/// \param type - the type of the object; if an array type, all
1525/// objects are destroyed in reverse order
1526/// \param destroyer - the function to call to destroy individual
1527/// elements
1528/// \param useEHCleanupForArray - whether an EH cleanup should be
1529/// used when destroying array elements, in case one of the
1530/// destructions throws an exception
John McCall7f416cc2015-09-08 08:05:57 +00001531void CodeGenFunction::emitDestroy(Address addr, QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001532 Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001533 bool useEHCleanupForArray) {
John McCall82fe67b2011-07-09 01:37:26 +00001534 const ArrayType *arrayType = getContext().getAsArrayType(type);
1535 if (!arrayType)
1536 return destroyer(*this, addr, type);
1537
John McCall7f416cc2015-09-08 08:05:57 +00001538 llvm::Value *length = emitArrayLength(arrayType, type, addr);
1539
1540 CharUnits elementAlign =
1541 addr.getAlignment()
1542 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
John McCall97eab0a2011-07-13 08:09:46 +00001543
1544 // Normally we have to check whether the array is zero-length.
1545 bool checkZeroLength = true;
1546
1547 // But if the array length is constant, we can suppress that.
1548 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1549 // ...and if it's constant zero, we can just skip the entire thing.
1550 if (constLength->isZero()) return;
1551 checkZeroLength = false;
1552 }
1553
John McCall7f416cc2015-09-08 08:05:57 +00001554 llvm::Value *begin = addr.getPointer();
John McCall82fe67b2011-07-09 01:37:26 +00001555 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
John McCall7f416cc2015-09-08 08:05:57 +00001556 emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001557 checkZeroLength, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001558}
1559
John McCall178360e2011-07-11 08:38:19 +00001560/// emitArrayDestroy - Destroys all the elements of the given array,
1561/// beginning from last to first. The array cannot be zero-length.
1562///
1563/// \param begin - a type* denoting the first element of the array
1564/// \param end - a type* denoting one past the end of the array
NAKAMURA Takumiff7a9252015-09-08 09:42:41 +00001565/// \param elementType - the element type of the array
John McCall178360e2011-07-11 08:38:19 +00001566/// \param destroyer - the function to call to destroy elements
1567/// \param useEHCleanup - whether to push an EH cleanup to destroy
1568/// the remaining elements in case the destruction of a single
1569/// element throws
John McCall82fe67b2011-07-09 01:37:26 +00001570void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1571 llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00001572 QualType elementType,
1573 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001574 Destroyer *destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001575 bool checkZeroLength,
John McCall178360e2011-07-11 08:38:19 +00001576 bool useEHCleanup) {
John McCall7f416cc2015-09-08 08:05:57 +00001577 assert(!elementType->isArrayType());
John McCall82fe67b2011-07-09 01:37:26 +00001578
1579 // The basic structure here is a do-while loop, because we don't
1580 // need to check for the zero-element case.
1581 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1582 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1583
John McCall97eab0a2011-07-13 08:09:46 +00001584 if (checkZeroLength) {
1585 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1586 "arraydestroy.isempty");
1587 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1588 }
1589
John McCall82fe67b2011-07-09 01:37:26 +00001590 // Enter the loop body, making that address the current address.
1591 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1592 EmitBlock(bodyBB);
1593 llvm::PHINode *elementPast =
1594 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1595 elementPast->addIncoming(end, entryBB);
1596
1597 // Shift the address back by one element.
1598 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1599 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1600 "arraydestroy.element");
1601
John McCall178360e2011-07-11 08:38:19 +00001602 if (useEHCleanup)
John McCall7f416cc2015-09-08 08:05:57 +00001603 pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
1604 destroyer);
John McCall178360e2011-07-11 08:38:19 +00001605
John McCall82fe67b2011-07-09 01:37:26 +00001606 // Perform the actual destruction there.
John McCall7f416cc2015-09-08 08:05:57 +00001607 destroyer(*this, Address(element, elementAlign), elementType);
John McCall82fe67b2011-07-09 01:37:26 +00001608
John McCall178360e2011-07-11 08:38:19 +00001609 if (useEHCleanup)
1610 PopCleanupBlock();
1611
John McCall82fe67b2011-07-09 01:37:26 +00001612 // Check whether we've reached the end.
1613 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1614 Builder.CreateCondBr(done, doneBB, bodyBB);
1615 elementPast->addIncoming(element, Builder.GetInsertBlock());
1616
1617 // Done.
1618 EmitBlock(doneBB);
1619}
1620
John McCall178360e2011-07-11 08:38:19 +00001621/// Perform partial array destruction as if in an EH cleanup. Unlike
1622/// emitArrayDestroy, the element type here may still be an array type.
John McCall178360e2011-07-11 08:38:19 +00001623static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1624 llvm::Value *begin, llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00001625 QualType type, CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001626 CodeGenFunction::Destroyer *destroyer) {
John McCall178360e2011-07-11 08:38:19 +00001627 // If the element type is itself an array, drill down.
John McCall97eab0a2011-07-13 08:09:46 +00001628 unsigned arrayDepth = 0;
John McCall178360e2011-07-11 08:38:19 +00001629 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1630 // VLAs don't require a GEP index to walk into.
1631 if (!isa<VariableArrayType>(arrayType))
John McCall97eab0a2011-07-13 08:09:46 +00001632 arrayDepth++;
John McCall178360e2011-07-11 08:38:19 +00001633 type = arrayType->getElementType();
1634 }
John McCall97eab0a2011-07-13 08:09:46 +00001635
1636 if (arrayDepth) {
John McCallf0f0b7a2015-09-14 18:57:08 +00001637 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
John McCall97eab0a2011-07-13 08:09:46 +00001638
John McCallf0f0b7a2015-09-14 18:57:08 +00001639 SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
Jay Foad040dd822011-07-22 08:16:57 +00001640 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1641 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
John McCall178360e2011-07-11 08:38:19 +00001642 }
1643
John McCall97eab0a2011-07-13 08:09:46 +00001644 // Destroy the array. We don't ever need an EH cleanup because we
1645 // assume that we're in an EH cleanup ourselves, so a throwing
1646 // destructor causes an immediate terminate.
John McCall7f416cc2015-09-08 08:05:57 +00001647 CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001648 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
John McCall178360e2011-07-11 08:38:19 +00001649}
1650
John McCall82fe67b2011-07-09 01:37:26 +00001651namespace {
John McCall178360e2011-07-11 08:38:19 +00001652 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1653 /// array destroy where the end pointer is regularly determined and
1654 /// does not need to be loaded from a local.
David Blaikie7e70d682015-08-18 22:40:54 +00001655 class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall178360e2011-07-11 08:38:19 +00001656 llvm::Value *ArrayBegin;
1657 llvm::Value *ArrayEnd;
1658 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001659 CodeGenFunction::Destroyer *Destroyer;
John McCall7f416cc2015-09-08 08:05:57 +00001660 CharUnits ElementAlign;
John McCall178360e2011-07-11 08:38:19 +00001661 public:
1662 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001663 QualType elementType, CharUnits elementAlign,
John McCall178360e2011-07-11 08:38:19 +00001664 CodeGenFunction::Destroyer *destroyer)
1665 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
John McCall7f416cc2015-09-08 08:05:57 +00001666 ElementType(elementType), Destroyer(destroyer),
1667 ElementAlign(elementAlign) {}
John McCall178360e2011-07-11 08:38:19 +00001668
Craig Topper4f12f102014-03-12 06:41:41 +00001669 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +00001670 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001671 ElementType, ElementAlign, Destroyer);
John McCall178360e2011-07-11 08:38:19 +00001672 }
1673 };
1674
1675 /// IrregularPartialArrayDestroy - a cleanup which performs a
1676 /// partial array destroy where the end pointer is irregularly
1677 /// determined and must be loaded from a local.
David Blaikie7e70d682015-08-18 22:40:54 +00001678 class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall82fe67b2011-07-09 01:37:26 +00001679 llvm::Value *ArrayBegin;
John McCall7f416cc2015-09-08 08:05:57 +00001680 Address ArrayEndPointer;
John McCall82fe67b2011-07-09 01:37:26 +00001681 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001682 CodeGenFunction::Destroyer *Destroyer;
John McCall7f416cc2015-09-08 08:05:57 +00001683 CharUnits ElementAlign;
John McCall82fe67b2011-07-09 01:37:26 +00001684 public:
John McCall178360e2011-07-11 08:38:19 +00001685 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00001686 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00001687 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001688 CharUnits elementAlign,
John McCall178360e2011-07-11 08:38:19 +00001689 CodeGenFunction::Destroyer *destroyer)
John McCall82fe67b2011-07-09 01:37:26 +00001690 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
John McCall7f416cc2015-09-08 08:05:57 +00001691 ElementType(elementType), Destroyer(destroyer),
1692 ElementAlign(elementAlign) {}
John McCall82fe67b2011-07-09 01:37:26 +00001693
Craig Topper4f12f102014-03-12 06:41:41 +00001694 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall82fe67b2011-07-09 01:37:26 +00001695 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
John McCall178360e2011-07-11 08:38:19 +00001696 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001697 ElementType, ElementAlign, Destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001698 }
1699 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001700} // end anonymous namespace
John McCall82fe67b2011-07-09 01:37:26 +00001701
John McCall178360e2011-07-11 08:38:19 +00001702/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
John McCall82fe67b2011-07-09 01:37:26 +00001703/// already-constructed elements of the given array. The cleanup
John McCall178360e2011-07-11 08:38:19 +00001704/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001705///
John McCall82fe67b2011-07-09 01:37:26 +00001706/// \param elementType - the immediate element type of the array;
1707/// possibly still an array type
John McCall4bd0fb12011-07-12 16:41:08 +00001708void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00001709 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00001710 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001711 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001712 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001713 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1714 arrayBegin, arrayEndPointer,
John McCall7f416cc2015-09-08 08:05:57 +00001715 elementType, elementAlign,
1716 destroyer);
John McCall178360e2011-07-11 08:38:19 +00001717}
1718
1719/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1720/// already-constructed elements of the given array. The cleanup
1721/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001722///
John McCall178360e2011-07-11 08:38:19 +00001723/// \param elementType - the immediate element type of the array;
1724/// possibly still an array type
John McCall178360e2011-07-11 08:38:19 +00001725void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1726 llvm::Value *arrayEnd,
1727 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001728 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001729 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001730 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
John McCall178360e2011-07-11 08:38:19 +00001731 arrayBegin, arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001732 elementType, elementAlign,
1733 destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001734}
1735
Nadav Rotem1da30942013-03-23 06:43:35 +00001736/// Lazily declare the @llvm.lifetime.start intrinsic.
1737llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
Matt Arsenaultd9729492017-04-10 20:18:45 +00001738 if (LifetimeStartFn)
1739 return LifetimeStartFn;
Nadav Rotem1da30942013-03-23 06:43:35 +00001740 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
Yaxun Liu7f7f3232017-04-17 20:03:11 +00001741 llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);
Nadav Rotem1da30942013-03-23 06:43:35 +00001742 return LifetimeStartFn;
1743}
1744
1745/// Lazily declare the @llvm.lifetime.end intrinsic.
1746llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
Matt Arsenaultd9729492017-04-10 20:18:45 +00001747 if (LifetimeEndFn)
1748 return LifetimeEndFn;
Nadav Rotem1da30942013-03-23 06:43:35 +00001749 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
Yaxun Liu7f7f3232017-04-17 20:03:11 +00001750 llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);
Nadav Rotem1da30942013-03-23 06:43:35 +00001751 return LifetimeEndFn;
1752}
1753
John McCall31168b02011-06-15 23:02:42 +00001754namespace {
1755 /// A cleanup to perform a release of an object at the end of a
1756 /// function. This is used to balance out the incoming +1 of a
1757 /// ns_consumed argument when we can't reasonably do that just by
1758 /// not doing the initial retain for a __block argument.
David Blaikie7e70d682015-08-18 22:40:54 +00001759 struct ConsumeARCParameter final : EHScopeStack::Cleanup {
John McCallcdda29c2013-03-13 03:10:54 +00001760 ConsumeARCParameter(llvm::Value *param,
1761 ARCPreciseLifetime_t precise)
1762 : Param(param), Precise(precise) {}
John McCall31168b02011-06-15 23:02:42 +00001763
1764 llvm::Value *Param;
John McCallcdda29c2013-03-13 03:10:54 +00001765 ARCPreciseLifetime_t Precise;
John McCall31168b02011-06-15 23:02:42 +00001766
Craig Topper4f12f102014-03-12 06:41:41 +00001767 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001768 CGF.EmitARCRelease(Param, Precise);
John McCall31168b02011-06-15 23:02:42 +00001769 }
1770 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001771} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00001772
Mike Stump11289f42009-09-09 15:08:12 +00001773/// Emit an alloca (or GlobalValue depending on target)
Chris Lattnerb781dc792008-05-08 05:58:21 +00001774/// for the specified parameter and set up LocalDeclMap.
John McCall7f416cc2015-09-08 08:05:57 +00001775void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
1776 unsigned ArgNo) {
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001777 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Guptad7959242008-10-31 09:52:39 +00001778 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001779 "Invalid argument to EmitParmDecl");
John McCall147d0212011-02-22 22:38:33 +00001780
John McCall7f416cc2015-09-08 08:05:57 +00001781 Arg.getAnyValue()->setName(D.getName());
John McCall147d0212011-02-22 22:38:33 +00001782
Adrian Prantl51936dd2013-03-14 17:53:33 +00001783 QualType Ty = D.getType();
1784
John McCall147d0212011-02-22 22:38:33 +00001785 // Use better IR generation for certain implicit parameters.
John McCall7f416cc2015-09-08 08:05:57 +00001786 if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
John McCall147d0212011-02-22 22:38:33 +00001787 // The only implicit argument a block has is its literal.
John McCall7f416cc2015-09-08 08:05:57 +00001788 // We assume this is always passed directly.
John McCall147d0212011-02-22 22:38:33 +00001789 if (BlockInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001790 setBlockContextParameter(IPD, ArgNo, Arg.getDirectValue());
John McCall147d0212011-02-22 22:38:33 +00001791 return;
1792 }
Reid Klecknere5a321b2016-09-07 18:21:30 +00001793
1794 // Apply any prologue 'this' adjustments required by the ABI. Be careful to
1795 // handle the case where 'this' is passed indirectly as part of an inalloca
1796 // struct.
1797 if (const CXXMethodDecl *MD =
1798 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
1799 if (MD->isVirtual() && IPD == CXXABIThisDecl) {
1800 llvm::Value *This = Arg.isIndirect()
1801 ? Builder.CreateLoad(Arg.getIndirectAddress())
1802 : Arg.getDirectValue();
1803 This = CGM.getCXXABI().adjustThisParameterInVirtualFunctionPrologue(
1804 *this, CurGD, This);
1805 if (Arg.isIndirect())
1806 Builder.CreateStore(This, Arg.getIndirectAddress());
1807 else
1808 Arg = ParamValue::forDirect(This);
1809 }
1810 }
John McCall147d0212011-02-22 22:38:33 +00001811 }
1812
John McCall7f416cc2015-09-08 08:05:57 +00001813 Address DeclPtr = Address::invalid();
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001814 bool DoStore = false;
1815 bool IsScalar = hasScalarEvaluationKind(Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001816 // If we already have a pointer to the argument, reuse the input pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001817 if (Arg.isIndirect()) {
1818 DeclPtr = Arg.getIndirectAddress();
Reid Kleckner5e8edba2014-04-02 00:16:53 +00001819 // If we have a prettier pointer type at this point, bitcast to that.
John McCall7f416cc2015-09-08 08:05:57 +00001820 unsigned AS = DeclPtr.getType()->getAddressSpace();
Reid Kleckner5e8edba2014-04-02 00:16:53 +00001821 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
John McCall7f416cc2015-09-08 08:05:57 +00001822 if (DeclPtr.getType() != IRTy)
1823 DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
1824
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001825 // Push a destructor cleanup for this parameter if the ABI requires it.
Reid Kleckner19819442014-07-25 21:39:46 +00001826 // Don't push a cleanup in a thunk for a method that will also emit a
1827 // cleanup.
1828 if (!IsScalar && !CurFuncIsThunk &&
Reid Kleckner739756c2013-12-04 19:23:12 +00001829 getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001830 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
1831 if (RD && RD->hasNonTrivialDestructor())
1832 pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001833 }
Chris Lattner53621a52007-06-13 20:44:40 +00001834 } else {
Daniel Dunbar3d33fab2010-02-08 22:53:07 +00001835 // Otherwise, create a temporary to hold the value.
John McCall7f416cc2015-09-08 08:05:57 +00001836 DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
1837 D.getName() + ".addr");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001838 DoStore = true;
1839 }
Mike Stump11289f42009-09-09 15:08:12 +00001840
John McCall7f416cc2015-09-08 08:05:57 +00001841 llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
1842
1843 LValue lv = MakeAddrLValue(DeclPtr, Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001844 if (IsScalar) {
John McCall31168b02011-06-15 23:02:42 +00001845 Qualifiers qs = Ty.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00001846 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1847 // We honor __attribute__((ns_consumed)) for types with lifetime.
1848 // For __strong, it's handled by just skipping the initial retain;
1849 // otherwise we have to balance out the initial +1 with an extra
1850 // cleanup to do the release at the end of the function.
1851 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1852
1853 // 'self' is always formally __strong, but if this is not an
1854 // init method then we don't want to retain it.
John McCalld4631322011-06-17 06:42:21 +00001855 if (D.isARCPseudoStrong()) {
John McCall31168b02011-06-15 23:02:42 +00001856 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1857 assert(&D == method->getSelfDecl());
John McCalld4631322011-06-17 06:42:21 +00001858 assert(lt == Qualifiers::OCL_Strong);
1859 assert(qs.hasConst());
John McCall31168b02011-06-15 23:02:42 +00001860 assert(method->getMethodFamily() != OMF_init);
John McCall10123692011-06-15 23:40:09 +00001861 (void) method;
John McCall31168b02011-06-15 23:02:42 +00001862 lt = Qualifiers::OCL_ExplicitNone;
1863 }
1864
Saleem Abdulrasoolda6784e2017-06-27 18:37:51 +00001865 // Load objects passed indirectly.
1866 if (Arg.isIndirect() && !ArgVal)
1867 ArgVal = Builder.CreateLoad(DeclPtr);
1868
John McCall31168b02011-06-15 23:02:42 +00001869 if (lt == Qualifiers::OCL_Strong) {
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001870 if (!isConsumed) {
1871 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1872 // use objc_storeStrong(&dest, value) for retaining the
1873 // object. But first, store a null into 'dest' because
1874 // objc_storeStrong attempts to release its old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001875 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001876 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
John McCall7f416cc2015-09-08 08:05:57 +00001877 EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001878 DoStore = false;
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001879 }
1880 else
John McCall31168b02011-06-15 23:02:42 +00001881 // Don't use objc_retainBlock for block pointers, because we
1882 // don't want to Block_copy something just because we got it
1883 // as a parameter.
John McCall7f416cc2015-09-08 08:05:57 +00001884 ArgVal = EmitARCRetainNonBlock(ArgVal);
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001885 }
John McCall31168b02011-06-15 23:02:42 +00001886 } else {
1887 // Push the cleanup for a consumed parameter.
John McCallcdda29c2013-03-13 03:10:54 +00001888 if (isConsumed) {
1889 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1890 ? ARCPreciseLifetime : ARCImpreciseLifetime);
John McCall7f416cc2015-09-08 08:05:57 +00001891 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
John McCallcdda29c2013-03-13 03:10:54 +00001892 precise);
1893 }
John McCall31168b02011-06-15 23:02:42 +00001894
1895 if (lt == Qualifiers::OCL_Weak) {
John McCall7f416cc2015-09-08 08:05:57 +00001896 EmitARCInitWeak(DeclPtr, ArgVal);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001897 DoStore = false; // The weak init is a store, no need to do two.
John McCall31168b02011-06-15 23:02:42 +00001898 }
1899 }
1900
1901 // Enter the cleanup scope.
1902 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1903 }
Chris Lattner53621a52007-06-13 20:44:40 +00001904 }
1905
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001906 // Store the initial value into the alloca.
1907 if (DoStore)
John McCall7f416cc2015-09-08 08:05:57 +00001908 EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001909
John McCall7f416cc2015-09-08 08:05:57 +00001910 setAddrOfLocalVar(&D, DeclPtr);
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001911
1912 // Emit debug info for param declaration.
Alexey Samsonov74a38682012-05-04 07:39:27 +00001913 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001914 if (CGM.getCodeGenOpts().getDebugInfo() >=
1915 codegenoptions::LimitedDebugInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001916 DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001917 }
1918 }
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001919
1920 if (D.hasAttr<AnnotateAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00001921 EmitVarAnnotations(&D, DeclPtr.getPointer());
Vedant Kumar42c17ec2017-03-14 01:56:34 +00001922
1923 // We can only check return value nullability if all arguments to the
1924 // function satisfy their nullability preconditions. This makes it necessary
1925 // to emit null checks for args in the function body itself.
1926 if (requiresReturnValueNullabilityCheck()) {
1927 auto Nullability = Ty->getNullability(getContext());
1928 if (Nullability && *Nullability == NullabilityKind::NonNull) {
1929 SanitizerScope SanScope(this);
1930 RetValNullabilityPrecondition =
1931 Builder.CreateAnd(RetValNullabilityPrecondition,
1932 Builder.CreateIsNotNull(Arg.getAnyValue()));
1933 }
1934 }
Chris Lattner53621a52007-06-13 20:44:40 +00001935}
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001936
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001937void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
1938 CodeGenFunction *CGF) {
1939 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
1940 return;
1941 getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
1942}