blob: 19cdc24270ce2b9ee956a553d04ccf7b77a14333 [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) {
Alexey Baderbed40092017-11-15 11:38:17 +0000165 // Static sampler variables translated to function calls.
166 if (D.getType()->isSamplerT())
167 return;
168
Eric Christopher31ab1302011-08-23 22:38:00 +0000169 llvm::GlobalValue::LinkageTypes Linkage =
David Majnemer27d69db2014-04-28 22:17:59 +0000170 CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000171
David Majnemer27d69db2014-04-28 22:17:59 +0000172 // FIXME: We need to force the emission/use of a guard variable for
173 // some variables even if we can constant-evaluate them because
174 // we can't guarantee every translation unit will constant-evaluate them.
Eric Christopher31ab1302011-08-23 22:38:00 +0000175
John McCall1c9c3fd2010-10-15 04:57:14 +0000176 return EmitStaticVarDecl(D, Linkage);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000177 }
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000178
Anastasia Stulovabcea6962015-09-30 14:08:20 +0000179 if (D.getType().getAddressSpace() == LangAS::opencl_local)
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000180 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
181
182 assert(D.hasLocalStorage());
183 return EmitAutoVarDecl(D);
Chris Lattner03df1222007-06-02 04:53:11 +0000184}
185
Reid Kleckner453e0562014-10-08 01:07:54 +0000186static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
187 if (CGM.getLangOpts().CPlusPlus)
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000188 return CGM.getMangledName(&D).str();
189
Reid Kleckner453e0562014-10-08 01:07:54 +0000190 // If this isn't C++, we don't need a mangled name, just a pretty one.
191 assert(!D.isExternallyVisible() && "name shouldn't matter");
192 std::string ContextName;
193 const DeclContext *DC = D.getDeclContext();
Alexey Bataev43f74392015-05-07 06:28:46 +0000194 if (auto *CD = dyn_cast<CapturedDecl>(DC))
195 DC = cast<DeclContext>(CD->getNonClosureContext());
Reid Kleckner453e0562014-10-08 01:07:54 +0000196 if (const auto *FD = dyn_cast<FunctionDecl>(DC))
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000197 ContextName = CGM.getMangledName(FD);
Reid Kleckner453e0562014-10-08 01:07:54 +0000198 else if (const auto *BD = dyn_cast<BlockDecl>(DC))
199 ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
200 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
201 ContextName = OMD->getSelector().getAsString();
Chris Lattnere99c1102009-12-05 08:22:11 +0000202 else
David Blaikie83d382b2011-09-23 05:06:16 +0000203 llvm_unreachable("Unknown context for static var decl");
Eric Christopher31ab1302011-08-23 22:38:00 +0000204
Reid Kleckner453e0562014-10-08 01:07:54 +0000205 ContextName += "." + D.getNameAsString();
206 return ContextName;
Chris Lattnere99c1102009-12-05 08:22:11 +0000207}
208
Reid Kleckner453e0562014-10-08 01:07:54 +0000209llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
210 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
211 // In general, we don't always emit static var decls once before we reference
212 // them. It is possible to reference them before emitting the function that
213 // contains them, and it is possible to emit the containing function multiple
214 // times.
215 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
216 return ExistingGV;
217
Chris Lattnerfc4379f2008-04-06 23:10:54 +0000218 QualType Ty = D.getType();
Eli Friedmana682d392008-02-15 12:20:59 +0000219 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begemanfaae0812008-04-19 04:17:09 +0000220
Benjamin Kramerddbb2b82011-11-20 21:05:04 +0000221 // Use the label if the variable is renamed with the asm-label extension.
222 std::string Name;
Benjamin Kramer5642e192011-11-21 15:47:23 +0000223 if (D.hasAttr<AsmLabelAttr>())
Reid Kleckner453e0562014-10-08 01:07:54 +0000224 Name = getMangledName(&D);
Benjamin Kramer5642e192011-11-21 15:47:23 +0000225 else
Reid Kleckner453e0562014-10-08 01:07:54 +0000226 Name = getStaticDeclName(*this, D);
Nate Begemanfaae0812008-04-19 04:17:09 +0000227
Reid Kleckner453e0562014-10-08 01:07:54 +0000228 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
Alexander Richardson6d989432017-10-15 18:48:14 +0000229 LangAS AS = GetGlobalVarAddressSpace(&D);
Yaxun Liucbf647c2017-07-08 13:24:52 +0000230 unsigned TargetAS = getContext().getTargetAddressSpace(AS);
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000231
232 // Local address space cannot have an initializer.
233 llvm::Constant *Init = nullptr;
234 if (Ty.getAddressSpace() != LangAS::opencl_local)
235 Init = EmitNullConstant(Ty);
236 else
237 Init = llvm::UndefValue::get(LTy);
238
Yaxun Liucbf647c2017-07-08 13:24:52 +0000239 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
240 getModule(), LTy, Ty.isConstant(getContext()), Linkage, Init, Name,
241 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
Ken Dyck160146e2010-01-27 17:10:57 +0000242 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Rafael Espindola699f5d62018-02-07 22:15:33 +0000243 setGVProperties(GV, &D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000244
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +0000245 if (supportsCOMDAT() && GV->isWeakForLinker())
246 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Rafael Espindola0d4fb982015-01-12 22:13:53 +0000247
Richard Smithfd3834f2013-04-13 02:43:54 +0000248 if (D.getTLSKind())
Reid Kleckner453e0562014-10-08 01:07:54 +0000249 setTLSMode(GV, D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000250
Hans Wennborgef2272c2014-06-18 15:55:13 +0000251 if (D.isExternallyVisible()) {
252 if (D.hasAttr<DLLImportAttr>())
253 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
254 else if (D.hasAttr<DLLExportAttr>())
255 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
256 }
257
Eli Benderskycb399432014-03-24 22:05:38 +0000258 // Make sure the result is of the correct type.
Alexander Richardson6d989432017-10-15 18:48:14 +0000259 LangAS ExpectedAS = Ty.getAddressSpace();
Reid Kleckner453e0562014-10-08 01:07:54 +0000260 llvm::Constant *Addr = GV;
Yaxun Liucbf647c2017-07-08 13:24:52 +0000261 if (AS != ExpectedAS) {
262 Addr = getTargetCodeGenInfo().performAddrSpaceCast(
263 *this, GV, AS, ExpectedAS,
264 LTy->getPointerTo(getContext().getTargetAddressSpace(ExpectedAS)));
Eli Benderskycb399432014-03-24 22:05:38 +0000265 }
266
Reid Kleckner453e0562014-10-08 01:07:54 +0000267 setStaticLocalDeclAddress(&D, Addr);
268
269 // Ensure that the static local gets initialized by making sure the parent
270 // function gets emitted eventually.
271 const Decl *DC = cast<Decl>(D.getDeclContext());
272
273 // We can't name blocks or captured statements directly, so try to emit their
274 // parents.
275 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
276 DC = DC->getNonClosureContext();
277 // FIXME: Ensure that global blocks get emitted.
278 if (!DC)
279 return Addr;
280 }
281
282 GlobalDecl GD;
283 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
284 GD = GlobalDecl(CD, Ctor_Base);
285 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
286 GD = GlobalDecl(DD, Dtor_Base);
287 else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
288 GD = GlobalDecl(FD);
289 else {
290 // Don't do anything for Obj-C method decls or global closures. We should
291 // never defer them.
292 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
293 }
294 if (GD.getDecl())
295 (void)GetAddrOfGlobal(GD);
296
297 return Addr;
Daniel Dunbar22a87f92009-02-25 19:24:29 +0000298}
299
Richard Smith6331c402012-02-13 22:16:19 +0000300/// hasNontrivialDestruction - Determine whether a type's destruction is
301/// non-trivial. If so, and the variable uses static initialization, we must
302/// register its destructor to run on exit.
303static bool hasNontrivialDestruction(QualType T) {
304 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
305 return RD && !RD->hasTrivialDestructor();
306}
307
Chandler Carruth84537952012-03-30 19:44:53 +0000308/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
309/// global variable that has already been created for it. If the initializer
310/// has a different type than GV does, this may free GV and return a different
311/// one. Otherwise it just returns GV.
312llvm::GlobalVariable *
John McCall1c9c3fd2010-10-15 04:57:14 +0000313CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
Chandler Carruth84537952012-03-30 19:44:53 +0000314 llvm::GlobalVariable *GV) {
John McCallde0fe072017-08-15 21:42:52 +0000315 ConstantEmitter emitter(*this);
316 llvm::Constant *Init = emitter.tryEmitForInitializer(D);
John McCall70013b62010-07-15 23:40:35 +0000317
Chris Lattnere99c1102009-12-05 08:22:11 +0000318 // If constant emission failed, then this should be a C++ static
319 // initializer.
Chandler Carruth84537952012-03-30 19:44:53 +0000320 if (!Init) {
Richard Smith9c6890a2012-11-01 22:30:59 +0000321 if (!getLangOpts().CPlusPlus)
Chris Lattnere99c1102009-12-05 08:22:11 +0000322 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
Matthias Braun44bfe032017-01-10 17:43:01 +0000323 else if (HaveInsertPoint()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000324 // Since we have a static initializer, this global variable can't
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000325 // be constant.
Chandler Carruth84537952012-03-30 19:44:53 +0000326 GV->setConstant(false);
John McCall68ff0372010-09-08 01:44:27 +0000327
Chandler Carruth84537952012-03-30 19:44:53 +0000328 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000329 }
Chandler Carruth84537952012-03-30 19:44:53 +0000330 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000331 }
John McCall70013b62010-07-15 23:40:35 +0000332
Chris Lattnere99c1102009-12-05 08:22:11 +0000333 // The initializer may differ in type from the global. Rewrite
334 // the global to match the initializer. (We have to do this
335 // because some types, like unions, can't be completely represented
336 // in the LLVM type system.)
Chandler Carruth84537952012-03-30 19:44:53 +0000337 if (GV->getType()->getElementType() != Init->getType()) {
338 llvm::GlobalVariable *OldGV = GV;
339
340 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
341 OldGV->isConstant(),
342 OldGV->getLinkage(), Init, "",
343 /*InsertBefore*/ OldGV,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +0000344 OldGV->getThreadLocalMode(),
Chandler Carruth84537952012-03-30 19:44:53 +0000345 CGM.getContext().getTargetAddressSpace(D.getType()));
346 GV->setVisibility(OldGV->getVisibility());
Rafael Espindola699f5d62018-02-07 22:15:33 +0000347 GV->setDSOLocal(OldGV->isDSOLocal());
Reid Klecknereab97d32015-07-20 20:35:30 +0000348 GV->setComdat(OldGV->getComdat());
Eric Christopher31ab1302011-08-23 22:38:00 +0000349
Chris Lattnere99c1102009-12-05 08:22:11 +0000350 // Steal the name of the old global
Chandler Carruth84537952012-03-30 19:44:53 +0000351 GV->takeName(OldGV);
Eric Christopher31ab1302011-08-23 22:38:00 +0000352
Chris Lattnere99c1102009-12-05 08:22:11 +0000353 // Replace all uses of the old global with the new global
Chandler Carruth84537952012-03-30 19:44:53 +0000354 llvm::Constant *NewPtrForOldDecl =
355 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
356 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eric Christopher31ab1302011-08-23 22:38:00 +0000357
Chris Lattnere99c1102009-12-05 08:22:11 +0000358 // Erase the old global, since it is no longer used.
Chandler Carruth84537952012-03-30 19:44:53 +0000359 OldGV->eraseFromParent();
Chris Lattnere99c1102009-12-05 08:22:11 +0000360 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000361
Chandler Carruth84537952012-03-30 19:44:53 +0000362 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
363 GV->setInitializer(Init);
Richard Smith6331c402012-02-13 22:16:19 +0000364
John McCallde0fe072017-08-15 21:42:52 +0000365 emitter.finalize(GV);
366
Matthias Braun44bfe032017-01-10 17:43:01 +0000367 if (hasNontrivialDestruction(D.getType()) && HaveInsertPoint()) {
Richard Smith6331c402012-02-13 22:16:19 +0000368 // We have a constant initializer, but a nontrivial destructor. We still
369 // need to perform a guarded "initialization" in order to register the
Richard Smithe070fd22012-02-17 06:48:11 +0000370 // destructor.
Chandler Carruth84537952012-03-30 19:44:53 +0000371 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
Richard Smith6331c402012-02-13 22:16:19 +0000372 }
373
Chandler Carruth84537952012-03-30 19:44:53 +0000374 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000375}
376
John McCall1c9c3fd2010-10-15 04:57:14 +0000377void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000378 llvm::GlobalValue::LinkageTypes Linkage) {
John McCallb88a5662012-03-30 21:00:39 +0000379 // Check to see if we already have a global variable for this
380 // declaration. This can happen when double-emitting function
381 // bodies, e.g. with complete and base constructors.
Reid Kleckner453e0562014-10-08 01:07:54 +0000382 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
John McCall7f416cc2015-09-08 08:05:57 +0000383 CharUnits alignment = getContext().getDeclAlign(&D);
Daniel Dunbara374e602009-02-25 19:45:19 +0000384
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000385 // Store into LocalDeclMap before generating initializer to handle
386 // circular references.
John McCall7f416cc2015-09-08 08:05:57 +0000387 setAddrOfLocalVar(&D, Address(addr, alignment));
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000388
John McCall4a39ab82010-05-04 20:45:42 +0000389 // We can't have a VLA here, but we can have a pointer to a VLA,
390 // even though that doesn't really make any sense.
Eli Friedmanbc633be2009-04-20 03:54:15 +0000391 // Make sure to evaluate VLA bounds now so that we have them for later.
392 if (D.getType()->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000393 EmitVariablyModifiedType(D.getType());
Eric Christopher31ab1302011-08-23 22:38:00 +0000394
John McCallb88a5662012-03-30 21:00:39 +0000395 // Save the type in case adding the initializer forces a type change.
396 llvm::Type *expectedType = addr->getType();
Eli Friedmanbc633be2009-04-20 03:54:15 +0000397
Eli Benderskycb399432014-03-24 22:05:38 +0000398 llvm::GlobalVariable *var =
399 cast<llvm::GlobalVariable>(addr->stripPointerCasts());
Artem Belevich4d430ba2016-05-09 22:09:56 +0000400
401 // CUDA's local and local static __shared__ variables should not
402 // have any non-empty initializers. This is ensured by Sema.
403 // Whatever initializer such variable may have when it gets here is
404 // a no-op and should not be emitted.
405 bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
406 D.hasAttr<CUDASharedAttr>();
Chris Lattnere99c1102009-12-05 08:22:11 +0000407 // If this value has an initializer, emit it.
Artem Belevich4d430ba2016-05-09 22:09:56 +0000408 if (D.getInit() && !isCudaSharedVar)
John McCallb88a5662012-03-30 21:00:39 +0000409 var = AddInitializerToStaticVarDecl(D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000410
John McCall7f416cc2015-09-08 08:05:57 +0000411 var->setAlignment(alignment.getQuantity());
Chris Lattner4d941092010-03-10 23:59:59 +0000412
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000413 if (D.hasAttr<AnnotateAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000414 CGM.AddGlobalAnnotations(&D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000415
Javed Absar2a67c9e2017-06-05 10:11:57 +0000416 if (auto *SA = D.getAttr<PragmaClangBSSSectionAttr>())
417 var->addAttribute("bss-section", SA->getName());
418 if (auto *SA = D.getAttr<PragmaClangDataSectionAttr>())
419 var->addAttribute("data-section", SA->getName());
420 if (auto *SA = D.getAttr<PragmaClangRodataSectionAttr>())
421 var->addAttribute("rodata-section", SA->getName());
422
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000423 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000424 var->setSection(SA->getName());
Mike Stump11289f42009-09-09 15:08:12 +0000425
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000426 if (D.hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +0000427 CGM.addUsedGlobal(var);
Daniel Dunbar128a1382009-02-13 22:08:43 +0000428
Chandler Carruth84537952012-03-30 19:44:53 +0000429 // We may have to cast the constant because of the initializer
430 // mismatch above.
431 //
432 // FIXME: It is really dangerous to store this in the map; if anyone
433 // RAUW's the GV uses of this constant will be invalid.
Eli Benderskycb399432014-03-24 22:05:38 +0000434 llvm::Constant *castedAddr =
435 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
John McCall7f416cc2015-09-08 08:05:57 +0000436 if (var != castedAddr)
437 LocalDeclMap.find(&D)->second = Address(castedAddr, alignment);
John McCallb88a5662012-03-30 21:00:39 +0000438 CGM.setStaticLocalDeclAddress(&D, castedAddr);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000439
Alexey Samsonov4b8de112014-08-01 21:35:28 +0000440 CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000441
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000442 // Emit global variable debug descriptor for static vars.
Anders Carlsson63784f42009-02-13 08:11:52 +0000443 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov74a38682012-05-04 07:39:27 +0000444 if (DI &&
Benjamin Kramer8c305922016-02-02 11:06:51 +0000445 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
Daniel Dunbarb9fd9022008-10-17 16:15:48 +0000446 DI->setLocation(D.getLocation());
John McCallb88a5662012-03-30 21:00:39 +0000447 DI->EmitGlobalVariable(var, &D);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000448 }
Anders Carlssonf94cd1f2007-10-17 00:52:43 +0000449}
Mike Stump11289f42009-09-09 15:08:12 +0000450
John McCall2b7fc382010-07-13 20:32:21 +0000451namespace {
David Blaikie7e70d682015-08-18 22:40:54 +0000452 struct DestroyObject final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000453 DestroyObject(Address addr, QualType type,
John McCall178360e2011-07-11 08:38:19 +0000454 CodeGenFunction::Destroyer *destroyer,
455 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +0000456 : addr(addr), type(type), destroyer(destroyer),
John McCall178360e2011-07-11 08:38:19 +0000457 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall2b7fc382010-07-13 20:32:21 +0000458
John McCall7f416cc2015-09-08 08:05:57 +0000459 Address addr;
John McCall82fe67b2011-07-09 01:37:26 +0000460 QualType type;
Peter Collingbourne1425b452012-01-26 03:33:36 +0000461 CodeGenFunction::Destroyer *destroyer;
John McCall178360e2011-07-11 08:38:19 +0000462 bool useEHCleanupForArray;
John McCall2b7fc382010-07-13 20:32:21 +0000463
Craig Topper4f12f102014-03-12 06:41:41 +0000464 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +0000465 // Don't use an EH cleanup recursively from an EH cleanup.
John McCall30317fd2011-07-12 20:27:29 +0000466 bool useEHCleanupForArray =
467 flags.isForNormalCleanup() && this->useEHCleanupForArray;
John McCall178360e2011-07-11 08:38:19 +0000468
469 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
John McCall2b7fc382010-07-13 20:32:21 +0000470 }
471 };
472
David Blaikie7e70d682015-08-18 22:40:54 +0000473 struct DestroyNRVOVariable final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000474 DestroyNRVOVariable(Address addr,
John McCall82fe67b2011-07-09 01:37:26 +0000475 const CXXDestructorDecl *Dtor,
476 llvm::Value *NRVOFlag)
477 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
John McCall2b7fc382010-07-13 20:32:21 +0000478
479 const CXXDestructorDecl *Dtor;
480 llvm::Value *NRVOFlag;
John McCall7f416cc2015-09-08 08:05:57 +0000481 Address Loc;
John McCall2b7fc382010-07-13 20:32:21 +0000482
Craig Topper4f12f102014-03-12 06:41:41 +0000483 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall2b7fc382010-07-13 20:32:21 +0000484 // Along the exceptions path we always execute the dtor.
John McCall30317fd2011-07-12 20:27:29 +0000485 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
John McCall2b7fc382010-07-13 20:32:21 +0000486
Craig Topper8a13c412014-05-21 05:09:00 +0000487 llvm::BasicBlock *SkipDtorBB = nullptr;
John McCall2b7fc382010-07-13 20:32:21 +0000488 if (NRVO) {
489 // If we exited via NRVO, we skip the destructor call.
490 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
491 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
John McCall7f416cc2015-09-08 08:05:57 +0000492 llvm::Value *DidNRVO =
493 CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
John McCall2b7fc382010-07-13 20:32:21 +0000494 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
495 CGF.EmitBlock(RunDtorBB);
496 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000497
John McCall2b7fc382010-07-13 20:32:21 +0000498 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +0000499 /*ForVirtualBase=*/false,
500 /*Delegating=*/false,
501 Loc);
John McCall2b7fc382010-07-13 20:32:21 +0000502
503 if (NRVO) CGF.EmitBlock(SkipDtorBB);
504 }
505 };
John McCall2b7fc382010-07-13 20:32:21 +0000506
David Blaikie7e70d682015-08-18 22:40:54 +0000507 struct CallStackRestore final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000508 Address Stack;
509 CallStackRestore(Address Stack) : Stack(Stack) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000510 void Emit(CodeGenFunction &CGF, Flags flags) override {
Benjamin Kramer76399eb2011-09-27 21:06:10 +0000511 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
John McCalla464ff92010-07-21 06:13:08 +0000512 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
513 CGF.Builder.CreateCall(F, V);
514 }
515 };
516
David Blaikie7e70d682015-08-18 22:40:54 +0000517 struct ExtendGCLifetime final : EHScopeStack::Cleanup {
John McCall1bd25562011-06-24 23:21:27 +0000518 const VarDecl &Var;
519 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
520
Craig Topper4f12f102014-03-12 06:41:41 +0000521 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1bd25562011-06-24 23:21:27 +0000522 // Compute the address of the local variable, in case it's a
523 // byref or something.
John McCall113bee02012-03-10 09:33:50 +0000524 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
525 Var.getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +0000526 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
527 SourceLocation());
John McCall1bd25562011-06-24 23:21:27 +0000528 CGF.EmitExtendGCLifetime(value);
529 }
530 };
531
David Blaikie7e70d682015-08-18 22:40:54 +0000532 struct CallCleanupFunction final : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000533 llvm::Constant *CleanupFn;
534 const CGFunctionInfo &FnInfo;
John McCalla464ff92010-07-21 06:13:08 +0000535 const VarDecl &Var;
Eric Christopher31ab1302011-08-23 22:38:00 +0000536
John McCalla464ff92010-07-21 06:13:08 +0000537 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCallc533cb72011-02-22 06:44:22 +0000538 const VarDecl *Var)
539 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalla464ff92010-07-21 06:13:08 +0000540
Craig Topper4f12f102014-03-12 06:41:41 +0000541 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall113bee02012-03-10 09:33:50 +0000542 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
543 Var.getType(), VK_LValue, SourceLocation());
John McCallc533cb72011-02-22 06:44:22 +0000544 // Compute the address of the local variable, in case it's a byref
545 // or something.
John McCall7f416cc2015-09-08 08:05:57 +0000546 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer();
John McCallc533cb72011-02-22 06:44:22 +0000547
John McCalla464ff92010-07-21 06:13:08 +0000548 // In some cases, the type of the function argument will be different from
549 // the type of the pointer. An example of this is
550 // void f(void* arg);
551 // __attribute__((cleanup(f))) void *g;
552 //
553 // To fix this we insert a bitcast here.
554 QualType ArgTy = FnInfo.arg_begin()->type;
555 llvm::Value *Arg =
556 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
557
558 CallArgList Args;
Eli Friedman43dca6a2011-05-02 17:57:46 +0000559 Args.add(RValue::get(Arg),
560 CGF.getContext().getPointerType(Var.getType()));
John McCallb92ab1a2016-10-26 23:46:34 +0000561 auto Callee = CGCallee::forDirect(CleanupFn);
562 CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
John McCalla464ff92010-07-21 06:13:08 +0000563 }
564 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000565} // end anonymous namespace
John McCalla464ff92010-07-21 06:13:08 +0000566
John McCall31168b02011-06-15 23:02:42 +0000567/// EmitAutoVarWithLifetime - Does the setup required for an automatic
568/// variable with lifetime.
569static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
John McCall7f416cc2015-09-08 08:05:57 +0000570 Address addr,
John McCall31168b02011-06-15 23:02:42 +0000571 Qualifiers::ObjCLifetime lifetime) {
572 switch (lifetime) {
573 case Qualifiers::OCL_None:
574 llvm_unreachable("present but none");
575
576 case Qualifiers::OCL_ExplicitNone:
577 // nothing to do
578 break;
579
580 case Qualifiers::OCL_Strong: {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000581 CodeGenFunction::Destroyer *destroyer =
John McCall4bd0fb12011-07-12 16:41:08 +0000582 (var.hasAttr<ObjCPreciseLifetimeAttr>()
583 ? CodeGenFunction::destroyARCStrongPrecise
584 : CodeGenFunction::destroyARCStrongImprecise);
585
586 CleanupKind cleanupKind = CGF.getARCCleanupKind();
587 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
588 cleanupKind & EHCleanup);
John McCall31168b02011-06-15 23:02:42 +0000589 break;
590 }
591 case Qualifiers::OCL_Autoreleasing:
592 // nothing to do
593 break;
Eric Christopher31ab1302011-08-23 22:38:00 +0000594
John McCall31168b02011-06-15 23:02:42 +0000595 case Qualifiers::OCL_Weak:
596 // __weak objects always get EH cleanups; otherwise, exceptions
597 // could cause really nasty crashes instead of mere leaks.
John McCall4bd0fb12011-07-12 16:41:08 +0000598 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
599 CodeGenFunction::destroyARCWeak,
600 /*useEHCleanup*/ true);
John McCall31168b02011-06-15 23:02:42 +0000601 break;
602 }
603}
604
605static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
606 if (const Expr *e = dyn_cast<Expr>(s)) {
607 // Skip the most common kinds of expressions that make
608 // hierarchy-walking expensive.
609 s = e = e->IgnoreParenCasts();
610
611 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
612 return (ref->getDecl() == &var);
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000613 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
614 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +0000615 for (const auto &I : block->captures()) {
616 if (I.getVariable() == &var)
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000617 return true;
618 }
619 }
John McCall31168b02011-06-15 23:02:42 +0000620 }
621
Benjamin Kramer642f1732015-07-02 21:03:14 +0000622 for (const Stmt *SubStmt : s->children())
623 // SubStmt might be null; as in missing decl or conditional of an if-stmt.
624 if (SubStmt && isAccessedBy(var, SubStmt))
John McCall31168b02011-06-15 23:02:42 +0000625 return true;
626
627 return false;
628}
629
630static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
631 if (!decl) return false;
632 if (!isa<VarDecl>(decl)) return false;
633 const VarDecl *var = cast<VarDecl>(decl);
634 return isAccessedBy(*var, e);
635}
636
John McCallf8a9b662015-10-21 18:06:31 +0000637static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
638 const LValue &destLV, const Expr *init) {
John McCall0204e342015-11-16 22:11:41 +0000639 bool needsCast = false;
640
John McCallf8a9b662015-10-21 18:06:31 +0000641 while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
642 switch (castExpr->getCastKind()) {
643 // Look through casts that don't require representation changes.
644 case CK_NoOp:
645 case CK_BitCast:
646 case CK_BlockPointerToObjCPointerCast:
John McCall0204e342015-11-16 22:11:41 +0000647 needsCast = true;
John McCallf8a9b662015-10-21 18:06:31 +0000648 break;
649
650 // If we find an l-value to r-value cast from a __weak variable,
651 // emit this operation as a copy or move.
652 case CK_LValueToRValue: {
653 const Expr *srcExpr = castExpr->getSubExpr();
654 if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
655 return false;
656
657 // Emit the source l-value.
658 LValue srcLV = CGF.EmitLValue(srcExpr);
659
John McCall0204e342015-11-16 22:11:41 +0000660 // Handle a formal type change to avoid asserting.
661 auto srcAddr = srcLV.getAddress();
662 if (needsCast) {
663 srcAddr = CGF.Builder.CreateElementBitCast(srcAddr,
664 destLV.getAddress().getElementType());
665 }
666
John McCallf8a9b662015-10-21 18:06:31 +0000667 // If it was an l-value, use objc_copyWeak.
668 if (srcExpr->getValueKind() == VK_LValue) {
John McCall0204e342015-11-16 22:11:41 +0000669 CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr);
John McCallf8a9b662015-10-21 18:06:31 +0000670 } else {
671 assert(srcExpr->getValueKind() == VK_XValue);
John McCall0204e342015-11-16 22:11:41 +0000672 CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr);
John McCallf8a9b662015-10-21 18:06:31 +0000673 }
674 return true;
675 }
676
677 // Stop at anything else.
678 default:
679 return false;
680 }
681
682 init = castExpr->getSubExpr();
John McCallf8a9b662015-10-21 18:06:31 +0000683 }
684 return false;
685}
686
John McCall1553b192011-06-16 04:16:24 +0000687static void drillIntoBlockVariable(CodeGenFunction &CGF,
688 LValue &lvalue,
689 const VarDecl *var) {
John McCall7f416cc2015-09-08 08:05:57 +0000690 lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var));
John McCall1553b192011-06-16 04:16:24 +0000691}
692
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000693void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS,
694 SourceLocation Loc) {
695 if (!SanOpts.has(SanitizerKind::NullabilityAssign))
696 return;
697
698 auto Nullability = LHS.getType()->getNullability(getContext());
699 if (!Nullability || *Nullability != NullabilityKind::NonNull)
700 return;
701
702 // Check if the right hand side of the assignment is nonnull, if the left
703 // hand side must be nonnull.
704 SanitizerScope SanScope(this);
705 llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS);
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000706 llvm::Constant *StaticData[] = {
707 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(LHS.getType()),
Simon Pilgrim2df19982017-03-14 21:43:52 +0000708 llvm::ConstantInt::get(Int8Ty, 0), // The LogAlignment info is unused.
Vedant Kumar2b9f48a2017-03-14 16:48:29 +0000709 llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)};
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000710 EmitCheck({{IsNotNull, SanitizerKind::NullabilityAssign}},
711 SanitizerHandler::TypeMismatch, StaticData, RHS);
712}
713
David Blaikie73ca5692014-12-09 00:32:22 +0000714void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +0000715 LValue lvalue, bool capturedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000716 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +0000717 if (!lifetime) {
718 llvm::Value *value = EmitScalarExpr(init);
John McCall1553b192011-06-16 04:16:24 +0000719 if (capturedByInit)
720 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000721 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
David Blaikie66e41972015-01-14 07:38:27 +0000722 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
John McCall31168b02011-06-15 23:02:42 +0000723 return;
724 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000725
Fariborz Jahaniana5a469e2014-03-14 15:40:54 +0000726 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
727 init = DIE->getExpr();
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000728
John McCall31168b02011-06-15 23:02:42 +0000729 // If we're emitting a value with lifetime, we have to do the
730 // initialization *before* we leave the cleanup scopes.
John McCall08ef4662011-11-10 08:15:53 +0000731 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
732 enterFullExpression(ewc);
John McCall31168b02011-06-15 23:02:42 +0000733 init = ewc->getSubExpr();
John McCall08ef4662011-11-10 08:15:53 +0000734 }
735 CodeGenFunction::RunCleanupsScope Scope(*this);
John McCall31168b02011-06-15 23:02:42 +0000736
737 // We have to maintain the illusion that the variable is
738 // zero-initialized. If the variable might be accessed in its
739 // initializer, zero-initialize before running the initializer, then
740 // actually perform the initialization with an assign.
741 bool accessedByInit = false;
742 if (lifetime != Qualifiers::OCL_ExplicitNone)
John McCallb726a552011-07-28 07:23:35 +0000743 accessedByInit = (capturedByInit || isAccessedBy(D, init));
John McCall31168b02011-06-15 23:02:42 +0000744 if (accessedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000745 LValue tempLV = lvalue;
John McCall31168b02011-06-15 23:02:42 +0000746 // Drill down to the __block object if necessary.
John McCall31168b02011-06-15 23:02:42 +0000747 if (capturedByInit) {
748 // We can use a simple GEP for this because it can't have been
749 // moved yet.
John McCall7f416cc2015-09-08 08:05:57 +0000750 tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(),
751 cast<VarDecl>(D),
752 /*follow*/ false));
John McCall31168b02011-06-15 23:02:42 +0000753 }
754
John McCall7f416cc2015-09-08 08:05:57 +0000755 auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType());
Yaxun Liu402804b2016-12-15 08:09:08 +0000756 llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());
Eric Christopher31ab1302011-08-23 22:38:00 +0000757
John McCall31168b02011-06-15 23:02:42 +0000758 // If __weak, we want to use a barrier under certain conditions.
759 if (lifetime == Qualifiers::OCL_Weak)
John McCall1553b192011-06-16 04:16:24 +0000760 EmitARCInitWeak(tempLV.getAddress(), zero);
John McCall31168b02011-06-15 23:02:42 +0000761
762 // Otherwise just do a simple store.
763 else
David Chisnallfa35df62012-01-16 17:27:18 +0000764 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000765 }
766
767 // Emit the initializer.
Craig Topper8a13c412014-05-21 05:09:00 +0000768 llvm::Value *value = nullptr;
John McCall31168b02011-06-15 23:02:42 +0000769
770 switch (lifetime) {
771 case Qualifiers::OCL_None:
772 llvm_unreachable("present but none");
773
774 case Qualifiers::OCL_ExplicitNone:
John McCalle399e5b2016-01-27 18:32:30 +0000775 value = EmitARCUnsafeUnretainedScalarExpr(init);
John McCall31168b02011-06-15 23:02:42 +0000776 break;
777
778 case Qualifiers::OCL_Strong: {
779 value = EmitARCRetainScalarExpr(init);
780 break;
781 }
782
783 case Qualifiers::OCL_Weak: {
John McCallf8a9b662015-10-21 18:06:31 +0000784 // If it's not accessed by the initializer, try to emit the
785 // initialization with a copy or move.
786 if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
787 return;
788 }
789
John McCall31168b02011-06-15 23:02:42 +0000790 // No way to optimize a producing initializer into this. It's not
791 // worth optimizing for, because the value will immediately
792 // disappear in the common case.
793 value = EmitScalarExpr(init);
794
John McCall1553b192011-06-16 04:16:24 +0000795 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000796 if (accessedByInit)
John McCall1553b192011-06-16 04:16:24 +0000797 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +0000798 else
John McCall1553b192011-06-16 04:16:24 +0000799 EmitARCInitWeak(lvalue.getAddress(), value);
John McCall31168b02011-06-15 23:02:42 +0000800 return;
801 }
802
803 case Qualifiers::OCL_Autoreleasing:
804 value = EmitARCRetainAutoreleaseScalarExpr(init);
805 break;
806 }
807
John McCall1553b192011-06-16 04:16:24 +0000808 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000809
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000810 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
811
John McCall31168b02011-06-15 23:02:42 +0000812 // If the variable might have been accessed by its initializer, we
813 // might have to initialize with a barrier. We have to do this for
814 // both __weak and __strong, but __weak got filtered out above.
815 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000816 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
David Chisnallfa35df62012-01-16 17:27:18 +0000817 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCallcdda29c2013-03-13 03:10:54 +0000818 EmitARCRelease(oldValue, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +0000819 return;
820 }
821
David Chisnallfa35df62012-01-16 17:27:18 +0000822 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000823}
Chris Lattnerb85025f2010-12-01 02:05:19 +0000824
825/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
826/// non-zero parts of the specified initializer with equal or fewer than
827/// NumStores scalar stores.
828static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
829 unsigned &NumStores) {
Chris Lattnere6af8862010-12-02 01:58:41 +0000830 // Zero and Undef never requires any extra stores.
831 if (isa<llvm::ConstantAggregateZero>(Init) ||
832 isa<llvm::ConstantPointerNull>(Init) ||
833 isa<llvm::UndefValue>(Init))
834 return true;
835 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
836 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
837 isa<llvm::ConstantExpr>(Init))
838 return Init->isNullValue() || NumStores--;
839
840 // See if we can emit each element.
841 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
842 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
843 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
844 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
845 return false;
846 }
847 return true;
848 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000849
Chris Lattner236b3572012-01-31 04:36:19 +0000850 if (llvm::ConstantDataSequential *CDS =
851 dyn_cast<llvm::ConstantDataSequential>(Init)) {
852 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
853 llvm::Constant *Elt = CDS->getElementAsConstant(i);
854 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
855 return false;
856 }
857 return true;
858 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000859
Chris Lattnerb85025f2010-12-01 02:05:19 +0000860 // Anything else is hard and scary.
861 return false;
862}
863
864/// emitStoresForInitAfterMemset - For inits that
865/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
866/// stores that would be required.
867static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
John McCallc533cb72011-02-22 06:44:22 +0000868 bool isVolatile, CGBuilderTy &Builder) {
Benjamin Kramer29f9a002012-08-27 22:07:02 +0000869 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
870 "called emitStoresForInitAfterMemset for zero or undef value.");
Eric Christopher31ab1302011-08-23 22:38:00 +0000871
Chris Lattnere6af8862010-12-02 01:58:41 +0000872 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
873 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
874 isa<llvm::ConstantExpr>(Init)) {
John McCall7f416cc2015-09-08 08:05:57 +0000875 Builder.CreateDefaultAlignedStore(Init, Loc, isVolatile);
Chris Lattner236b3572012-01-31 04:36:19 +0000876 return;
877 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000878
879 if (llvm::ConstantDataSequential *CDS =
880 dyn_cast<llvm::ConstantDataSequential>(Init)) {
Chris Lattner236b3572012-01-31 04:36:19 +0000881 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
882 llvm::Constant *Elt = CDS->getElementAsConstant(i);
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000883
884 // If necessary, get a pointer to the element and emit it.
885 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
David Blaikie17ea2662015-04-04 21:07:17 +0000886 emitStoresForInitAfterMemset(
887 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
888 isVolatile, Builder);
Chris Lattner236b3572012-01-31 04:36:19 +0000889 }
Chris Lattnere6af8862010-12-02 01:58:41 +0000890 return;
891 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000892
Chris Lattnere6af8862010-12-02 01:58:41 +0000893 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
894 "Unknown value type!");
Eric Christopher31ab1302011-08-23 22:38:00 +0000895
Chris Lattnere6af8862010-12-02 01:58:41 +0000896 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
897 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000898
899 // If necessary, get a pointer to the element and emit it.
900 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
David Blaikie17ea2662015-04-04 21:07:17 +0000901 emitStoresForInitAfterMemset(
902 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
903 isVolatile, Builder);
Chris Lattnere6af8862010-12-02 01:58:41 +0000904 }
Chris Lattnerb85025f2010-12-01 02:05:19 +0000905}
906
Chris Lattnerb85025f2010-12-01 02:05:19 +0000907/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
908/// plus some stores to initialize a local variable instead of using a memcpy
909/// from a constant global. It is beneficial to use memset if the global is all
910/// zeros, or mostly zeros and large.
911static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
912 uint64_t GlobalSize) {
913 // If a global is all zeros, always use a memset.
914 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
915
Chris Lattnerb85025f2010-12-01 02:05:19 +0000916 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
917 // do it if it will require 6 or fewer scalar stores.
918 // TODO: Should budget depends on the size? Avoiding a large global warrants
919 // plopping in more stores.
920 unsigned StoreBudget = 6;
921 uint64_t SizeLimit = 32;
Eric Christopher31ab1302011-08-23 22:38:00 +0000922
923 return GlobalSize > SizeLimit &&
Chris Lattnerb85025f2010-12-01 02:05:19 +0000924 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
925}
926
Nick Lewycky8a7d90b2010-12-30 20:21:55 +0000927/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Chris Lattner03df1222007-06-02 04:53:11 +0000928/// variable declaration with auto, register, or no storage class specifier.
Chris Lattnerb781dc792008-05-08 05:58:21 +0000929/// These turn into simple stack objects, or GlobalValues depending on target.
John McCallc533cb72011-02-22 06:44:22 +0000930void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
931 AutoVarEmission emission = EmitAutoVarAlloca(D);
932 EmitAutoVarInit(emission);
933 EmitAutoVarCleanups(emission);
934}
Chris Lattner03df1222007-06-02 04:53:11 +0000935
David Majnemerdc012fa2015-04-22 21:38:15 +0000936/// Emit a lifetime.begin marker if some criteria are satisfied.
937/// \return a pointer to the temporary size Value if a marker was emitted, null
938/// otherwise
939llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
940 llvm::Value *Addr) {
Vitaly Buka1c943322016-10-26 01:59:57 +0000941 if (!ShouldEmitLifetimeMarkers)
Reid Kleckner1ef49212015-04-23 18:07:13 +0000942 return nullptr;
943
David Majnemerdc012fa2015-04-22 21:38:15 +0000944 llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
Yaxun Liu7f7f3232017-04-17 20:03:11 +0000945 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
Alexey Samsonovd918ff62015-06-12 22:31:32 +0000946 llvm::CallInst *C =
947 Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +0000948 C->setDoesNotThrow();
949 return SizeV;
950}
951
952void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
Yaxun Liu7f7f3232017-04-17 20:03:11 +0000953 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
Alexey Samsonovd918ff62015-06-12 22:31:32 +0000954 llvm::CallInst *C =
955 Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +0000956 C->setDoesNotThrow();
957}
958
Sander de Smalen891af03a2018-02-03 13:55:59 +0000959void CodeGenFunction::EmitAndRegisterVariableArrayDimensions(
960 CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo) {
961 // For each dimension stores its QualType and corresponding
962 // size-expression Value.
963 SmallVector<CodeGenFunction::VlaSizePair, 4> Dimensions;
964
965 // Break down the array into individual dimensions.
966 QualType Type1D = D.getType();
967 while (getContext().getAsVariableArrayType(Type1D)) {
968 auto VlaSize = getVLAElements1D(Type1D);
969 if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
970 Dimensions.emplace_back(C, Type1D.getUnqualifiedType());
971 else {
Sander de Smalen9084a3b2018-02-13 07:49:34 +0000972 auto SizeExprAddr = CreateDefaultAlignTempAlloca(
973 VlaSize.NumElts->getType(), "__vla_expr");
Sander de Smalen891af03a2018-02-03 13:55:59 +0000974 Builder.CreateStore(VlaSize.NumElts, SizeExprAddr);
975 Dimensions.emplace_back(SizeExprAddr.getPointer(),
976 Type1D.getUnqualifiedType());
977 }
978 Type1D = VlaSize.Type;
979 }
980
981 if (!EmitDebugInfo)
982 return;
983
984 // Register each dimension's size-expression with a DILocalVariable,
985 // so that it can be used by CGDebugInfo when instantiating a DISubrange
986 // to describe this array.
987 for (auto &VlaSize : Dimensions) {
988 llvm::Metadata *MD;
989 if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
990 MD = llvm::ConstantAsMetadata::get(C);
991 else {
992 // Create an artificial VarDecl to generate debug info for.
993 IdentifierInfo &NameIdent = getContext().Idents.getOwn(
994 cast<llvm::AllocaInst>(VlaSize.NumElts)->getName());
995 auto VlaExprTy = VlaSize.NumElts->getType()->getPointerElementType();
996 auto QT = getContext().getIntTypeForBitwidth(
997 VlaExprTy->getScalarSizeInBits(), false);
998 auto *ArtificialDecl = VarDecl::Create(
999 getContext(), const_cast<DeclContext *>(D.getDeclContext()),
1000 D.getLocation(), D.getLocation(), &NameIdent, QT,
1001 getContext().CreateTypeSourceInfo(QT), SC_Auto);
Sander de Smalen9084a3b2018-02-13 07:49:34 +00001002 ArtificialDecl->setImplicit();
Sander de Smalen891af03a2018-02-03 13:55:59 +00001003
1004 MD = DI->EmitDeclareOfAutoVariable(ArtificialDecl, VlaSize.NumElts,
1005 Builder);
1006 }
1007 assert(MD && "No Size expression debug node created");
1008 DI->registerVLASizeExpression(VlaSize.Type, MD);
1009 }
1010}
1011
John McCallc533cb72011-02-22 06:44:22 +00001012/// EmitAutoVarAlloca - Emit the alloca and debug information for a
Alp Tokerf6a24ce2013-12-05 16:25:25 +00001013/// local variable. Does not emit initialization or destruction.
John McCallc533cb72011-02-22 06:44:22 +00001014CodeGenFunction::AutoVarEmission
1015CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
1016 QualType Ty = D.getType();
Yaxun Liub7318e02017-10-13 03:37:48 +00001017 assert(
1018 Ty.getAddressSpace() == LangAS::Default ||
1019 (Ty.getAddressSpace() == LangAS::opencl_private && getLangOpts().OpenCL));
John McCallc533cb72011-02-22 06:44:22 +00001020
1021 AutoVarEmission emission(D);
1022
1023 bool isByRef = D.hasAttr<BlocksAttr>();
1024 emission.IsByRef = isByRef;
1025
1026 CharUnits alignment = getContext().getDeclAlign(&D);
John McCallc533cb72011-02-22 06:44:22 +00001027
John McCall23c29fe2011-06-24 21:55:10 +00001028 // If the type is variably-modified, emit all the VLA sizes for it.
1029 if (Ty->isVariablyModifiedType())
1030 EmitVariablyModifiedType(Ty);
1031
Sander de Smalen891af03a2018-02-03 13:55:59 +00001032 auto *DI = getDebugInfo();
1033 bool EmitDebugInfo = DI && CGM.getCodeGenOpts().getDebugInfo() >=
1034 codegenoptions::LimitedDebugInfo;
1035
John McCall7f416cc2015-09-08 08:05:57 +00001036 Address address = Address::invalid();
Eli Friedmana682d392008-02-15 12:20:59 +00001037 if (Ty->isConstantSizeType()) {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001038 bool NRVO = getLangOpts().ElideConstructors &&
1039 D.isNRVOVariable();
John McCallc533cb72011-02-22 06:44:22 +00001040
Richard Smith2bcde3a2013-06-02 00:09:52 +00001041 // If this value is an array or struct with a statically determinable
1042 // constant initializer, there are optimizations we can do.
Rafael Espindola609f5d92013-03-26 18:41:47 +00001043 //
1044 // TODO: We should constant-evaluate the initializer of any variable,
1045 // as long as it is initialized by a constant expression. Currently,
1046 // isConstantInitializer produces wrong answers for structs with
1047 // reference or bitfield members, and a few other cases, and checking
1048 // for POD-ness protects us from some of these.
Richard Smith2bcde3a2013-06-02 00:09:52 +00001049 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
1050 (D.isConstexpr() ||
1051 ((Ty.isPODType(getContext()) ||
1052 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
1053 D.getInit()->isConstantInitializer(getContext(), false)))) {
John McCallc533cb72011-02-22 06:44:22 +00001054
Rafael Espindola609f5d92013-03-26 18:41:47 +00001055 // If the variable's a const type, and it's neither an NRVO
1056 // candidate nor a __block variable and has no mutable members,
1057 // emit it as a global instead.
Anastasia Stulovae4a1c382016-11-29 17:01:19 +00001058 // Exception is if a variable is located in non-constant address space
1059 // in OpenCL.
1060 if ((!getLangOpts().OpenCL ||
1061 Ty.getAddressSpace() == LangAS::opencl_constant) &&
1062 (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
1063 CGM.isTypeConstant(Ty, true))) {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001064 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCallc533cb72011-02-22 06:44:22 +00001065
John McCall7f416cc2015-09-08 08:05:57 +00001066 // Signal this condition to later callbacks.
1067 emission.Addr = Address::invalid();
Rafael Espindola609f5d92013-03-26 18:41:47 +00001068 assert(emission.wasEmittedAsGlobal());
1069 return emission;
Tanya Lattnerf9d41df2009-11-04 01:18:09 +00001070 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001071
Rafael Espindola609f5d92013-03-26 18:41:47 +00001072 // Otherwise, tell the initialization code that we're in this case.
1073 emission.IsConstantAggregate = true;
1074 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001075
Rafael Espindola609f5d92013-03-26 18:41:47 +00001076 // A normal fixed sized variable becomes an alloca in the entry block,
1077 // unless it's an NRVO variable.
Eric Christopher31ab1302011-08-23 22:38:00 +00001078
Rafael Espindola609f5d92013-03-26 18:41:47 +00001079 if (NRVO) {
1080 // The named return value optimization: allocate this variable in the
1081 // return slot, so that we can elide the copy when returning this
1082 // variable (C++0x [class.copy]p34).
John McCall7f416cc2015-09-08 08:05:57 +00001083 address = ReturnValue;
Eric Christopher31ab1302011-08-23 22:38:00 +00001084
Rafael Espindola609f5d92013-03-26 18:41:47 +00001085 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1086 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
1087 // Create a flag that is used to indicate when the NRVO was applied
1088 // to this variable. Set it to zero to indicate that NRVO was not
1089 // applied.
1090 llvm::Value *Zero = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +00001091 Address NRVOFlag =
1092 CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
Rafael Espindola609f5d92013-03-26 18:41:47 +00001093 EnsureInsertPoint();
1094 Builder.CreateStore(Zero, NRVOFlag);
Eric Christopher31ab1302011-08-23 22:38:00 +00001095
Rafael Espindola609f5d92013-03-26 18:41:47 +00001096 // Record the NRVO flag for this variable.
John McCall7f416cc2015-09-08 08:05:57 +00001097 NRVOFlags[&D] = NRVOFlag.getPointer();
1098 emission.NRVOFlag = NRVOFlag.getPointer();
Nadav Rotem1da30942013-03-23 06:43:35 +00001099 }
Douglas Gregor290c93e2010-05-15 06:46:45 +00001100 }
Chris Lattnerb781dc792008-05-08 05:58:21 +00001101 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001102 CharUnits allocaAlignment;
1103 llvm::Type *allocaTy;
1104 if (isByRef) {
1105 auto &byrefInfo = getBlockByrefInfo(&D);
1106 allocaTy = byrefInfo.Type;
1107 allocaAlignment = byrefInfo.ByrefAlignment;
1108 } else {
1109 allocaTy = ConvertTypeForMem(Ty);
1110 allocaAlignment = alignment;
1111 }
Rafael Espindola609f5d92013-03-26 18:41:47 +00001112
John McCall999110f2015-09-08 09:18:30 +00001113 // Create the alloca. Note that we set the name separately from
1114 // building the instruction so that it's there even in no-asserts
1115 // builds.
Yaxun Liu84744c12017-06-19 17:03:41 +00001116 address = CreateTempAlloca(allocaTy, allocaAlignment, D.getName());
Rafael Espindola609f5d92013-03-26 18:41:47 +00001117
Reid Kleckner1f88e932015-10-07 21:03:41 +00001118 // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1119 // the catch parameter starts in the catchpad instruction, and we can't
1120 // insert code in those basic blocks.
1121 bool IsMSCatchParam =
1122 D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1123
Vitaly Buka64c80b42016-10-26 05:42:30 +00001124 // Emit a lifetime intrinsic if meaningful. There's no point in doing this
1125 // if we don't have a valid insertion point (?).
Reid Kleckner1f88e932015-10-07 21:03:41 +00001126 if (HaveInsertPoint() && !IsMSCatchParam) {
Akira Hatanakafdcd18b2017-01-25 22:55:13 +00001127 // If there's a jump into the lifetime of this variable, its lifetime
1128 // gets broken up into several regions in IR, which requires more work
1129 // to handle correctly. For now, just omit the intrinsics; this is a
1130 // rare case, and it's better to just be conservatively correct.
1131 // PR28267.
1132 //
1133 // We have to do this in all language modes if there's a jump past the
1134 // declaration. We also have to do it in C if there's a jump to an
1135 // earlier point in the current block because non-VLA lifetimes begin as
1136 // soon as the containing block is entered, not when its variables
1137 // actually come into scope; suppressing the lifetime annotations
1138 // completely in this case is unnecessarily pessimistic, but again, this
1139 // is rare.
1140 if (!Bypasses.IsBypassed(&D) &&
1141 !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
Vitaly Buka64c80b42016-10-26 05:42:30 +00001142 uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
1143 emission.SizeForLifetimeMarkers =
1144 EmitLifetimeStart(size, address.getPointer());
1145 }
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +00001146 } else {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001147 assert(!emission.useLifetimeMarkers());
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +00001148 }
Chris Lattnerb781dc792008-05-08 05:58:21 +00001149 }
Chris Lattner03df1222007-06-02 04:53:11 +00001150 } else {
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001151 EnsureInsertPoint();
1152
Anders Carlsson15949b32009-02-09 20:41:50 +00001153 if (!DidCallStackSave) {
Anders Carlsson30032882008-12-12 07:38:43 +00001154 // Save the stack.
John McCall7f416cc2015-09-08 08:05:57 +00001155 Address Stack =
1156 CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
Mike Stump11289f42009-09-09 15:08:12 +00001157
Anders Carlsson30032882008-12-12 07:38:43 +00001158 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
David Blaikie4ba525b2015-07-14 17:27:39 +00001159 llvm::Value *V = Builder.CreateCall(F);
Anders Carlsson30032882008-12-12 07:38:43 +00001160 Builder.CreateStore(V, Stack);
Anders Carlsson15949b32009-02-09 20:41:50 +00001161
1162 DidCallStackSave = true;
Mike Stump11289f42009-09-09 15:08:12 +00001163
John McCalla464ff92010-07-21 06:13:08 +00001164 // Push a cleanup block and restore the stack there.
John McCalle4df6c82011-01-28 08:37:24 +00001165 // FIXME: in general circumstances, this should be an EH cleanup.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001166 pushStackRestore(NormalCleanup, Stack);
Anders Carlsson30032882008-12-12 07:38:43 +00001167 }
Mike Stump11289f42009-09-09 15:08:12 +00001168
Sander de Smalen891af03a2018-02-03 13:55:59 +00001169 auto VlaSize = getVLASize(Ty);
1170 llvm::Type *llvmTy = ConvertTypeForMem(VlaSize.Type);
Anders Carlsson30032882008-12-12 07:38:43 +00001171
1172 // Allocate memory for the array.
Sander de Smalen891af03a2018-02-03 13:55:59 +00001173 address = CreateTempAlloca(llvmTy, alignment, "vla", VlaSize.NumElts);
1174
1175 // If we have debug info enabled, properly describe the VLA dimensions for
1176 // this type by registering the vla size expression for each of the
1177 // dimensions.
1178 EmitAndRegisterVariableArrayDimensions(DI, D, EmitDebugInfo);
Chris Lattner03df1222007-06-02 04:53:11 +00001179 }
Eli Friedmanf4084702008-12-20 23:11:59 +00001180
John McCall7f416cc2015-09-08 08:05:57 +00001181 setAddrOfLocalVar(&D, address);
1182 emission.Addr = address;
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001183
1184 // Emit debug info for local var declaration.
Sander de Smalen891af03a2018-02-03 13:55:59 +00001185 if (EmitDebugInfo && HaveInsertPoint()) {
1186 DI->setLocation(D.getLocation());
1187 (void)DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
1188 }
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001189
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001190 if (D.hasAttr<AnnotateAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00001191 EmitVarAnnotations(&D, address.getPointer());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001192
Kuba Mracek5e5e4e72017-04-14 16:53:25 +00001193 // Make sure we call @llvm.lifetime.end.
1194 if (emission.useLifetimeMarkers())
1195 EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
1196 emission.getAllocatedAddress(),
1197 emission.getSizeForLifetimeMarkers());
1198
John McCallc533cb72011-02-22 06:44:22 +00001199 return emission;
1200}
1201
1202/// Determines whether the given __block variable is potentially
1203/// captured by the given expression.
1204static bool isCapturedBy(const VarDecl &var, const Expr *e) {
1205 // Skip the most common kinds of expressions that make
1206 // hierarchy-walking expensive.
1207 e = e->IgnoreParenCasts();
1208
1209 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
1210 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +00001211 for (const auto &I : block->captures()) {
1212 if (I.getVariable() == &var)
John McCallc533cb72011-02-22 06:44:22 +00001213 return true;
1214 }
1215
1216 // No need to walk into the subexpressions.
1217 return false;
1218 }
1219
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001220 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1221 const CompoundStmt *CS = SE->getSubStmt();
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001222 for (const auto *BI : CS->body())
1223 if (const auto *E = dyn_cast<Expr>(BI)) {
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001224 if (isCapturedBy(var, E))
1225 return true;
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001226 }
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001227 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001228 // special case declarations
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001229 for (const auto *I : DS->decls()) {
1230 if (const auto *VD = dyn_cast<VarDecl>((I))) {
1231 const Expr *Init = VD->getInit();
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001232 if (Init && isCapturedBy(var, Init))
1233 return true;
1234 }
1235 }
1236 }
1237 else
1238 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1239 // Later, provide code to poke into statements for capture analysis.
1240 return true;
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001241 return false;
1242 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001243
Benjamin Kramer642f1732015-07-02 21:03:14 +00001244 for (const Stmt *SubStmt : e->children())
1245 if (isCapturedBy(var, cast<Expr>(SubStmt)))
John McCallc533cb72011-02-22 06:44:22 +00001246 return true;
1247
1248 return false;
1249}
1250
Douglas Gregor82e1af22011-07-01 21:08:19 +00001251/// \brief Determine whether the given initializer is trivial in the sense
1252/// that it requires no code to be generated.
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001253bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
Douglas Gregor82e1af22011-07-01 21:08:19 +00001254 if (!Init)
1255 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001256
Douglas Gregor82e1af22011-07-01 21:08:19 +00001257 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1258 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1259 if (Constructor->isTrivial() &&
1260 Constructor->isDefaultConstructor() &&
1261 !Construct->requiresZeroInitialization())
1262 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001263
Douglas Gregor82e1af22011-07-01 21:08:19 +00001264 return false;
1265}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001266
John McCallc533cb72011-02-22 06:44:22 +00001267void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001268 assert(emission.Variable && "emission was not valid!");
1269
John McCallc533cb72011-02-22 06:44:22 +00001270 // If this was emitted as a global constant, we're done.
1271 if (emission.wasEmittedAsGlobal()) return;
1272
John McCall9e2e22f2011-02-22 07:16:58 +00001273 const VarDecl &D = *emission.Variable;
Adrian Prantl95b24e92015-02-03 20:00:54 +00001274 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
John McCallc533cb72011-02-22 06:44:22 +00001275 QualType type = D.getType();
1276
Chris Lattner07eb7332007-07-12 00:39:48 +00001277 // If this local has an initializer, emit it now.
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001278 const Expr *Init = D.getInit();
1279
1280 // If we are at an unreachable point, we don't need to emit the initializer
1281 // unless it contains a label.
1282 if (!HaveInsertPoint()) {
John McCallc533cb72011-02-22 06:44:22 +00001283 if (!Init || !ContainsLabel(Init)) return;
1284 EnsureInsertPoint();
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001285 }
1286
John McCall73064872011-03-31 01:59:53 +00001287 // Initialize the structure of a __block variable.
1288 if (emission.IsByRef)
1289 emitByrefStructureInit(emission);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001290
Douglas Gregor82e1af22011-07-01 21:08:19 +00001291 if (isTrivialInitializer(Init))
1292 return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001293
John McCallc533cb72011-02-22 06:44:22 +00001294 // Check whether this is a byref variable that's potentially
1295 // captured and moved by its own initializer. If so, we'll need to
1296 // emit the initializer first, then copy into the variable.
1297 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1298
John McCall7f416cc2015-09-08 08:05:57 +00001299 Address Loc =
1300 capturedByInit ? emission.Addr : emission.getObjectAddress(*this);
John McCallc533cb72011-02-22 06:44:22 +00001301
Craig Topper8a13c412014-05-21 05:09:00 +00001302 llvm::Constant *constant = nullptr;
Richard Smith2bcde3a2013-06-02 00:09:52 +00001303 if (emission.IsConstantAggregate || D.isConstexpr()) {
Richard Smithfddd3842011-12-30 21:15:51 +00001304 assert(!capturedByInit && "constant init contains a capturing block?");
John McCallde0fe072017-08-15 21:42:52 +00001305 constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(D);
Richard Smithfddd3842011-12-30 21:15:51 +00001306 }
1307
1308 if (!constant) {
John McCall7f416cc2015-09-08 08:05:57 +00001309 LValue lv = MakeAddrLValue(Loc, type);
John McCall1553b192011-06-16 04:16:24 +00001310 lv.setNonGC(true);
David Blaikie66e41972015-01-14 07:38:27 +00001311 return EmitExprAsInit(Init, &D, lv, capturedByInit);
John McCall1553b192011-06-16 04:16:24 +00001312 }
John McCall91ca10f2011-03-08 09:11:50 +00001313
Richard Smith2bcde3a2013-06-02 00:09:52 +00001314 if (!emission.IsConstantAggregate) {
1315 // For simple scalar/complex initialization, store the value directly.
John McCall7f416cc2015-09-08 08:05:57 +00001316 LValue lv = MakeAddrLValue(Loc, type);
Richard Smith2bcde3a2013-06-02 00:09:52 +00001317 lv.setNonGC(true);
1318 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1319 }
1320
John McCallc533cb72011-02-22 06:44:22 +00001321 // If this is a simple aggregate initialization, we can optimize it
1322 // in various ways.
John McCall91ca10f2011-03-08 09:11:50 +00001323 bool isVolatile = type.isVolatileQualified();
John McCallc533cb72011-02-22 06:44:22 +00001324
John McCall91ca10f2011-03-08 09:11:50 +00001325 llvm::Value *SizeVal =
Eric Christopher31ab1302011-08-23 22:38:00 +00001326 llvm::ConstantInt::get(IntPtrTy,
John McCall91ca10f2011-03-08 09:11:50 +00001327 getContext().getTypeSizeInChars(type).getQuantity());
John McCallc533cb72011-02-22 06:44:22 +00001328
Yaxun Liubd382362017-10-23 17:49:26 +00001329 llvm::Type *BP = AllocaInt8PtrTy;
John McCall7f416cc2015-09-08 08:05:57 +00001330 if (Loc.getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001331 Loc = Builder.CreateBitCast(Loc, BP);
Mon P Wangcc2ab0c2010-04-04 03:10:52 +00001332
John McCall91ca10f2011-03-08 09:11:50 +00001333 // If the initializer is all or mostly zeros, codegen with memset then do
1334 // a few stores afterward.
Eric Christopher31ab1302011-08-23 22:38:00 +00001335 if (shouldUseMemSetPlusStoresToInitialize(constant,
Micah Villmowdd31ca12012-10-08 16:25:52 +00001336 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
John McCall91ca10f2011-03-08 09:11:50 +00001337 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
John McCall7f416cc2015-09-08 08:05:57 +00001338 isVolatile);
Benjamin Kramer29f9a002012-08-27 22:07:02 +00001339 // Zero and undef don't require a stores.
1340 if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
Matt Arsenault935574a2018-02-08 19:37:09 +00001341 Loc = Builder.CreateBitCast(Loc,
1342 constant->getType()->getPointerTo(Loc.getAddressSpace()));
John McCall7f416cc2015-09-08 08:05:57 +00001343 emitStoresForInitAfterMemset(constant, Loc.getPointer(),
1344 isVolatile, Builder);
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001345 }
John McCall91ca10f2011-03-08 09:11:50 +00001346 } else {
Eric Christopher31ab1302011-08-23 22:38:00 +00001347 // Otherwise, create a temporary global with the initializer then
John McCall91ca10f2011-03-08 09:11:50 +00001348 // memcpy from the global to the alloca.
Reid Kleckner453e0562014-10-08 01:07:54 +00001349 std::string Name = getStaticDeclName(CGM, D);
Alexey Baderabdcfc12016-10-31 10:26:31 +00001350 unsigned AS = 0;
1351 if (getLangOpts().OpenCL) {
1352 AS = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
1353 BP = llvm::PointerType::getInt8PtrTy(getLLVMContext(), AS);
1354 }
John McCall91ca10f2011-03-08 09:11:50 +00001355 llvm::GlobalVariable *GV =
1356 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
Eric Christopherb58b3e82011-08-24 00:33:55 +00001357 llvm::GlobalValue::PrivateLinkage,
Alexey Baderabdcfc12016-10-31 10:26:31 +00001358 constant, Name, nullptr,
1359 llvm::GlobalValue::NotThreadLocal, AS);
John McCall7f416cc2015-09-08 08:05:57 +00001360 GV->setAlignment(Loc.getAlignment().getQuantity());
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001361 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Eric Christopher31ab1302011-08-23 22:38:00 +00001362
John McCall7f416cc2015-09-08 08:05:57 +00001363 Address SrcPtr = Address(GV, Loc.getAlignment());
1364 if (SrcPtr.getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001365 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
John McCall91ca10f2011-03-08 09:11:50 +00001366
John McCall7f416cc2015-09-08 08:05:57 +00001367 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, isVolatile);
John McCall91ca10f2011-03-08 09:11:50 +00001368 }
1369}
1370
1371/// Emit an expression as an initializer for a variable at the given
1372/// location. The expression is not necessarily the normal
1373/// initializer for the variable, and the address is not necessarily
1374/// its normal location.
1375///
1376/// \param init the initializing expression
1377/// \param var the variable to act as if we're initializing
1378/// \param loc the address to initialize; its type is a pointer
1379/// to the LLVM mapping of the variable's type
1380/// \param alignment the alignment of the address
1381/// \param capturedByInit true if the variable is a __block variable
1382/// whose address is potentially changed by the initializer
David Blaikie73ca5692014-12-09 00:32:22 +00001383void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +00001384 LValue lvalue, bool capturedByInit) {
John McCall31168b02011-06-15 23:02:42 +00001385 QualType type = D->getType();
John McCall91ca10f2011-03-08 09:11:50 +00001386
1387 if (type->isReferenceType()) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +00001388 RValue rvalue = EmitReferenceBindingToExpr(init);
Eric Christopher31ab1302011-08-23 22:38:00 +00001389 if (capturedByInit)
John McCall1553b192011-06-16 04:16:24 +00001390 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001391 EmitStoreThroughLValue(rvalue, lvalue, true);
John McCall47fb9502013-03-07 21:37:08 +00001392 return;
1393 }
1394 switch (getEvaluationKind(type)) {
1395 case TEK_Scalar:
David Blaikie66e41972015-01-14 07:38:27 +00001396 EmitScalarInit(init, D, lvalue, capturedByInit);
John McCall47fb9502013-03-07 21:37:08 +00001397 return;
1398 case TEK_Complex: {
John McCall91ca10f2011-03-08 09:11:50 +00001399 ComplexPairTy complex = EmitComplexExpr(init);
John McCall1553b192011-06-16 04:16:24 +00001400 if (capturedByInit)
1401 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001402 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
John McCall47fb9502013-03-07 21:37:08 +00001403 return;
1404 }
1405 case TEK_Aggregate:
John McCalla8ec7eb2013-03-07 21:37:17 +00001406 if (type->isAtomicType()) {
1407 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1408 } else {
1409 // TODO: how can we delay here if D is captured by its initializer?
1410 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001411 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001412 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001413 AggValueSlot::IsNotAliased));
John McCalla8ec7eb2013-03-07 21:37:17 +00001414 }
John McCall47fb9502013-03-07 21:37:08 +00001415 return;
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001416 }
John McCall47fb9502013-03-07 21:37:08 +00001417 llvm_unreachable("bad evaluation kind");
John McCallc533cb72011-02-22 06:44:22 +00001418}
John McCallbd309292010-07-06 01:34:17 +00001419
John McCall82fe67b2011-07-09 01:37:26 +00001420/// Enter a destroy cleanup for the given local variable.
1421void CodeGenFunction::emitAutoVarTypeCleanup(
1422 const CodeGenFunction::AutoVarEmission &emission,
1423 QualType::DestructionKind dtorKind) {
1424 assert(dtorKind != QualType::DK_none);
1425
1426 // Note that for __block variables, we want to destroy the
1427 // original stack object, not the possibly forwarded object.
John McCall7f416cc2015-09-08 08:05:57 +00001428 Address addr = emission.getObjectAddress(*this);
John McCall82fe67b2011-07-09 01:37:26 +00001429
1430 const VarDecl *var = emission.Variable;
1431 QualType type = var->getType();
1432
1433 CleanupKind cleanupKind = NormalAndEHCleanup;
Craig Topper8a13c412014-05-21 05:09:00 +00001434 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall82fe67b2011-07-09 01:37:26 +00001435
1436 switch (dtorKind) {
1437 case QualType::DK_none:
1438 llvm_unreachable("no cleanup for trivially-destructible variable");
1439
1440 case QualType::DK_cxx_destructor:
1441 // If there's an NRVO flag on the emission, we need a different
1442 // cleanup.
1443 if (emission.NRVOFlag) {
1444 assert(!type->isArrayType());
1445 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
John McCall7f416cc2015-09-08 08:05:57 +00001446 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr,
1447 dtor, emission.NRVOFlag);
John McCall82fe67b2011-07-09 01:37:26 +00001448 return;
1449 }
1450 break;
1451
1452 case QualType::DK_objc_strong_lifetime:
1453 // Suppress cleanups for pseudo-strong variables.
1454 if (var->isARCPseudoStrong()) return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001455
John McCall82fe67b2011-07-09 01:37:26 +00001456 // Otherwise, consider whether to use an EH cleanup or not.
1457 cleanupKind = getARCCleanupKind();
1458
1459 // Use the imprecise destroyer by default.
1460 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1461 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1462 break;
1463
1464 case QualType::DK_objc_weak_lifetime:
1465 break;
1466 }
1467
1468 // If we haven't chosen a more specific destroyer, use the default.
Peter Collingbourne1425b452012-01-26 03:33:36 +00001469 if (!destroyer) destroyer = getDestroyer(dtorKind);
John McCall178360e2011-07-11 08:38:19 +00001470
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001471 // Use an EH cleanup in array destructors iff the destructor itself
John McCall178360e2011-07-11 08:38:19 +00001472 // is being pushed as an EH cleanup.
1473 bool useEHCleanup = (cleanupKind & EHCleanup);
1474 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1475 useEHCleanup);
John McCall82fe67b2011-07-09 01:37:26 +00001476}
1477
John McCallc533cb72011-02-22 06:44:22 +00001478void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001479 assert(emission.Variable && "emission was not valid!");
1480
John McCallc533cb72011-02-22 06:44:22 +00001481 // If this was emitted as a global constant, we're done.
1482 if (emission.wasEmittedAsGlobal()) return;
1483
John McCall8c38d352012-04-13 18:44:05 +00001484 // If we don't have an insertion point, we're done. Sema prevents
1485 // us from jumping into any of these scopes anyway.
1486 if (!HaveInsertPoint()) return;
1487
John McCall9e2e22f2011-02-22 07:16:58 +00001488 const VarDecl &D = *emission.Variable;
John McCallc533cb72011-02-22 06:44:22 +00001489
John McCall82fe67b2011-07-09 01:37:26 +00001490 // Check the type for a cleanup.
1491 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1492 emitAutoVarTypeCleanup(emission, dtorKind);
John McCall31168b02011-06-15 23:02:42 +00001493
John McCall1bd25562011-06-24 23:21:27 +00001494 // In GC mode, honor objc_precise_lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001495 if (getLangOpts().getGC() != LangOptions::NonGC &&
John McCall1bd25562011-06-24 23:21:27 +00001496 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1497 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1498 }
1499
John McCallc533cb72011-02-22 06:44:22 +00001500 // Handle the cleanup attribute.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001501 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001502 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001503
John McCallc533cb72011-02-22 06:44:22 +00001504 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001505 assert(F && "Could not find function!");
Mike Stump11289f42009-09-09 15:08:12 +00001506
John McCalla729c622012-02-17 03:33:10 +00001507 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
John McCallc533cb72011-02-22 06:44:22 +00001508 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001509 }
Mike Stump626aecc2009-03-05 01:23:13 +00001510
John McCallc533cb72011-02-22 06:44:22 +00001511 // If this is a block variable, call _Block_object_destroy
1512 // (on the unforwarded address).
John McCall73064872011-03-31 01:59:53 +00001513 if (emission.IsByRef)
1514 enterByrefCleanup(emission);
Chris Lattner03df1222007-06-02 04:53:11 +00001515}
Chris Lattner53621a52007-06-13 20:44:40 +00001516
Peter Collingbourne1425b452012-01-26 03:33:36 +00001517CodeGenFunction::Destroyer *
John McCall82fe67b2011-07-09 01:37:26 +00001518CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1519 switch (kind) {
1520 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
John McCallc2f00012011-07-09 09:09:00 +00001521 case QualType::DK_cxx_destructor:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001522 return destroyCXXObject;
John McCallc2f00012011-07-09 09:09:00 +00001523 case QualType::DK_objc_strong_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001524 return destroyARCStrongPrecise;
John McCallc2f00012011-07-09 09:09:00 +00001525 case QualType::DK_objc_weak_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001526 return destroyARCWeak;
John McCall82fe67b2011-07-09 01:37:26 +00001527 }
Matt Beaumont-Gay934bbf52012-01-27 00:46:27 +00001528 llvm_unreachable("Unknown DestructionKind");
John McCall82fe67b2011-07-09 01:37:26 +00001529}
1530
John McCall12cc42a2013-02-01 05:11:40 +00001531/// pushEHDestroy - Push the standard destructor for the given type as
1532/// an EH-only cleanup.
1533void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00001534 Address addr, QualType type) {
John McCall12cc42a2013-02-01 05:11:40 +00001535 assert(dtorKind && "cannot push destructor for trivial type");
1536 assert(needsEHCleanup(dtorKind));
1537
1538 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1539}
1540
1541/// pushDestroy - Push the standard destructor for the given type as
1542/// at least a normal cleanup.
John McCall4bd0fb12011-07-12 16:41:08 +00001543void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00001544 Address addr, QualType type) {
John McCall4bd0fb12011-07-12 16:41:08 +00001545 assert(dtorKind && "cannot push destructor for trivial type");
1546
1547 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1548 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1549 cleanupKind & EHCleanup);
1550}
1551
John McCall7f416cc2015-09-08 08:05:57 +00001552void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001553 QualType type, Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001554 bool useEHCleanupForArray) {
John McCall4bd0fb12011-07-12 16:41:08 +00001555 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1556 destroyer, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001557}
1558
John McCall7f416cc2015-09-08 08:05:57 +00001559void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001560 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
1561}
1562
Richard Smith736a9472013-06-12 20:42:33 +00001563void CodeGenFunction::pushLifetimeExtendedDestroy(
John McCall7f416cc2015-09-08 08:05:57 +00001564 CleanupKind cleanupKind, Address addr, QualType type,
Richard Smith736a9472013-06-12 20:42:33 +00001565 Destroyer *destroyer, bool useEHCleanupForArray) {
1566 assert(!isInConditionalBranch() &&
1567 "performing lifetime extension from within conditional");
1568
1569 // Push an EH-only cleanup for the object now.
1570 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1571 // around in case a temporary's destructor throws an exception.
1572 if (cleanupKind & EHCleanup)
1573 EHStack.pushCleanup<DestroyObject>(
1574 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1575 destroyer, useEHCleanupForArray);
1576
1577 // Remember that we need to push a full cleanup for the object at the
1578 // end of the full-expression.
1579 pushCleanupAfterFullExpr<DestroyObject>(
1580 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1581}
1582
John McCall178360e2011-07-11 08:38:19 +00001583/// emitDestroy - Immediately perform the destruction of the given
1584/// object.
1585///
1586/// \param addr - the address of the object; a type*
1587/// \param type - the type of the object; if an array type, all
1588/// objects are destroyed in reverse order
1589/// \param destroyer - the function to call to destroy individual
1590/// elements
1591/// \param useEHCleanupForArray - whether an EH cleanup should be
1592/// used when destroying array elements, in case one of the
1593/// destructions throws an exception
John McCall7f416cc2015-09-08 08:05:57 +00001594void CodeGenFunction::emitDestroy(Address addr, QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001595 Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001596 bool useEHCleanupForArray) {
John McCall82fe67b2011-07-09 01:37:26 +00001597 const ArrayType *arrayType = getContext().getAsArrayType(type);
1598 if (!arrayType)
1599 return destroyer(*this, addr, type);
1600
John McCall7f416cc2015-09-08 08:05:57 +00001601 llvm::Value *length = emitArrayLength(arrayType, type, addr);
1602
1603 CharUnits elementAlign =
1604 addr.getAlignment()
1605 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
John McCall97eab0a2011-07-13 08:09:46 +00001606
1607 // Normally we have to check whether the array is zero-length.
1608 bool checkZeroLength = true;
1609
1610 // But if the array length is constant, we can suppress that.
1611 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1612 // ...and if it's constant zero, we can just skip the entire thing.
1613 if (constLength->isZero()) return;
1614 checkZeroLength = false;
1615 }
1616
John McCall7f416cc2015-09-08 08:05:57 +00001617 llvm::Value *begin = addr.getPointer();
John McCall82fe67b2011-07-09 01:37:26 +00001618 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
John McCall7f416cc2015-09-08 08:05:57 +00001619 emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001620 checkZeroLength, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001621}
1622
John McCall178360e2011-07-11 08:38:19 +00001623/// emitArrayDestroy - Destroys all the elements of the given array,
1624/// beginning from last to first. The array cannot be zero-length.
1625///
1626/// \param begin - a type* denoting the first element of the array
1627/// \param end - a type* denoting one past the end of the array
NAKAMURA Takumiff7a9252015-09-08 09:42:41 +00001628/// \param elementType - the element type of the array
John McCall178360e2011-07-11 08:38:19 +00001629/// \param destroyer - the function to call to destroy elements
1630/// \param useEHCleanup - whether to push an EH cleanup to destroy
1631/// the remaining elements in case the destruction of a single
1632/// element throws
John McCall82fe67b2011-07-09 01:37:26 +00001633void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1634 llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00001635 QualType elementType,
1636 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001637 Destroyer *destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001638 bool checkZeroLength,
John McCall178360e2011-07-11 08:38:19 +00001639 bool useEHCleanup) {
John McCall7f416cc2015-09-08 08:05:57 +00001640 assert(!elementType->isArrayType());
John McCall82fe67b2011-07-09 01:37:26 +00001641
1642 // The basic structure here is a do-while loop, because we don't
1643 // need to check for the zero-element case.
1644 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1645 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1646
John McCall97eab0a2011-07-13 08:09:46 +00001647 if (checkZeroLength) {
1648 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1649 "arraydestroy.isempty");
1650 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1651 }
1652
John McCall82fe67b2011-07-09 01:37:26 +00001653 // Enter the loop body, making that address the current address.
1654 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1655 EmitBlock(bodyBB);
1656 llvm::PHINode *elementPast =
1657 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1658 elementPast->addIncoming(end, entryBB);
1659
1660 // Shift the address back by one element.
1661 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1662 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1663 "arraydestroy.element");
1664
John McCall178360e2011-07-11 08:38:19 +00001665 if (useEHCleanup)
John McCall7f416cc2015-09-08 08:05:57 +00001666 pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
1667 destroyer);
John McCall178360e2011-07-11 08:38:19 +00001668
John McCall82fe67b2011-07-09 01:37:26 +00001669 // Perform the actual destruction there.
John McCall7f416cc2015-09-08 08:05:57 +00001670 destroyer(*this, Address(element, elementAlign), elementType);
John McCall82fe67b2011-07-09 01:37:26 +00001671
John McCall178360e2011-07-11 08:38:19 +00001672 if (useEHCleanup)
1673 PopCleanupBlock();
1674
John McCall82fe67b2011-07-09 01:37:26 +00001675 // Check whether we've reached the end.
1676 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1677 Builder.CreateCondBr(done, doneBB, bodyBB);
1678 elementPast->addIncoming(element, Builder.GetInsertBlock());
1679
1680 // Done.
1681 EmitBlock(doneBB);
1682}
1683
John McCall178360e2011-07-11 08:38:19 +00001684/// Perform partial array destruction as if in an EH cleanup. Unlike
1685/// emitArrayDestroy, the element type here may still be an array type.
John McCall178360e2011-07-11 08:38:19 +00001686static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1687 llvm::Value *begin, llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00001688 QualType type, CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001689 CodeGenFunction::Destroyer *destroyer) {
John McCall178360e2011-07-11 08:38:19 +00001690 // If the element type is itself an array, drill down.
John McCall97eab0a2011-07-13 08:09:46 +00001691 unsigned arrayDepth = 0;
John McCall178360e2011-07-11 08:38:19 +00001692 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1693 // VLAs don't require a GEP index to walk into.
1694 if (!isa<VariableArrayType>(arrayType))
John McCall97eab0a2011-07-13 08:09:46 +00001695 arrayDepth++;
John McCall178360e2011-07-11 08:38:19 +00001696 type = arrayType->getElementType();
1697 }
John McCall97eab0a2011-07-13 08:09:46 +00001698
1699 if (arrayDepth) {
John McCallf0f0b7a2015-09-14 18:57:08 +00001700 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
John McCall97eab0a2011-07-13 08:09:46 +00001701
John McCallf0f0b7a2015-09-14 18:57:08 +00001702 SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
Jay Foad040dd822011-07-22 08:16:57 +00001703 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1704 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
John McCall178360e2011-07-11 08:38:19 +00001705 }
1706
John McCall97eab0a2011-07-13 08:09:46 +00001707 // Destroy the array. We don't ever need an EH cleanup because we
1708 // assume that we're in an EH cleanup ourselves, so a throwing
1709 // destructor causes an immediate terminate.
John McCall7f416cc2015-09-08 08:05:57 +00001710 CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001711 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
John McCall178360e2011-07-11 08:38:19 +00001712}
1713
John McCall82fe67b2011-07-09 01:37:26 +00001714namespace {
John McCall178360e2011-07-11 08:38:19 +00001715 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1716 /// array destroy where the end pointer is regularly determined and
1717 /// does not need to be loaded from a local.
David Blaikie7e70d682015-08-18 22:40:54 +00001718 class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall178360e2011-07-11 08:38:19 +00001719 llvm::Value *ArrayBegin;
1720 llvm::Value *ArrayEnd;
1721 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001722 CodeGenFunction::Destroyer *Destroyer;
John McCall7f416cc2015-09-08 08:05:57 +00001723 CharUnits ElementAlign;
John McCall178360e2011-07-11 08:38:19 +00001724 public:
1725 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001726 QualType elementType, CharUnits elementAlign,
John McCall178360e2011-07-11 08:38:19 +00001727 CodeGenFunction::Destroyer *destroyer)
1728 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
John McCall7f416cc2015-09-08 08:05:57 +00001729 ElementType(elementType), Destroyer(destroyer),
1730 ElementAlign(elementAlign) {}
John McCall178360e2011-07-11 08:38:19 +00001731
Craig Topper4f12f102014-03-12 06:41:41 +00001732 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +00001733 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001734 ElementType, ElementAlign, Destroyer);
John McCall178360e2011-07-11 08:38:19 +00001735 }
1736 };
1737
1738 /// IrregularPartialArrayDestroy - a cleanup which performs a
1739 /// partial array destroy where the end pointer is irregularly
1740 /// determined and must be loaded from a local.
David Blaikie7e70d682015-08-18 22:40:54 +00001741 class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall82fe67b2011-07-09 01:37:26 +00001742 llvm::Value *ArrayBegin;
John McCall7f416cc2015-09-08 08:05:57 +00001743 Address ArrayEndPointer;
John McCall82fe67b2011-07-09 01:37:26 +00001744 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001745 CodeGenFunction::Destroyer *Destroyer;
John McCall7f416cc2015-09-08 08:05:57 +00001746 CharUnits ElementAlign;
John McCall82fe67b2011-07-09 01:37:26 +00001747 public:
John McCall178360e2011-07-11 08:38:19 +00001748 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00001749 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00001750 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001751 CharUnits elementAlign,
John McCall178360e2011-07-11 08:38:19 +00001752 CodeGenFunction::Destroyer *destroyer)
John McCall82fe67b2011-07-09 01:37:26 +00001753 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
John McCall7f416cc2015-09-08 08:05:57 +00001754 ElementType(elementType), Destroyer(destroyer),
1755 ElementAlign(elementAlign) {}
John McCall82fe67b2011-07-09 01:37:26 +00001756
Craig Topper4f12f102014-03-12 06:41:41 +00001757 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall82fe67b2011-07-09 01:37:26 +00001758 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
John McCall178360e2011-07-11 08:38:19 +00001759 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001760 ElementType, ElementAlign, Destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001761 }
1762 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001763} // end anonymous namespace
John McCall82fe67b2011-07-09 01:37:26 +00001764
John McCall178360e2011-07-11 08:38:19 +00001765/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
John McCall82fe67b2011-07-09 01:37:26 +00001766/// already-constructed elements of the given array. The cleanup
John McCall178360e2011-07-11 08:38:19 +00001767/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001768///
John McCall82fe67b2011-07-09 01:37:26 +00001769/// \param elementType - the immediate element type of the array;
1770/// possibly still an array type
John McCall4bd0fb12011-07-12 16:41:08 +00001771void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00001772 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00001773 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001774 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001775 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001776 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1777 arrayBegin, arrayEndPointer,
John McCall7f416cc2015-09-08 08:05:57 +00001778 elementType, elementAlign,
1779 destroyer);
John McCall178360e2011-07-11 08:38:19 +00001780}
1781
1782/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1783/// already-constructed elements of the given array. The cleanup
1784/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001785///
John McCall178360e2011-07-11 08:38:19 +00001786/// \param elementType - the immediate element type of the array;
1787/// possibly still an array type
John McCall178360e2011-07-11 08:38:19 +00001788void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1789 llvm::Value *arrayEnd,
1790 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001791 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001792 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001793 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
John McCall178360e2011-07-11 08:38:19 +00001794 arrayBegin, arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001795 elementType, elementAlign,
1796 destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001797}
1798
Nadav Rotem1da30942013-03-23 06:43:35 +00001799/// Lazily declare the @llvm.lifetime.start intrinsic.
1800llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
Matt Arsenaultd9729492017-04-10 20:18:45 +00001801 if (LifetimeStartFn)
1802 return LifetimeStartFn;
Nadav Rotem1da30942013-03-23 06:43:35 +00001803 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
Yaxun Liu7f7f3232017-04-17 20:03:11 +00001804 llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);
Nadav Rotem1da30942013-03-23 06:43:35 +00001805 return LifetimeStartFn;
1806}
1807
1808/// Lazily declare the @llvm.lifetime.end intrinsic.
1809llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
Matt Arsenaultd9729492017-04-10 20:18:45 +00001810 if (LifetimeEndFn)
1811 return LifetimeEndFn;
Nadav Rotem1da30942013-03-23 06:43:35 +00001812 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
Yaxun Liu7f7f3232017-04-17 20:03:11 +00001813 llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);
Nadav Rotem1da30942013-03-23 06:43:35 +00001814 return LifetimeEndFn;
1815}
1816
John McCall31168b02011-06-15 23:02:42 +00001817namespace {
1818 /// A cleanup to perform a release of an object at the end of a
1819 /// function. This is used to balance out the incoming +1 of a
1820 /// ns_consumed argument when we can't reasonably do that just by
1821 /// not doing the initial retain for a __block argument.
David Blaikie7e70d682015-08-18 22:40:54 +00001822 struct ConsumeARCParameter final : EHScopeStack::Cleanup {
John McCallcdda29c2013-03-13 03:10:54 +00001823 ConsumeARCParameter(llvm::Value *param,
1824 ARCPreciseLifetime_t precise)
1825 : Param(param), Precise(precise) {}
John McCall31168b02011-06-15 23:02:42 +00001826
1827 llvm::Value *Param;
John McCallcdda29c2013-03-13 03:10:54 +00001828 ARCPreciseLifetime_t Precise;
John McCall31168b02011-06-15 23:02:42 +00001829
Craig Topper4f12f102014-03-12 06:41:41 +00001830 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001831 CGF.EmitARCRelease(Param, Precise);
John McCall31168b02011-06-15 23:02:42 +00001832 }
1833 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001834} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00001835
Mike Stump11289f42009-09-09 15:08:12 +00001836/// Emit an alloca (or GlobalValue depending on target)
Chris Lattnerb781dc792008-05-08 05:58:21 +00001837/// for the specified parameter and set up LocalDeclMap.
John McCall7f416cc2015-09-08 08:05:57 +00001838void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
1839 unsigned ArgNo) {
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001840 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Guptad7959242008-10-31 09:52:39 +00001841 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001842 "Invalid argument to EmitParmDecl");
John McCall147d0212011-02-22 22:38:33 +00001843
John McCall7f416cc2015-09-08 08:05:57 +00001844 Arg.getAnyValue()->setName(D.getName());
John McCall147d0212011-02-22 22:38:33 +00001845
Adrian Prantl51936dd2013-03-14 17:53:33 +00001846 QualType Ty = D.getType();
1847
John McCall147d0212011-02-22 22:38:33 +00001848 // Use better IR generation for certain implicit parameters.
John McCall7f416cc2015-09-08 08:05:57 +00001849 if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
John McCall147d0212011-02-22 22:38:33 +00001850 // The only implicit argument a block has is its literal.
Saleem Abdulrasoolc1b46382018-02-21 21:47:51 +00001851 // This may be passed as an inalloca'ed value on Windows x86.
John McCall147d0212011-02-22 22:38:33 +00001852 if (BlockInfo) {
Saleem Abdulrasoolc1b46382018-02-21 21:47:51 +00001853 llvm::Value *V = Arg.isIndirect()
1854 ? Builder.CreateLoad(Arg.getIndirectAddress())
1855 : Arg.getDirectValue();
1856 setBlockContextParameter(IPD, ArgNo, V);
John McCall147d0212011-02-22 22:38:33 +00001857 return;
1858 }
1859 }
1860
John McCall7f416cc2015-09-08 08:05:57 +00001861 Address DeclPtr = Address::invalid();
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001862 bool DoStore = false;
1863 bool IsScalar = hasScalarEvaluationKind(Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001864 // If we already have a pointer to the argument, reuse the input pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001865 if (Arg.isIndirect()) {
1866 DeclPtr = Arg.getIndirectAddress();
Reid Kleckner5e8edba2014-04-02 00:16:53 +00001867 // If we have a prettier pointer type at this point, bitcast to that.
John McCall7f416cc2015-09-08 08:05:57 +00001868 unsigned AS = DeclPtr.getType()->getAddressSpace();
Reid Kleckner5e8edba2014-04-02 00:16:53 +00001869 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
John McCall7f416cc2015-09-08 08:05:57 +00001870 if (DeclPtr.getType() != IRTy)
1871 DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
1872
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001873 // Push a destructor cleanup for this parameter if the ABI requires it.
Reid Kleckner19819442014-07-25 21:39:46 +00001874 // Don't push a cleanup in a thunk for a method that will also emit a
1875 // cleanup.
1876 if (!IsScalar && !CurFuncIsThunk &&
Akira Hatanaka02914dc2018-02-05 20:23:22 +00001877 getContext().isParamDestroyedInCallee(Ty)) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001878 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
1879 if (RD && RD->hasNonTrivialDestructor())
1880 pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001881 }
Chris Lattner53621a52007-06-13 20:44:40 +00001882 } else {
Daniel Dunbar3d33fab2010-02-08 22:53:07 +00001883 // Otherwise, create a temporary to hold the value.
John McCall7f416cc2015-09-08 08:05:57 +00001884 DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
1885 D.getName() + ".addr");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001886 DoStore = true;
1887 }
Mike Stump11289f42009-09-09 15:08:12 +00001888
John McCall7f416cc2015-09-08 08:05:57 +00001889 llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
1890
1891 LValue lv = MakeAddrLValue(DeclPtr, Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001892 if (IsScalar) {
John McCall31168b02011-06-15 23:02:42 +00001893 Qualifiers qs = Ty.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00001894 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1895 // We honor __attribute__((ns_consumed)) for types with lifetime.
1896 // For __strong, it's handled by just skipping the initial retain;
1897 // otherwise we have to balance out the initial +1 with an extra
1898 // cleanup to do the release at the end of the function.
1899 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1900
1901 // 'self' is always formally __strong, but if this is not an
1902 // init method then we don't want to retain it.
John McCalld4631322011-06-17 06:42:21 +00001903 if (D.isARCPseudoStrong()) {
John McCall31168b02011-06-15 23:02:42 +00001904 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1905 assert(&D == method->getSelfDecl());
John McCalld4631322011-06-17 06:42:21 +00001906 assert(lt == Qualifiers::OCL_Strong);
1907 assert(qs.hasConst());
John McCall31168b02011-06-15 23:02:42 +00001908 assert(method->getMethodFamily() != OMF_init);
John McCall10123692011-06-15 23:40:09 +00001909 (void) method;
John McCall31168b02011-06-15 23:02:42 +00001910 lt = Qualifiers::OCL_ExplicitNone;
1911 }
1912
Saleem Abdulrasoolda6784e2017-06-27 18:37:51 +00001913 // Load objects passed indirectly.
1914 if (Arg.isIndirect() && !ArgVal)
1915 ArgVal = Builder.CreateLoad(DeclPtr);
1916
John McCall31168b02011-06-15 23:02:42 +00001917 if (lt == Qualifiers::OCL_Strong) {
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001918 if (!isConsumed) {
1919 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1920 // use objc_storeStrong(&dest, value) for retaining the
1921 // object. But first, store a null into 'dest' because
1922 // objc_storeStrong attempts to release its old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001923 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001924 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
John McCall7f416cc2015-09-08 08:05:57 +00001925 EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001926 DoStore = false;
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001927 }
1928 else
John McCall31168b02011-06-15 23:02:42 +00001929 // Don't use objc_retainBlock for block pointers, because we
1930 // don't want to Block_copy something just because we got it
1931 // as a parameter.
John McCall7f416cc2015-09-08 08:05:57 +00001932 ArgVal = EmitARCRetainNonBlock(ArgVal);
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001933 }
John McCall31168b02011-06-15 23:02:42 +00001934 } else {
1935 // Push the cleanup for a consumed parameter.
John McCallcdda29c2013-03-13 03:10:54 +00001936 if (isConsumed) {
1937 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1938 ? ARCPreciseLifetime : ARCImpreciseLifetime);
John McCall7f416cc2015-09-08 08:05:57 +00001939 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
John McCallcdda29c2013-03-13 03:10:54 +00001940 precise);
1941 }
John McCall31168b02011-06-15 23:02:42 +00001942
1943 if (lt == Qualifiers::OCL_Weak) {
John McCall7f416cc2015-09-08 08:05:57 +00001944 EmitARCInitWeak(DeclPtr, ArgVal);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001945 DoStore = false; // The weak init is a store, no need to do two.
John McCall31168b02011-06-15 23:02:42 +00001946 }
1947 }
1948
1949 // Enter the cleanup scope.
1950 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1951 }
Chris Lattner53621a52007-06-13 20:44:40 +00001952 }
1953
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001954 // Store the initial value into the alloca.
1955 if (DoStore)
John McCall7f416cc2015-09-08 08:05:57 +00001956 EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001957
John McCall7f416cc2015-09-08 08:05:57 +00001958 setAddrOfLocalVar(&D, DeclPtr);
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001959
1960 // Emit debug info for param declaration.
Alexey Samsonov74a38682012-05-04 07:39:27 +00001961 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001962 if (CGM.getCodeGenOpts().getDebugInfo() >=
1963 codegenoptions::LimitedDebugInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001964 DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001965 }
1966 }
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001967
1968 if (D.hasAttr<AnnotateAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00001969 EmitVarAnnotations(&D, DeclPtr.getPointer());
Vedant Kumar42c17ec2017-03-14 01:56:34 +00001970
1971 // We can only check return value nullability if all arguments to the
1972 // function satisfy their nullability preconditions. This makes it necessary
1973 // to emit null checks for args in the function body itself.
1974 if (requiresReturnValueNullabilityCheck()) {
1975 auto Nullability = Ty->getNullability(getContext());
1976 if (Nullability && *Nullability == NullabilityKind::NonNull) {
1977 SanitizerScope SanScope(this);
1978 RetValNullabilityPrecondition =
1979 Builder.CreateAnd(RetValNullabilityPrecondition,
1980 Builder.CreateIsNotNull(Arg.getAnyValue()));
1981 }
1982 }
Chris Lattner53621a52007-06-13 20:44:40 +00001983}
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001984
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001985void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
1986 CodeGenFunction *CGF) {
1987 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
1988 return;
1989 getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
1990}