blob: 44ee6b3b3a64aae97bdcbe3750ba10733497e10b [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"
JF Bastien2f0582f2018-09-21 13:54:09 +000033#include "llvm/Analysis/ValueTracking.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000034#include "llvm/IR/DataLayout.h"
35#include "llvm/IR/GlobalVariable.h"
36#include "llvm/IR/Intrinsics.h"
37#include "llvm/IR/Type.h"
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +000038
Chris Lattner84915fa2007-06-02 04:16:21 +000039using namespace clang;
40using namespace CodeGen;
41
Chris Lattner1ad38f82007-06-09 01:20:56 +000042void CodeGenFunction::EmitDecl(const Decl &D) {
Chris Lattner1ad38f82007-06-09 01:20:56 +000043 switch (D.getKind()) {
David Majnemerd9b1a4f2015-11-04 03:40:30 +000044 case Decl::BuiltinTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000045 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +000046 case Decl::ExternCContext:
Douglas Gregor19043f02010-04-23 02:02:43 +000047 case Decl::Namespace:
48 case Decl::UnresolvedUsingTypename:
49 case Decl::ClassTemplateSpecialization:
50 case Decl::ClassTemplatePartialSpecialization:
Larisse Voufo39a1e502013-08-06 01:03:05 +000051 case Decl::VarTemplateSpecialization:
52 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor19043f02010-04-23 02:02:43 +000053 case Decl::TemplateTypeParm:
54 case Decl::UnresolvedUsingValue:
Alexis Hunted053252010-05-30 07:21:58 +000055 case Decl::NonTypeTemplateParm:
Richard Smithbc491202017-02-17 20:05:37 +000056 case Decl::CXXDeductionGuide:
Douglas Gregor19043f02010-04-23 02:02:43 +000057 case Decl::CXXMethod:
58 case Decl::CXXConstructor:
59 case Decl::CXXDestructor:
60 case Decl::CXXConversion:
61 case Decl::Field:
John McCall5e77d762013-04-16 07:28:30 +000062 case Decl::MSProperty:
Francois Pichetdf946c32010-11-21 06:49:41 +000063 case Decl::IndirectField:
Douglas Gregor19043f02010-04-23 02:02:43 +000064 case Decl::ObjCIvar:
Eric Christopher31ab1302011-08-23 22:38:00 +000065 case Decl::ObjCAtDefsField:
Chris Lattnerba9dddb2007-10-08 21:37:32 +000066 case Decl::ParmVar:
Douglas Gregor19043f02010-04-23 02:02:43 +000067 case Decl::ImplicitParam:
68 case Decl::ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +000069 case Decl::VarTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000070 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +000071 case Decl::TypeAliasTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000072 case Decl::TemplateTemplateParm:
73 case Decl::ObjCMethod:
74 case Decl::ObjCCategory:
75 case Decl::ObjCProtocol:
76 case Decl::ObjCInterface:
77 case Decl::ObjCCategoryImpl:
78 case Decl::ObjCImplementation:
79 case Decl::ObjCProperty:
80 case Decl::ObjCCompatibleAlias:
Nico Weber66220292016-03-02 17:28:48 +000081 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +000082 case Decl::PragmaDetectMismatch:
Abramo Bagnarad7340582010-06-05 05:09:32 +000083 case Decl::AccessSpec:
Douglas Gregor19043f02010-04-23 02:02:43 +000084 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +000085 case Decl::Export:
Douglas Gregor19043f02010-04-23 02:02:43 +000086 case Decl::ObjCPropertyImpl:
Douglas Gregor19043f02010-04-23 02:02:43 +000087 case Decl::FileScopeAsm:
88 case Decl::Friend:
89 case Decl::FriendTemplate:
90 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +000091 case Decl::Captured:
Francois Pichet00c7e6c2011-08-14 03:52:19 +000092 case Decl::ClassScopeFunctionSpecialization:
David Blaikiebd483762013-05-20 04:58:53 +000093 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +000094 case Decl::ConstructorUsingShadow:
Douglas Gregor85f3f952015-07-07 03:57:15 +000095 case Decl::ObjCTypeParam:
Richard Smithda383632016-08-15 01:33:41 +000096 case Decl::Binding:
David Blaikie83d382b2011-09-23 05:06:16 +000097 llvm_unreachable("Declaration should not be in declstmts!");
Amjad Abouddc4531e2016-04-30 01:44:38 +000098 case Decl::Function: // void X();
99 case Decl::Record: // struct/union/class X;
100 case Decl::Enum: // enum X;
101 case Decl::EnumConstant: // enum ? { X = ? }
102 case Decl::CXXRecord: // struct/union/class X; [C++]
Anders Carlssonce2cd012009-12-03 17:26:31 +0000103 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
Chris Lattner43e7f312011-02-18 02:08:43 +0000104 case Decl::Label: // __label__ x;
Douglas Gregorba345522011-12-02 23:23:56 +0000105 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +0000106 case Decl::OMPThreadPrivate:
Alexey Bataev4244be22016-02-11 05:35:55 +0000107 case Decl::OMPCapturedExpr:
Michael Han84324352013-02-22 17:15:32 +0000108 case Decl::Empty:
Chris Lattner84915fa2007-06-02 04:16:21 +0000109 // None of these decls require codegen support.
110 return;
David Blaikieb7d1e1f2013-02-02 00:39:32 +0000111
David Blaikief121b932013-05-20 22:50:41 +0000112 case Decl::NamespaceAlias:
113 if (CGDebugInfo *DI = getDebugInfo())
Amjad Abouddc4531e2016-04-30 01:44:38 +0000114 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
David Blaikief121b932013-05-20 22:50:41 +0000115 return;
David Blaikiebd483762013-05-20 04:58:53 +0000116 case Decl::Using: // using X; [C++]
117 if (CGDebugInfo *DI = getDebugInfo())
Amjad Abouddc4531e2016-04-30 01:44:38 +0000118 DI->EmitUsingDecl(cast<UsingDecl>(D));
David Blaikiebd483762013-05-20 04:58:53 +0000119 return;
Richard Smith151c4562016-12-20 21:35:28 +0000120 case Decl::UsingPack:
121 for (auto *Using : cast<UsingPackDecl>(D).expansions())
122 EmitDecl(*Using);
123 return;
David Blaikie9f88fe82013-04-22 06:13:21 +0000124 case Decl::UsingDirective: // using namespace X; [C++]
125 if (CGDebugInfo *DI = getDebugInfo())
126 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
127 return;
Richard Smithbdb84f32016-07-22 23:36:59 +0000128 case Decl::Var:
129 case Decl::Decomposition: {
Daniel Dunbara7998072008-08-29 17:28:43 +0000130 const VarDecl &VD = cast<VarDecl>(D);
John McCall1c9c3fd2010-10-15 04:57:14 +0000131 assert(VD.isLocalVarDecl() &&
Daniel Dunbara7998072008-08-29 17:28:43 +0000132 "Should not see file-scope variables inside a function!");
Richard Smithda383632016-08-15 01:33:41 +0000133 EmitVarDecl(VD);
134 if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
135 for (auto *B : DD->bindings())
136 if (auto *HD = B->getHoldingVar())
137 EmitVarDecl(*HD);
138 return;
Chris Lattner84915fa2007-06-02 04:16:21 +0000139 }
Mike Stump11289f42009-09-09 15:08:12 +0000140
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000141 case Decl::OMPDeclareReduction:
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000142 return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000143
Richard Smithdda56e42011-04-15 14:24:37 +0000144 case Decl::Typedef: // typedef int X;
145 case Decl::TypeAlias: { // using X = int; [C++0x]
146 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000147 QualType Ty = TD.getUnderlyingType();
Mike Stump11289f42009-09-09 15:08:12 +0000148
Anders Carlsson5d985f52008-12-20 21:51:53 +0000149 if (Ty->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000150 EmitVariablyModifiedType(Ty);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000151 }
Daniel Dunbara7998072008-08-29 17:28:43 +0000152 }
Chris Lattner84915fa2007-06-02 04:16:21 +0000153}
Chris Lattner03df1222007-06-02 04:53:11 +0000154
John McCall1c9c3fd2010-10-15 04:57:14 +0000155/// EmitVarDecl - This method handles emission of any variable declaration
Chris Lattner03df1222007-06-02 04:53:11 +0000156/// inside a function, including static vars etc.
John McCall1c9c3fd2010-10-15 04:57:14 +0000157void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Yaxun Liu4f33b3d2017-05-15 14:47:47 +0000158 if (D.hasExternalStorage())
159 // Don't emit it now, allow it to be emitted lazily on its first use.
160 return;
161
162 // Some function-scope variable does not have static storage but still
163 // needs to be emitted like a static variable, e.g. a function-scope
164 // variable in constant address space in OpenCL.
165 if (D.getStorageDuration() != SD_Automatic) {
Alexey Baderbed40092017-11-15 11:38:17 +0000166 // Static sampler variables translated to function calls.
167 if (D.getType()->isSamplerT())
168 return;
169
Eric Christopher31ab1302011-08-23 22:38:00 +0000170 llvm::GlobalValue::LinkageTypes Linkage =
David Majnemer27d69db2014-04-28 22:17:59 +0000171 CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000172
David Majnemer27d69db2014-04-28 22:17:59 +0000173 // FIXME: We need to force the emission/use of a guard variable for
174 // some variables even if we can constant-evaluate them because
175 // we can't guarantee every translation unit will constant-evaluate them.
Eric Christopher31ab1302011-08-23 22:38:00 +0000176
John McCall1c9c3fd2010-10-15 04:57:14 +0000177 return EmitStaticVarDecl(D, Linkage);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000178 }
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000179
Anastasia Stulovabcea6962015-09-30 14:08:20 +0000180 if (D.getType().getAddressSpace() == LangAS::opencl_local)
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000181 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
182
183 assert(D.hasLocalStorage());
184 return EmitAutoVarDecl(D);
Chris Lattner03df1222007-06-02 04:53:11 +0000185}
186
Reid Kleckner453e0562014-10-08 01:07:54 +0000187static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
188 if (CGM.getLangOpts().CPlusPlus)
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000189 return CGM.getMangledName(&D).str();
190
Reid Kleckner453e0562014-10-08 01:07:54 +0000191 // If this isn't C++, we don't need a mangled name, just a pretty one.
192 assert(!D.isExternallyVisible() && "name shouldn't matter");
193 std::string ContextName;
194 const DeclContext *DC = D.getDeclContext();
Alexey Bataev43f74392015-05-07 06:28:46 +0000195 if (auto *CD = dyn_cast<CapturedDecl>(DC))
196 DC = cast<DeclContext>(CD->getNonClosureContext());
Reid Kleckner453e0562014-10-08 01:07:54 +0000197 if (const auto *FD = dyn_cast<FunctionDecl>(DC))
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000198 ContextName = CGM.getMangledName(FD);
Reid Kleckner453e0562014-10-08 01:07:54 +0000199 else if (const auto *BD = dyn_cast<BlockDecl>(DC))
200 ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
201 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
202 ContextName = OMD->getSelector().getAsString();
Chris Lattnere99c1102009-12-05 08:22:11 +0000203 else
David Blaikie83d382b2011-09-23 05:06:16 +0000204 llvm_unreachable("Unknown context for static var decl");
Eric Christopher31ab1302011-08-23 22:38:00 +0000205
Reid Kleckner453e0562014-10-08 01:07:54 +0000206 ContextName += "." + D.getNameAsString();
207 return ContextName;
Chris Lattnere99c1102009-12-05 08:22:11 +0000208}
209
Reid Kleckner453e0562014-10-08 01:07:54 +0000210llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
211 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
212 // In general, we don't always emit static var decls once before we reference
213 // them. It is possible to reference them before emitting the function that
214 // contains them, and it is possible to emit the containing function multiple
215 // times.
216 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
217 return ExistingGV;
218
Chris Lattnerfc4379f2008-04-06 23:10:54 +0000219 QualType Ty = D.getType();
Eli Friedmana682d392008-02-15 12:20:59 +0000220 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begemanfaae0812008-04-19 04:17:09 +0000221
Benjamin Kramerddbb2b82011-11-20 21:05:04 +0000222 // Use the label if the variable is renamed with the asm-label extension.
223 std::string Name;
Benjamin Kramer5642e192011-11-21 15:47:23 +0000224 if (D.hasAttr<AsmLabelAttr>())
Reid Kleckner453e0562014-10-08 01:07:54 +0000225 Name = getMangledName(&D);
Benjamin Kramer5642e192011-11-21 15:47:23 +0000226 else
Reid Kleckner453e0562014-10-08 01:07:54 +0000227 Name = getStaticDeclName(*this, D);
Nate Begemanfaae0812008-04-19 04:17:09 +0000228
Reid Kleckner453e0562014-10-08 01:07:54 +0000229 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
Alexander Richardson6d989432017-10-15 18:48:14 +0000230 LangAS AS = GetGlobalVarAddressSpace(&D);
Yaxun Liucbf647c2017-07-08 13:24:52 +0000231 unsigned TargetAS = getContext().getTargetAddressSpace(AS);
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000232
Yaxun Liua64a4912018-04-02 17:38:24 +0000233 // OpenCL variables in local address space and CUDA shared
234 // variables cannot have an initializer.
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000235 llvm::Constant *Init = nullptr;
Yaxun Liua64a4912018-04-02 17:38:24 +0000236 if (Ty.getAddressSpace() == LangAS::opencl_local ||
237 D.hasAttr<CUDASharedAttr>())
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000238 Init = llvm::UndefValue::get(LTy);
Yaxun Liua64a4912018-04-02 17:38:24 +0000239 else
240 Init = EmitNullConstant(Ty);
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000241
Yaxun Liucbf647c2017-07-08 13:24:52 +0000242 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
243 getModule(), LTy, Ty.isConstant(getContext()), Linkage, Init, Name,
244 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
Ken Dyck160146e2010-01-27 17:10:57 +0000245 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000246
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +0000247 if (supportsCOMDAT() && GV->isWeakForLinker())
248 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Rafael Espindola0d4fb982015-01-12 22:13:53 +0000249
Richard Smithfd3834f2013-04-13 02:43:54 +0000250 if (D.getTLSKind())
Reid Kleckner453e0562014-10-08 01:07:54 +0000251 setTLSMode(GV, D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000252
Rafael Espindola922f2aa2018-02-23 19:30:48 +0000253 setGVProperties(GV, &D);
254
Eli Benderskycb399432014-03-24 22:05:38 +0000255 // Make sure the result is of the correct type.
Alexander Richardson6d989432017-10-15 18:48:14 +0000256 LangAS ExpectedAS = Ty.getAddressSpace();
Reid Kleckner453e0562014-10-08 01:07:54 +0000257 llvm::Constant *Addr = GV;
Yaxun Liucbf647c2017-07-08 13:24:52 +0000258 if (AS != ExpectedAS) {
259 Addr = getTargetCodeGenInfo().performAddrSpaceCast(
260 *this, GV, AS, ExpectedAS,
261 LTy->getPointerTo(getContext().getTargetAddressSpace(ExpectedAS)));
Eli Benderskycb399432014-03-24 22:05:38 +0000262 }
263
Reid Kleckner453e0562014-10-08 01:07:54 +0000264 setStaticLocalDeclAddress(&D, Addr);
265
266 // Ensure that the static local gets initialized by making sure the parent
267 // function gets emitted eventually.
268 const Decl *DC = cast<Decl>(D.getDeclContext());
269
270 // We can't name blocks or captured statements directly, so try to emit their
271 // parents.
272 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
273 DC = DC->getNonClosureContext();
274 // FIXME: Ensure that global blocks get emitted.
275 if (!DC)
276 return Addr;
277 }
278
279 GlobalDecl GD;
280 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
281 GD = GlobalDecl(CD, Ctor_Base);
282 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
283 GD = GlobalDecl(DD, Dtor_Base);
284 else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
285 GD = GlobalDecl(FD);
286 else {
287 // Don't do anything for Obj-C method decls or global closures. We should
288 // never defer them.
289 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
290 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +0000291 if (GD.getDecl()) {
292 // Disable emission of the parent function for the OpenMP device codegen.
293 CGOpenMPRuntime::DisableAutoDeclareTargetRAII NoDeclTarget(*this);
Reid Kleckner453e0562014-10-08 01:07:54 +0000294 (void)GetAddrOfGlobal(GD);
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +0000295 }
Reid Kleckner453e0562014-10-08 01:07:54 +0000296
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
Akira Hatanaka673af7a2018-03-29 17:56:24 +0000473 template <class Derived>
474 struct DestroyNRVOVariable : EHScopeStack::Cleanup {
475 DestroyNRVOVariable(Address addr, llvm::Value *NRVOFlag)
476 : NRVOFlag(NRVOFlag), Loc(addr) {}
John McCall2b7fc382010-07-13 20:32:21 +0000477
John McCall2b7fc382010-07-13 20:32:21 +0000478 llvm::Value *NRVOFlag;
John McCall7f416cc2015-09-08 08:05:57 +0000479 Address Loc;
John McCall2b7fc382010-07-13 20:32:21 +0000480
Craig Topper4f12f102014-03-12 06:41:41 +0000481 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall2b7fc382010-07-13 20:32:21 +0000482 // Along the exceptions path we always execute the dtor.
John McCall30317fd2011-07-12 20:27:29 +0000483 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
John McCall2b7fc382010-07-13 20:32:21 +0000484
Craig Topper8a13c412014-05-21 05:09:00 +0000485 llvm::BasicBlock *SkipDtorBB = nullptr;
John McCall2b7fc382010-07-13 20:32:21 +0000486 if (NRVO) {
487 // If we exited via NRVO, we skip the destructor call.
488 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
489 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
John McCall7f416cc2015-09-08 08:05:57 +0000490 llvm::Value *DidNRVO =
491 CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
John McCall2b7fc382010-07-13 20:32:21 +0000492 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
493 CGF.EmitBlock(RunDtorBB);
494 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000495
Akira Hatanaka673af7a2018-03-29 17:56:24 +0000496 static_cast<Derived *>(this)->emitDestructorCall(CGF);
John McCall2b7fc382010-07-13 20:32:21 +0000497
498 if (NRVO) CGF.EmitBlock(SkipDtorBB);
499 }
Akira Hatanaka673af7a2018-03-29 17:56:24 +0000500
501 virtual ~DestroyNRVOVariable() = default;
502 };
503
504 struct DestroyNRVOVariableCXX final
505 : DestroyNRVOVariable<DestroyNRVOVariableCXX> {
506 DestroyNRVOVariableCXX(Address addr, const CXXDestructorDecl *Dtor,
507 llvm::Value *NRVOFlag)
508 : DestroyNRVOVariable<DestroyNRVOVariableCXX>(addr, NRVOFlag),
509 Dtor(Dtor) {}
510
511 const CXXDestructorDecl *Dtor;
512
513 void emitDestructorCall(CodeGenFunction &CGF) {
514 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
515 /*ForVirtualBase=*/false,
516 /*Delegating=*/false, Loc);
517 }
518 };
519
520 struct DestroyNRVOVariableC final
521 : DestroyNRVOVariable<DestroyNRVOVariableC> {
522 DestroyNRVOVariableC(Address addr, llvm::Value *NRVOFlag, QualType Ty)
523 : DestroyNRVOVariable<DestroyNRVOVariableC>(addr, NRVOFlag), Ty(Ty) {}
524
525 QualType Ty;
526
527 void emitDestructorCall(CodeGenFunction &CGF) {
528 CGF.destroyNonTrivialCStruct(CGF, Loc, Ty);
529 }
John McCall2b7fc382010-07-13 20:32:21 +0000530 };
John McCall2b7fc382010-07-13 20:32:21 +0000531
David Blaikie7e70d682015-08-18 22:40:54 +0000532 struct CallStackRestore final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000533 Address Stack;
534 CallStackRestore(Address Stack) : Stack(Stack) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000535 void Emit(CodeGenFunction &CGF, Flags flags) override {
Benjamin Kramer76399eb2011-09-27 21:06:10 +0000536 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
John McCalla464ff92010-07-21 06:13:08 +0000537 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
538 CGF.Builder.CreateCall(F, V);
539 }
540 };
541
David Blaikie7e70d682015-08-18 22:40:54 +0000542 struct ExtendGCLifetime final : EHScopeStack::Cleanup {
John McCall1bd25562011-06-24 23:21:27 +0000543 const VarDecl &Var;
544 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
545
Craig Topper4f12f102014-03-12 06:41:41 +0000546 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1bd25562011-06-24 23:21:27 +0000547 // Compute the address of the local variable, in case it's a
548 // byref or something.
John McCall113bee02012-03-10 09:33:50 +0000549 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
550 Var.getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +0000551 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
552 SourceLocation());
John McCall1bd25562011-06-24 23:21:27 +0000553 CGF.EmitExtendGCLifetime(value);
554 }
555 };
556
David Blaikie7e70d682015-08-18 22:40:54 +0000557 struct CallCleanupFunction final : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000558 llvm::Constant *CleanupFn;
559 const CGFunctionInfo &FnInfo;
John McCalla464ff92010-07-21 06:13:08 +0000560 const VarDecl &Var;
Eric Christopher31ab1302011-08-23 22:38:00 +0000561
John McCalla464ff92010-07-21 06:13:08 +0000562 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCallc533cb72011-02-22 06:44:22 +0000563 const VarDecl *Var)
564 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalla464ff92010-07-21 06:13:08 +0000565
Craig Topper4f12f102014-03-12 06:41:41 +0000566 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall113bee02012-03-10 09:33:50 +0000567 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
568 Var.getType(), VK_LValue, SourceLocation());
John McCallc533cb72011-02-22 06:44:22 +0000569 // Compute the address of the local variable, in case it's a byref
570 // or something.
John McCall7f416cc2015-09-08 08:05:57 +0000571 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer();
John McCallc533cb72011-02-22 06:44:22 +0000572
John McCalla464ff92010-07-21 06:13:08 +0000573 // In some cases, the type of the function argument will be different from
574 // the type of the pointer. An example of this is
575 // void f(void* arg);
576 // __attribute__((cleanup(f))) void *g;
577 //
578 // To fix this we insert a bitcast here.
579 QualType ArgTy = FnInfo.arg_begin()->type;
580 llvm::Value *Arg =
581 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
582
583 CallArgList Args;
Eli Friedman43dca6a2011-05-02 17:57:46 +0000584 Args.add(RValue::get(Arg),
585 CGF.getContext().getPointerType(Var.getType()));
John McCallb92ab1a2016-10-26 23:46:34 +0000586 auto Callee = CGCallee::forDirect(CleanupFn);
587 CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
John McCalla464ff92010-07-21 06:13:08 +0000588 }
589 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000590} // end anonymous namespace
John McCalla464ff92010-07-21 06:13:08 +0000591
John McCall31168b02011-06-15 23:02:42 +0000592/// EmitAutoVarWithLifetime - Does the setup required for an automatic
593/// variable with lifetime.
594static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
John McCall7f416cc2015-09-08 08:05:57 +0000595 Address addr,
John McCall31168b02011-06-15 23:02:42 +0000596 Qualifiers::ObjCLifetime lifetime) {
597 switch (lifetime) {
598 case Qualifiers::OCL_None:
599 llvm_unreachable("present but none");
600
601 case Qualifiers::OCL_ExplicitNone:
602 // nothing to do
603 break;
604
605 case Qualifiers::OCL_Strong: {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000606 CodeGenFunction::Destroyer *destroyer =
John McCall4bd0fb12011-07-12 16:41:08 +0000607 (var.hasAttr<ObjCPreciseLifetimeAttr>()
608 ? CodeGenFunction::destroyARCStrongPrecise
609 : CodeGenFunction::destroyARCStrongImprecise);
610
611 CleanupKind cleanupKind = CGF.getARCCleanupKind();
612 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
613 cleanupKind & EHCleanup);
John McCall31168b02011-06-15 23:02:42 +0000614 break;
615 }
616 case Qualifiers::OCL_Autoreleasing:
617 // nothing to do
618 break;
Eric Christopher31ab1302011-08-23 22:38:00 +0000619
John McCall31168b02011-06-15 23:02:42 +0000620 case Qualifiers::OCL_Weak:
621 // __weak objects always get EH cleanups; otherwise, exceptions
622 // could cause really nasty crashes instead of mere leaks.
John McCall4bd0fb12011-07-12 16:41:08 +0000623 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
624 CodeGenFunction::destroyARCWeak,
625 /*useEHCleanup*/ true);
John McCall31168b02011-06-15 23:02:42 +0000626 break;
627 }
628}
629
630static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
631 if (const Expr *e = dyn_cast<Expr>(s)) {
632 // Skip the most common kinds of expressions that make
633 // hierarchy-walking expensive.
634 s = e = e->IgnoreParenCasts();
635
636 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
637 return (ref->getDecl() == &var);
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000638 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
639 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +0000640 for (const auto &I : block->captures()) {
641 if (I.getVariable() == &var)
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000642 return true;
643 }
644 }
John McCall31168b02011-06-15 23:02:42 +0000645 }
646
Benjamin Kramer642f1732015-07-02 21:03:14 +0000647 for (const Stmt *SubStmt : s->children())
648 // SubStmt might be null; as in missing decl or conditional of an if-stmt.
649 if (SubStmt && isAccessedBy(var, SubStmt))
John McCall31168b02011-06-15 23:02:42 +0000650 return true;
651
652 return false;
653}
654
655static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
656 if (!decl) return false;
657 if (!isa<VarDecl>(decl)) return false;
658 const VarDecl *var = cast<VarDecl>(decl);
659 return isAccessedBy(*var, e);
660}
661
John McCallf8a9b662015-10-21 18:06:31 +0000662static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
663 const LValue &destLV, const Expr *init) {
John McCall0204e342015-11-16 22:11:41 +0000664 bool needsCast = false;
665
John McCallf8a9b662015-10-21 18:06:31 +0000666 while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
667 switch (castExpr->getCastKind()) {
668 // Look through casts that don't require representation changes.
669 case CK_NoOp:
670 case CK_BitCast:
671 case CK_BlockPointerToObjCPointerCast:
John McCall0204e342015-11-16 22:11:41 +0000672 needsCast = true;
John McCallf8a9b662015-10-21 18:06:31 +0000673 break;
674
675 // If we find an l-value to r-value cast from a __weak variable,
676 // emit this operation as a copy or move.
677 case CK_LValueToRValue: {
678 const Expr *srcExpr = castExpr->getSubExpr();
679 if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
680 return false;
681
682 // Emit the source l-value.
683 LValue srcLV = CGF.EmitLValue(srcExpr);
684
John McCall0204e342015-11-16 22:11:41 +0000685 // Handle a formal type change to avoid asserting.
686 auto srcAddr = srcLV.getAddress();
687 if (needsCast) {
688 srcAddr = CGF.Builder.CreateElementBitCast(srcAddr,
689 destLV.getAddress().getElementType());
690 }
691
John McCallf8a9b662015-10-21 18:06:31 +0000692 // If it was an l-value, use objc_copyWeak.
693 if (srcExpr->getValueKind() == VK_LValue) {
John McCall0204e342015-11-16 22:11:41 +0000694 CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr);
John McCallf8a9b662015-10-21 18:06:31 +0000695 } else {
696 assert(srcExpr->getValueKind() == VK_XValue);
John McCall0204e342015-11-16 22:11:41 +0000697 CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr);
John McCallf8a9b662015-10-21 18:06:31 +0000698 }
699 return true;
700 }
701
702 // Stop at anything else.
703 default:
704 return false;
705 }
706
707 init = castExpr->getSubExpr();
John McCallf8a9b662015-10-21 18:06:31 +0000708 }
709 return false;
710}
711
John McCall1553b192011-06-16 04:16:24 +0000712static void drillIntoBlockVariable(CodeGenFunction &CGF,
713 LValue &lvalue,
714 const VarDecl *var) {
John McCall7f416cc2015-09-08 08:05:57 +0000715 lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var));
John McCall1553b192011-06-16 04:16:24 +0000716}
717
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000718void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS,
719 SourceLocation Loc) {
720 if (!SanOpts.has(SanitizerKind::NullabilityAssign))
721 return;
722
723 auto Nullability = LHS.getType()->getNullability(getContext());
724 if (!Nullability || *Nullability != NullabilityKind::NonNull)
725 return;
726
727 // Check if the right hand side of the assignment is nonnull, if the left
728 // hand side must be nonnull.
729 SanitizerScope SanScope(this);
730 llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS);
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000731 llvm::Constant *StaticData[] = {
732 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(LHS.getType()),
Simon Pilgrim2df19982017-03-14 21:43:52 +0000733 llvm::ConstantInt::get(Int8Ty, 0), // The LogAlignment info is unused.
Vedant Kumar2b9f48a2017-03-14 16:48:29 +0000734 llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)};
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000735 EmitCheck({{IsNotNull, SanitizerKind::NullabilityAssign}},
736 SanitizerHandler::TypeMismatch, StaticData, RHS);
737}
738
David Blaikie73ca5692014-12-09 00:32:22 +0000739void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +0000740 LValue lvalue, bool capturedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000741 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +0000742 if (!lifetime) {
743 llvm::Value *value = EmitScalarExpr(init);
John McCall1553b192011-06-16 04:16:24 +0000744 if (capturedByInit)
745 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000746 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
David Blaikie66e41972015-01-14 07:38:27 +0000747 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
John McCall31168b02011-06-15 23:02:42 +0000748 return;
749 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000750
Fariborz Jahaniana5a469e2014-03-14 15:40:54 +0000751 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
752 init = DIE->getExpr();
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000753
John McCall31168b02011-06-15 23:02:42 +0000754 // If we're emitting a value with lifetime, we have to do the
755 // initialization *before* we leave the cleanup scopes.
John McCall08ef4662011-11-10 08:15:53 +0000756 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
757 enterFullExpression(ewc);
John McCall31168b02011-06-15 23:02:42 +0000758 init = ewc->getSubExpr();
John McCall08ef4662011-11-10 08:15:53 +0000759 }
760 CodeGenFunction::RunCleanupsScope Scope(*this);
John McCall31168b02011-06-15 23:02:42 +0000761
762 // We have to maintain the illusion that the variable is
763 // zero-initialized. If the variable might be accessed in its
764 // initializer, zero-initialize before running the initializer, then
765 // actually perform the initialization with an assign.
766 bool accessedByInit = false;
767 if (lifetime != Qualifiers::OCL_ExplicitNone)
John McCallb726a552011-07-28 07:23:35 +0000768 accessedByInit = (capturedByInit || isAccessedBy(D, init));
John McCall31168b02011-06-15 23:02:42 +0000769 if (accessedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000770 LValue tempLV = lvalue;
John McCall31168b02011-06-15 23:02:42 +0000771 // Drill down to the __block object if necessary.
John McCall31168b02011-06-15 23:02:42 +0000772 if (capturedByInit) {
773 // We can use a simple GEP for this because it can't have been
774 // moved yet.
John McCall7f416cc2015-09-08 08:05:57 +0000775 tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(),
776 cast<VarDecl>(D),
777 /*follow*/ false));
John McCall31168b02011-06-15 23:02:42 +0000778 }
779
John McCall7f416cc2015-09-08 08:05:57 +0000780 auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType());
Yaxun Liu402804b2016-12-15 08:09:08 +0000781 llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());
Eric Christopher31ab1302011-08-23 22:38:00 +0000782
John McCall31168b02011-06-15 23:02:42 +0000783 // If __weak, we want to use a barrier under certain conditions.
784 if (lifetime == Qualifiers::OCL_Weak)
John McCall1553b192011-06-16 04:16:24 +0000785 EmitARCInitWeak(tempLV.getAddress(), zero);
John McCall31168b02011-06-15 23:02:42 +0000786
787 // Otherwise just do a simple store.
788 else
David Chisnallfa35df62012-01-16 17:27:18 +0000789 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000790 }
791
792 // Emit the initializer.
Craig Topper8a13c412014-05-21 05:09:00 +0000793 llvm::Value *value = nullptr;
John McCall31168b02011-06-15 23:02:42 +0000794
795 switch (lifetime) {
796 case Qualifiers::OCL_None:
797 llvm_unreachable("present but none");
798
799 case Qualifiers::OCL_ExplicitNone:
John McCalle399e5b2016-01-27 18:32:30 +0000800 value = EmitARCUnsafeUnretainedScalarExpr(init);
John McCall31168b02011-06-15 23:02:42 +0000801 break;
802
803 case Qualifiers::OCL_Strong: {
804 value = EmitARCRetainScalarExpr(init);
805 break;
806 }
807
808 case Qualifiers::OCL_Weak: {
John McCallf8a9b662015-10-21 18:06:31 +0000809 // If it's not accessed by the initializer, try to emit the
810 // initialization with a copy or move.
811 if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
812 return;
813 }
814
John McCall31168b02011-06-15 23:02:42 +0000815 // No way to optimize a producing initializer into this. It's not
816 // worth optimizing for, because the value will immediately
817 // disappear in the common case.
818 value = EmitScalarExpr(init);
819
John McCall1553b192011-06-16 04:16:24 +0000820 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000821 if (accessedByInit)
John McCall1553b192011-06-16 04:16:24 +0000822 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +0000823 else
John McCall1553b192011-06-16 04:16:24 +0000824 EmitARCInitWeak(lvalue.getAddress(), value);
John McCall31168b02011-06-15 23:02:42 +0000825 return;
826 }
827
828 case Qualifiers::OCL_Autoreleasing:
829 value = EmitARCRetainAutoreleaseScalarExpr(init);
830 break;
831 }
832
John McCall1553b192011-06-16 04:16:24 +0000833 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000834
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000835 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
836
John McCall31168b02011-06-15 23:02:42 +0000837 // If the variable might have been accessed by its initializer, we
838 // might have to initialize with a barrier. We have to do this for
839 // both __weak and __strong, but __weak got filtered out above.
840 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000841 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
David Chisnallfa35df62012-01-16 17:27:18 +0000842 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCallcdda29c2013-03-13 03:10:54 +0000843 EmitARCRelease(oldValue, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +0000844 return;
845 }
846
David Chisnallfa35df62012-01-16 17:27:18 +0000847 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000848}
Chris Lattnerb85025f2010-12-01 02:05:19 +0000849
JF Bastiened92f602018-07-20 23:37:12 +0000850/// Decide whether we can emit the non-zero parts of the specified initializer
851/// with equal or fewer than NumStores scalar stores.
852static bool canEmitInitWithFewStoresAfterBZero(llvm::Constant *Init,
853 unsigned &NumStores) {
Chris Lattnere6af8862010-12-02 01:58:41 +0000854 // Zero and Undef never requires any extra stores.
855 if (isa<llvm::ConstantAggregateZero>(Init) ||
856 isa<llvm::ConstantPointerNull>(Init) ||
857 isa<llvm::UndefValue>(Init))
858 return true;
859 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
860 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
861 isa<llvm::ConstantExpr>(Init))
862 return Init->isNullValue() || NumStores--;
863
864 // See if we can emit each element.
865 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
866 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
867 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
JF Bastiened92f602018-07-20 23:37:12 +0000868 if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
Chris Lattnere6af8862010-12-02 01:58:41 +0000869 return false;
870 }
871 return true;
872 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000873
Chris Lattner236b3572012-01-31 04:36:19 +0000874 if (llvm::ConstantDataSequential *CDS =
875 dyn_cast<llvm::ConstantDataSequential>(Init)) {
876 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
877 llvm::Constant *Elt = CDS->getElementAsConstant(i);
JF Bastiened92f602018-07-20 23:37:12 +0000878 if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
Chris Lattner236b3572012-01-31 04:36:19 +0000879 return false;
880 }
881 return true;
882 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000883
Chris Lattnerb85025f2010-12-01 02:05:19 +0000884 // Anything else is hard and scary.
885 return false;
886}
887
JF Bastiened92f602018-07-20 23:37:12 +0000888/// For inits that canEmitInitWithFewStoresAfterBZero returned true for, emit
889/// the scalar stores that would be required.
890static void emitStoresForInitAfterBZero(CodeGenModule &CGM,
891 llvm::Constant *Init, Address Loc,
892 bool isVolatile, CGBuilderTy &Builder) {
Benjamin Kramer29f9a002012-08-27 22:07:02 +0000893 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
JF Bastiened92f602018-07-20 23:37:12 +0000894 "called emitStoresForInitAfterBZero for zero or undef value.");
Eric Christopher31ab1302011-08-23 22:38:00 +0000895
Chris Lattnere6af8862010-12-02 01:58:41 +0000896 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
897 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
898 isa<llvm::ConstantExpr>(Init)) {
JF Bastien9aab85a2018-07-13 20:33:23 +0000899 Builder.CreateStore(Init, Loc, isVolatile);
Chris Lattner236b3572012-01-31 04:36:19 +0000900 return;
901 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000902
903 if (llvm::ConstantDataSequential *CDS =
904 dyn_cast<llvm::ConstantDataSequential>(Init)) {
Chris Lattner236b3572012-01-31 04:36:19 +0000905 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
906 llvm::Constant *Elt = CDS->getElementAsConstant(i);
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000907
908 // If necessary, get a pointer to the element and emit it.
909 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
JF Bastiened92f602018-07-20 23:37:12 +0000910 emitStoresForInitAfterBZero(
JF Bastien9aab85a2018-07-13 20:33:23 +0000911 CGM, Elt,
912 Builder.CreateConstInBoundsGEP2_32(Loc, 0, i, CGM.getDataLayout()),
David Blaikie17ea2662015-04-04 21:07:17 +0000913 isVolatile, Builder);
Chris Lattner236b3572012-01-31 04:36:19 +0000914 }
Chris Lattnere6af8862010-12-02 01:58:41 +0000915 return;
916 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000917
Chris Lattnere6af8862010-12-02 01:58:41 +0000918 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
919 "Unknown value type!");
Eric Christopher31ab1302011-08-23 22:38:00 +0000920
Chris Lattnere6af8862010-12-02 01:58:41 +0000921 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
922 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000923
924 // If necessary, get a pointer to the element and emit it.
925 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
JF Bastiened92f602018-07-20 23:37:12 +0000926 emitStoresForInitAfterBZero(
JF Bastien9aab85a2018-07-13 20:33:23 +0000927 CGM, Elt,
928 Builder.CreateConstInBoundsGEP2_32(Loc, 0, i, CGM.getDataLayout()),
David Blaikie17ea2662015-04-04 21:07:17 +0000929 isVolatile, Builder);
Chris Lattnere6af8862010-12-02 01:58:41 +0000930 }
Chris Lattnerb85025f2010-12-01 02:05:19 +0000931}
932
JF Bastiened92f602018-07-20 23:37:12 +0000933/// Decide whether we should use bzero plus some stores to initialize a local
934/// variable instead of using a memcpy from a constant global. It is beneficial
935/// to use bzero if the global is all zeros, or mostly zeros and large.
936static bool shouldUseBZeroPlusStoresToInitialize(llvm::Constant *Init,
937 uint64_t GlobalSize) {
938 // If a global is all zeros, always use a bzero.
Chris Lattnerb85025f2010-12-01 02:05:19 +0000939 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
940
Chris Lattnerb85025f2010-12-01 02:05:19 +0000941 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
942 // do it if it will require 6 or fewer scalar stores.
943 // TODO: Should budget depends on the size? Avoiding a large global warrants
944 // plopping in more stores.
945 unsigned StoreBudget = 6;
946 uint64_t SizeLimit = 32;
Eric Christopher31ab1302011-08-23 22:38:00 +0000947
948 return GlobalSize > SizeLimit &&
JF Bastiened92f602018-07-20 23:37:12 +0000949 canEmitInitWithFewStoresAfterBZero(Init, StoreBudget);
Chris Lattnerb85025f2010-12-01 02:05:19 +0000950}
951
JF Bastien65089292018-07-25 04:29:03 +0000952/// Decide whether we should use memset to initialize a local variable instead
953/// of using a memcpy from a constant global. Assumes we've already decided to
954/// not user bzero.
955/// FIXME We could be more clever, as we are for bzero above, and generate
956/// memset followed by stores. It's unclear that's worth the effort.
JF Bastien2f0582f2018-09-21 13:54:09 +0000957static llvm::Value *shouldUseMemSetToInitialize(llvm::Constant *Init,
958 uint64_t GlobalSize) {
JF Bastien65089292018-07-25 04:29:03 +0000959 uint64_t SizeLimit = 32;
960 if (GlobalSize <= SizeLimit)
JF Bastien2f0582f2018-09-21 13:54:09 +0000961 return nullptr;
962 return llvm::isBytewiseValue(Init);
JF Bastien65089292018-07-25 04:29:03 +0000963}
964
JF Bastienb9cc1fc2018-08-07 21:55:13 +0000965static void emitStoresForConstant(CodeGenModule &CGM, const VarDecl &D,
966 Address Loc, bool isVolatile,
967 CGBuilderTy &Builder,
968 llvm::Constant *constant) {
969 auto *Int8Ty = llvm::IntegerType::getInt8Ty(CGM.getLLVMContext());
970 auto *IntPtrTy = CGM.getDataLayout().getIntPtrType(CGM.getLLVMContext());
971
972 // If the initializer is all or mostly the same, codegen with bzero / memset
973 // then do a few stores afterward.
974 uint64_t ConstantSize =
975 CGM.getDataLayout().getTypeAllocSize(constant->getType());
976 auto *SizeVal = llvm::ConstantInt::get(IntPtrTy, ConstantSize);
977 if (shouldUseBZeroPlusStoresToInitialize(constant, ConstantSize)) {
978 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
979 isVolatile);
980
981 bool valueAlreadyCorrect =
982 constant->isNullValue() || isa<llvm::UndefValue>(constant);
983 if (!valueAlreadyCorrect) {
984 Loc = Builder.CreateBitCast(
985 Loc, constant->getType()->getPointerTo(Loc.getAddressSpace()));
986 emitStoresForInitAfterBZero(CGM, constant, Loc, isVolatile, Builder);
987 }
988 return;
989 }
990
JF Bastien2f0582f2018-09-21 13:54:09 +0000991 llvm::Value *Pattern = shouldUseMemSetToInitialize(constant, ConstantSize);
992 if (Pattern) {
993 uint64_t Value = 0x00;
994 if (!isa<llvm::UndefValue>(Pattern)) {
995 const llvm::APInt &AP = cast<llvm::ConstantInt>(Pattern)->getValue();
996 assert(AP.getBitWidth() <= 8);
997 Value = AP.getLimitedValue();
998 }
JF Bastienb9cc1fc2018-08-07 21:55:13 +0000999 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, Value), SizeVal,
1000 isVolatile);
1001 return;
1002 }
1003
1004 // Otherwise, create a temporary global with the initializer then memcpy from
1005 // the global to the alloca.
1006 std::string Name = getStaticDeclName(CGM, D);
1007 unsigned AS = CGM.getContext().getTargetAddressSpace(
1008 CGM.getStringLiteralAddressSpace());
1009 llvm::Type *BP = llvm::PointerType::getInt8PtrTy(CGM.getLLVMContext(), AS);
1010
1011 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1012 CGM.getModule(), constant->getType(), true,
1013 llvm::GlobalValue::PrivateLinkage, constant, Name, nullptr,
1014 llvm::GlobalValue::NotThreadLocal, AS);
1015 GV->setAlignment(Loc.getAlignment().getQuantity());
1016 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1017
1018 Address SrcPtr = Address(GV, Loc.getAlignment());
1019 if (SrcPtr.getType() != BP)
1020 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
1021
1022 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, isVolatile);
1023}
1024
Nick Lewycky8a7d90b2010-12-30 20:21:55 +00001025/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Chris Lattner03df1222007-06-02 04:53:11 +00001026/// variable declaration with auto, register, or no storage class specifier.
Chris Lattnerb781dc792008-05-08 05:58:21 +00001027/// These turn into simple stack objects, or GlobalValues depending on target.
John McCallc533cb72011-02-22 06:44:22 +00001028void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
1029 AutoVarEmission emission = EmitAutoVarAlloca(D);
1030 EmitAutoVarInit(emission);
1031 EmitAutoVarCleanups(emission);
1032}
Chris Lattner03df1222007-06-02 04:53:11 +00001033
David Majnemerdc012fa2015-04-22 21:38:15 +00001034/// Emit a lifetime.begin marker if some criteria are satisfied.
1035/// \return a pointer to the temporary size Value if a marker was emitted, null
1036/// otherwise
1037llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
1038 llvm::Value *Addr) {
Vitaly Buka1c943322016-10-26 01:59:57 +00001039 if (!ShouldEmitLifetimeMarkers)
Reid Kleckner1ef49212015-04-23 18:07:13 +00001040 return nullptr;
1041
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001042 assert(Addr->getType()->getPointerAddressSpace() ==
1043 CGM.getDataLayout().getAllocaAddrSpace() &&
1044 "Pointer should be in alloca address space");
David Majnemerdc012fa2015-04-22 21:38:15 +00001045 llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
Yaxun Liu7f7f3232017-04-17 20:03:11 +00001046 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
Alexey Samsonovd918ff62015-06-12 22:31:32 +00001047 llvm::CallInst *C =
1048 Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +00001049 C->setDoesNotThrow();
1050 return SizeV;
1051}
1052
1053void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001054 assert(Addr->getType()->getPointerAddressSpace() ==
1055 CGM.getDataLayout().getAllocaAddrSpace() &&
1056 "Pointer should be in alloca address space");
Yaxun Liu7f7f3232017-04-17 20:03:11 +00001057 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
Alexey Samsonovd918ff62015-06-12 22:31:32 +00001058 llvm::CallInst *C =
1059 Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +00001060 C->setDoesNotThrow();
1061}
1062
Sander de Smalen891af03a2018-02-03 13:55:59 +00001063void CodeGenFunction::EmitAndRegisterVariableArrayDimensions(
1064 CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo) {
1065 // For each dimension stores its QualType and corresponding
1066 // size-expression Value.
1067 SmallVector<CodeGenFunction::VlaSizePair, 4> Dimensions;
1068
1069 // Break down the array into individual dimensions.
1070 QualType Type1D = D.getType();
1071 while (getContext().getAsVariableArrayType(Type1D)) {
1072 auto VlaSize = getVLAElements1D(Type1D);
1073 if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1074 Dimensions.emplace_back(C, Type1D.getUnqualifiedType());
1075 else {
Sander de Smalen9084a3b2018-02-13 07:49:34 +00001076 auto SizeExprAddr = CreateDefaultAlignTempAlloca(
1077 VlaSize.NumElts->getType(), "__vla_expr");
Sander de Smalen891af03a2018-02-03 13:55:59 +00001078 Builder.CreateStore(VlaSize.NumElts, SizeExprAddr);
1079 Dimensions.emplace_back(SizeExprAddr.getPointer(),
1080 Type1D.getUnqualifiedType());
1081 }
1082 Type1D = VlaSize.Type;
1083 }
1084
1085 if (!EmitDebugInfo)
1086 return;
1087
1088 // Register each dimension's size-expression with a DILocalVariable,
1089 // so that it can be used by CGDebugInfo when instantiating a DISubrange
1090 // to describe this array.
1091 for (auto &VlaSize : Dimensions) {
1092 llvm::Metadata *MD;
1093 if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1094 MD = llvm::ConstantAsMetadata::get(C);
1095 else {
1096 // Create an artificial VarDecl to generate debug info for.
1097 IdentifierInfo &NameIdent = getContext().Idents.getOwn(
1098 cast<llvm::AllocaInst>(VlaSize.NumElts)->getName());
1099 auto VlaExprTy = VlaSize.NumElts->getType()->getPointerElementType();
1100 auto QT = getContext().getIntTypeForBitwidth(
1101 VlaExprTy->getScalarSizeInBits(), false);
1102 auto *ArtificialDecl = VarDecl::Create(
1103 getContext(), const_cast<DeclContext *>(D.getDeclContext()),
1104 D.getLocation(), D.getLocation(), &NameIdent, QT,
1105 getContext().CreateTypeSourceInfo(QT), SC_Auto);
Sander de Smalen9084a3b2018-02-13 07:49:34 +00001106 ArtificialDecl->setImplicit();
Sander de Smalen891af03a2018-02-03 13:55:59 +00001107
1108 MD = DI->EmitDeclareOfAutoVariable(ArtificialDecl, VlaSize.NumElts,
1109 Builder);
1110 }
1111 assert(MD && "No Size expression debug node created");
1112 DI->registerVLASizeExpression(VlaSize.Type, MD);
1113 }
1114}
1115
John McCallc533cb72011-02-22 06:44:22 +00001116/// EmitAutoVarAlloca - Emit the alloca and debug information for a
Alp Tokerf6a24ce2013-12-05 16:25:25 +00001117/// local variable. Does not emit initialization or destruction.
John McCallc533cb72011-02-22 06:44:22 +00001118CodeGenFunction::AutoVarEmission
1119CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
1120 QualType Ty = D.getType();
Yaxun Liub7318e02017-10-13 03:37:48 +00001121 assert(
1122 Ty.getAddressSpace() == LangAS::Default ||
1123 (Ty.getAddressSpace() == LangAS::opencl_private && getLangOpts().OpenCL));
John McCallc533cb72011-02-22 06:44:22 +00001124
1125 AutoVarEmission emission(D);
1126
Akira Hatanaka9bd24522018-09-09 05:22:49 +00001127 bool isByRef = D.hasAttr<BlocksAttr>();
1128 emission.IsByRef = isByRef;
John McCallc533cb72011-02-22 06:44:22 +00001129
1130 CharUnits alignment = getContext().getDeclAlign(&D);
John McCallc533cb72011-02-22 06:44:22 +00001131
John McCall23c29fe2011-06-24 21:55:10 +00001132 // If the type is variably-modified, emit all the VLA sizes for it.
1133 if (Ty->isVariablyModifiedType())
1134 EmitVariablyModifiedType(Ty);
1135
Sander de Smalen891af03a2018-02-03 13:55:59 +00001136 auto *DI = getDebugInfo();
1137 bool EmitDebugInfo = DI && CGM.getCodeGenOpts().getDebugInfo() >=
1138 codegenoptions::LimitedDebugInfo;
1139
John McCall7f416cc2015-09-08 08:05:57 +00001140 Address address = Address::invalid();
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001141 Address AllocaAddr = Address::invalid();
Eli Friedmana682d392008-02-15 12:20:59 +00001142 if (Ty->isConstantSizeType()) {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001143 bool NRVO = getLangOpts().ElideConstructors &&
1144 D.isNRVOVariable();
John McCallc533cb72011-02-22 06:44:22 +00001145
Richard Smith2bcde3a2013-06-02 00:09:52 +00001146 // If this value is an array or struct with a statically determinable
1147 // constant initializer, there are optimizations we can do.
Rafael Espindola609f5d92013-03-26 18:41:47 +00001148 //
1149 // TODO: We should constant-evaluate the initializer of any variable,
1150 // as long as it is initialized by a constant expression. Currently,
1151 // isConstantInitializer produces wrong answers for structs with
1152 // reference or bitfield members, and a few other cases, and checking
1153 // for POD-ness protects us from some of these.
Richard Smith2bcde3a2013-06-02 00:09:52 +00001154 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
1155 (D.isConstexpr() ||
1156 ((Ty.isPODType(getContext()) ||
1157 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
1158 D.getInit()->isConstantInitializer(getContext(), false)))) {
John McCallc533cb72011-02-22 06:44:22 +00001159
Rafael Espindola609f5d92013-03-26 18:41:47 +00001160 // If the variable's a const type, and it's neither an NRVO
1161 // candidate nor a __block variable and has no mutable members,
1162 // emit it as a global instead.
Anastasia Stulovae4a1c382016-11-29 17:01:19 +00001163 // Exception is if a variable is located in non-constant address space
1164 // in OpenCL.
1165 if ((!getLangOpts().OpenCL ||
1166 Ty.getAddressSpace() == LangAS::opencl_constant) &&
Akira Hatanaka9bd24522018-09-09 05:22:49 +00001167 (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
1168 CGM.isTypeConstant(Ty, true))) {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001169 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCallc533cb72011-02-22 06:44:22 +00001170
John McCall7f416cc2015-09-08 08:05:57 +00001171 // Signal this condition to later callbacks.
1172 emission.Addr = Address::invalid();
Rafael Espindola609f5d92013-03-26 18:41:47 +00001173 assert(emission.wasEmittedAsGlobal());
1174 return emission;
Tanya Lattnerf9d41df2009-11-04 01:18:09 +00001175 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001176
Rafael Espindola609f5d92013-03-26 18:41:47 +00001177 // Otherwise, tell the initialization code that we're in this case.
1178 emission.IsConstantAggregate = true;
1179 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001180
Rafael Espindola609f5d92013-03-26 18:41:47 +00001181 // A normal fixed sized variable becomes an alloca in the entry block,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001182 // unless:
1183 // - it's an NRVO variable.
1184 // - we are compiling OpenMP and it's an OpenMP local variable.
Eric Christopher31ab1302011-08-23 22:38:00 +00001185
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001186 Address OpenMPLocalAddr =
1187 getLangOpts().OpenMP
1188 ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
1189 : Address::invalid();
1190 if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
1191 address = OpenMPLocalAddr;
1192 } else if (NRVO) {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001193 // The named return value optimization: allocate this variable in the
1194 // return slot, so that we can elide the copy when returning this
1195 // variable (C++0x [class.copy]p34).
John McCall7f416cc2015-09-08 08:05:57 +00001196 address = ReturnValue;
Eric Christopher31ab1302011-08-23 22:38:00 +00001197
Rafael Espindola609f5d92013-03-26 18:41:47 +00001198 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
Akira Hatanaka673af7a2018-03-29 17:56:24 +00001199 const auto *RD = RecordTy->getDecl();
1200 const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1201 if ((CXXRD && !CXXRD->hasTrivialDestructor()) ||
1202 RD->isNonTrivialToPrimitiveDestroy()) {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001203 // Create a flag that is used to indicate when the NRVO was applied
1204 // to this variable. Set it to zero to indicate that NRVO was not
1205 // applied.
1206 llvm::Value *Zero = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +00001207 Address NRVOFlag =
1208 CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
Rafael Espindola609f5d92013-03-26 18:41:47 +00001209 EnsureInsertPoint();
1210 Builder.CreateStore(Zero, NRVOFlag);
Eric Christopher31ab1302011-08-23 22:38:00 +00001211
Rafael Espindola609f5d92013-03-26 18:41:47 +00001212 // Record the NRVO flag for this variable.
John McCall7f416cc2015-09-08 08:05:57 +00001213 NRVOFlags[&D] = NRVOFlag.getPointer();
1214 emission.NRVOFlag = NRVOFlag.getPointer();
Nadav Rotem1da30942013-03-23 06:43:35 +00001215 }
Douglas Gregor290c93e2010-05-15 06:46:45 +00001216 }
Chris Lattnerb781dc792008-05-08 05:58:21 +00001217 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001218 CharUnits allocaAlignment;
1219 llvm::Type *allocaTy;
Akira Hatanaka9bd24522018-09-09 05:22:49 +00001220 if (isByRef) {
John McCall7f416cc2015-09-08 08:05:57 +00001221 auto &byrefInfo = getBlockByrefInfo(&D);
1222 allocaTy = byrefInfo.Type;
1223 allocaAlignment = byrefInfo.ByrefAlignment;
1224 } else {
1225 allocaTy = ConvertTypeForMem(Ty);
1226 allocaAlignment = alignment;
1227 }
Rafael Espindola609f5d92013-03-26 18:41:47 +00001228
John McCall999110f2015-09-08 09:18:30 +00001229 // Create the alloca. Note that we set the name separately from
1230 // building the instruction so that it's there even in no-asserts
1231 // builds.
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001232 address = CreateTempAlloca(allocaTy, allocaAlignment, D.getName(),
1233 /*ArraySize=*/nullptr, &AllocaAddr);
Rafael Espindola609f5d92013-03-26 18:41:47 +00001234
Reid Kleckner1f88e932015-10-07 21:03:41 +00001235 // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1236 // the catch parameter starts in the catchpad instruction, and we can't
1237 // insert code in those basic blocks.
1238 bool IsMSCatchParam =
1239 D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1240
Vitaly Buka64c80b42016-10-26 05:42:30 +00001241 // Emit a lifetime intrinsic if meaningful. There's no point in doing this
1242 // if we don't have a valid insertion point (?).
Reid Kleckner1f88e932015-10-07 21:03:41 +00001243 if (HaveInsertPoint() && !IsMSCatchParam) {
Akira Hatanakafdcd18b2017-01-25 22:55:13 +00001244 // If there's a jump into the lifetime of this variable, its lifetime
1245 // gets broken up into several regions in IR, which requires more work
1246 // to handle correctly. For now, just omit the intrinsics; this is a
1247 // rare case, and it's better to just be conservatively correct.
1248 // PR28267.
1249 //
1250 // We have to do this in all language modes if there's a jump past the
1251 // declaration. We also have to do it in C if there's a jump to an
1252 // earlier point in the current block because non-VLA lifetimes begin as
1253 // soon as the containing block is entered, not when its variables
1254 // actually come into scope; suppressing the lifetime annotations
1255 // completely in this case is unnecessarily pessimistic, but again, this
1256 // is rare.
1257 if (!Bypasses.IsBypassed(&D) &&
1258 !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
Vitaly Buka64c80b42016-10-26 05:42:30 +00001259 uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
1260 emission.SizeForLifetimeMarkers =
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001261 EmitLifetimeStart(size, AllocaAddr.getPointer());
Vitaly Buka64c80b42016-10-26 05:42:30 +00001262 }
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +00001263 } else {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001264 assert(!emission.useLifetimeMarkers());
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +00001265 }
Chris Lattnerb781dc792008-05-08 05:58:21 +00001266 }
Chris Lattner03df1222007-06-02 04:53:11 +00001267 } else {
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001268 EnsureInsertPoint();
1269
Anders Carlsson15949b32009-02-09 20:41:50 +00001270 if (!DidCallStackSave) {
Anders Carlsson30032882008-12-12 07:38:43 +00001271 // Save the stack.
John McCall7f416cc2015-09-08 08:05:57 +00001272 Address Stack =
1273 CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
Mike Stump11289f42009-09-09 15:08:12 +00001274
Anders Carlsson30032882008-12-12 07:38:43 +00001275 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
David Blaikie4ba525b2015-07-14 17:27:39 +00001276 llvm::Value *V = Builder.CreateCall(F);
Anders Carlsson30032882008-12-12 07:38:43 +00001277 Builder.CreateStore(V, Stack);
Anders Carlsson15949b32009-02-09 20:41:50 +00001278
1279 DidCallStackSave = true;
Mike Stump11289f42009-09-09 15:08:12 +00001280
John McCalla464ff92010-07-21 06:13:08 +00001281 // Push a cleanup block and restore the stack there.
John McCalle4df6c82011-01-28 08:37:24 +00001282 // FIXME: in general circumstances, this should be an EH cleanup.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001283 pushStackRestore(NormalCleanup, Stack);
Anders Carlsson30032882008-12-12 07:38:43 +00001284 }
Mike Stump11289f42009-09-09 15:08:12 +00001285
Sander de Smalen891af03a2018-02-03 13:55:59 +00001286 auto VlaSize = getVLASize(Ty);
1287 llvm::Type *llvmTy = ConvertTypeForMem(VlaSize.Type);
Anders Carlsson30032882008-12-12 07:38:43 +00001288
1289 // Allocate memory for the array.
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001290 address = CreateTempAlloca(llvmTy, alignment, "vla", VlaSize.NumElts,
1291 &AllocaAddr);
Sander de Smalen891af03a2018-02-03 13:55:59 +00001292
1293 // If we have debug info enabled, properly describe the VLA dimensions for
1294 // this type by registering the vla size expression for each of the
1295 // dimensions.
1296 EmitAndRegisterVariableArrayDimensions(DI, D, EmitDebugInfo);
Chris Lattner03df1222007-06-02 04:53:11 +00001297 }
Eli Friedmanf4084702008-12-20 23:11:59 +00001298
John McCall7f416cc2015-09-08 08:05:57 +00001299 setAddrOfLocalVar(&D, address);
1300 emission.Addr = address;
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001301 emission.AllocaAddr = AllocaAddr;
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001302
1303 // Emit debug info for local var declaration.
Sander de Smalen891af03a2018-02-03 13:55:59 +00001304 if (EmitDebugInfo && HaveInsertPoint()) {
1305 DI->setLocation(D.getLocation());
1306 (void)DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
1307 }
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001308
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001309 if (D.hasAttr<AnnotateAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00001310 EmitVarAnnotations(&D, address.getPointer());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001311
Kuba Mracek5e5e4e72017-04-14 16:53:25 +00001312 // Make sure we call @llvm.lifetime.end.
1313 if (emission.useLifetimeMarkers())
1314 EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001315 emission.getOriginalAllocatedAddress(),
Kuba Mracek5e5e4e72017-04-14 16:53:25 +00001316 emission.getSizeForLifetimeMarkers());
1317
John McCallc533cb72011-02-22 06:44:22 +00001318 return emission;
1319}
1320
JF Bastien6b239722018-05-19 04:21:26 +00001321static bool isCapturedBy(const VarDecl &, const Expr *);
1322
1323/// Determines whether the given __block variable is potentially
1324/// captured by the given statement.
1325static bool isCapturedBy(const VarDecl &Var, const Stmt *S) {
1326 if (const Expr *E = dyn_cast<Expr>(S))
1327 return isCapturedBy(Var, E);
1328 for (const Stmt *SubStmt : S->children())
1329 if (isCapturedBy(Var, SubStmt))
1330 return true;
1331 return false;
1332}
1333
John McCallc533cb72011-02-22 06:44:22 +00001334/// Determines whether the given __block variable is potentially
1335/// captured by the given expression.
JF Bastien6b239722018-05-19 04:21:26 +00001336static bool isCapturedBy(const VarDecl &Var, const Expr *E) {
John McCallc533cb72011-02-22 06:44:22 +00001337 // Skip the most common kinds of expressions that make
1338 // hierarchy-walking expensive.
JF Bastien6b239722018-05-19 04:21:26 +00001339 E = E->IgnoreParenCasts();
John McCallc533cb72011-02-22 06:44:22 +00001340
JF Bastien6b239722018-05-19 04:21:26 +00001341 if (const BlockExpr *BE = dyn_cast<BlockExpr>(E)) {
1342 const BlockDecl *Block = BE->getBlockDecl();
1343 for (const auto &I : Block->captures()) {
1344 if (I.getVariable() == &Var)
John McCallc533cb72011-02-22 06:44:22 +00001345 return true;
1346 }
1347
1348 // No need to walk into the subexpressions.
1349 return false;
1350 }
1351
JF Bastien6b239722018-05-19 04:21:26 +00001352 if (const StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001353 const CompoundStmt *CS = SE->getSubStmt();
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001354 for (const auto *BI : CS->body())
JF Bastien6b239722018-05-19 04:21:26 +00001355 if (const auto *BIE = dyn_cast<Expr>(BI)) {
1356 if (isCapturedBy(Var, BIE))
1357 return true;
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001358 }
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001359 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001360 // special case declarations
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001361 for (const auto *I : DS->decls()) {
1362 if (const auto *VD = dyn_cast<VarDecl>((I))) {
1363 const Expr *Init = VD->getInit();
JF Bastien6b239722018-05-19 04:21:26 +00001364 if (Init && isCapturedBy(Var, Init))
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001365 return true;
1366 }
1367 }
1368 }
1369 else
1370 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1371 // Later, provide code to poke into statements for capture analysis.
1372 return true;
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001373 return false;
1374 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001375
JF Bastien6b239722018-05-19 04:21:26 +00001376 for (const Stmt *SubStmt : E->children())
1377 if (isCapturedBy(Var, SubStmt))
John McCallc533cb72011-02-22 06:44:22 +00001378 return true;
1379
1380 return false;
1381}
1382
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001383/// Determine whether the given initializer is trivial in the sense
Douglas Gregor82e1af22011-07-01 21:08:19 +00001384/// that it requires no code to be generated.
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001385bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
Douglas Gregor82e1af22011-07-01 21:08:19 +00001386 if (!Init)
1387 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001388
Douglas Gregor82e1af22011-07-01 21:08:19 +00001389 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1390 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1391 if (Constructor->isTrivial() &&
1392 Constructor->isDefaultConstructor() &&
1393 !Construct->requiresZeroInitialization())
1394 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001395
Douglas Gregor82e1af22011-07-01 21:08:19 +00001396 return false;
1397}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001398
John McCallc533cb72011-02-22 06:44:22 +00001399void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001400 assert(emission.Variable && "emission was not valid!");
1401
John McCallc533cb72011-02-22 06:44:22 +00001402 // If this was emitted as a global constant, we're done.
1403 if (emission.wasEmittedAsGlobal()) return;
1404
John McCall9e2e22f2011-02-22 07:16:58 +00001405 const VarDecl &D = *emission.Variable;
Adrian Prantl95b24e92015-02-03 20:00:54 +00001406 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
John McCallc533cb72011-02-22 06:44:22 +00001407 QualType type = D.getType();
1408
Chris Lattner07eb7332007-07-12 00:39:48 +00001409 // If this local has an initializer, emit it now.
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001410 const Expr *Init = D.getInit();
1411
1412 // If we are at an unreachable point, we don't need to emit the initializer
1413 // unless it contains a label.
1414 if (!HaveInsertPoint()) {
John McCallc533cb72011-02-22 06:44:22 +00001415 if (!Init || !ContainsLabel(Init)) return;
1416 EnsureInsertPoint();
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001417 }
1418
John McCall73064872011-03-31 01:59:53 +00001419 // Initialize the structure of a __block variable.
Akira Hatanaka9bd24522018-09-09 05:22:49 +00001420 if (emission.IsByRef)
John McCall73064872011-03-31 01:59:53 +00001421 emitByrefStructureInit(emission);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001422
Akira Hatanaka7275da02018-02-28 07:15:55 +00001423 // Initialize the variable here if it doesn't have a initializer and it is a
1424 // C struct that is non-trivial to initialize or an array containing such a
1425 // struct.
1426 if (!Init &&
1427 type.isNonTrivialToPrimitiveDefaultInitialize() ==
1428 QualType::PDIK_Struct) {
1429 LValue Dst = MakeAddrLValue(emission.getAllocatedAddress(), type);
Akira Hatanaka9bd24522018-09-09 05:22:49 +00001430 if (emission.IsByRef)
Akira Hatanaka7275da02018-02-28 07:15:55 +00001431 drillIntoBlockVariable(*this, Dst, &D);
1432 defaultInitNonTrivialCStructVar(Dst);
1433 return;
1434 }
1435
Douglas Gregor82e1af22011-07-01 21:08:19 +00001436 if (isTrivialInitializer(Init))
1437 return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001438
John McCallc533cb72011-02-22 06:44:22 +00001439 // Check whether this is a byref variable that's potentially
1440 // captured and moved by its own initializer. If so, we'll need to
1441 // emit the initializer first, then copy into the variable.
Akira Hatanaka9bd24522018-09-09 05:22:49 +00001442 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
John McCallc533cb72011-02-22 06:44:22 +00001443
John McCall7f416cc2015-09-08 08:05:57 +00001444 Address Loc =
1445 capturedByInit ? emission.Addr : emission.getObjectAddress(*this);
John McCallc533cb72011-02-22 06:44:22 +00001446
Craig Topper8a13c412014-05-21 05:09:00 +00001447 llvm::Constant *constant = nullptr;
Richard Smith2bcde3a2013-06-02 00:09:52 +00001448 if (emission.IsConstantAggregate || D.isConstexpr()) {
Richard Smithfddd3842011-12-30 21:15:51 +00001449 assert(!capturedByInit && "constant init contains a capturing block?");
John McCallde0fe072017-08-15 21:42:52 +00001450 constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(D);
Richard Smithfddd3842011-12-30 21:15:51 +00001451 }
1452
1453 if (!constant) {
John McCall7f416cc2015-09-08 08:05:57 +00001454 LValue lv = MakeAddrLValue(Loc, type);
John McCall1553b192011-06-16 04:16:24 +00001455 lv.setNonGC(true);
David Blaikie66e41972015-01-14 07:38:27 +00001456 return EmitExprAsInit(Init, &D, lv, capturedByInit);
John McCall1553b192011-06-16 04:16:24 +00001457 }
John McCall91ca10f2011-03-08 09:11:50 +00001458
Richard Smith2bcde3a2013-06-02 00:09:52 +00001459 if (!emission.IsConstantAggregate) {
1460 // For simple scalar/complex initialization, store the value directly.
John McCall7f416cc2015-09-08 08:05:57 +00001461 LValue lv = MakeAddrLValue(Loc, type);
Richard Smith2bcde3a2013-06-02 00:09:52 +00001462 lv.setNonGC(true);
1463 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1464 }
1465
John McCallc533cb72011-02-22 06:44:22 +00001466 // If this is a simple aggregate initialization, we can optimize it
1467 // in various ways.
John McCall91ca10f2011-03-08 09:11:50 +00001468 bool isVolatile = type.isVolatileQualified();
John McCallc533cb72011-02-22 06:44:22 +00001469
Yaxun Liudaceb1e2018-05-14 19:20:12 +00001470 llvm::Type *BP = CGM.Int8Ty->getPointerTo(Loc.getAddressSpace());
John McCall7f416cc2015-09-08 08:05:57 +00001471 if (Loc.getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001472 Loc = Builder.CreateBitCast(Loc, BP);
Mon P Wangcc2ab0c2010-04-04 03:10:52 +00001473
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001474 emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant);
John McCall91ca10f2011-03-08 09:11:50 +00001475}
1476
Richard Smithe78fac52018-04-05 20:52:58 +00001477/// Emit an expression as an initializer for an object (variable, field, etc.)
1478/// at the given location. The expression is not necessarily the normal
1479/// initializer for the object, and the address is not necessarily
John McCall91ca10f2011-03-08 09:11:50 +00001480/// its normal location.
1481///
1482/// \param init the initializing expression
Richard Smithe78fac52018-04-05 20:52:58 +00001483/// \param D the object to act as if we're initializing
John McCall91ca10f2011-03-08 09:11:50 +00001484/// \param loc the address to initialize; its type is a pointer
Richard Smithe78fac52018-04-05 20:52:58 +00001485/// to the LLVM mapping of the object's type
John McCall91ca10f2011-03-08 09:11:50 +00001486/// \param alignment the alignment of the address
Richard Smithe78fac52018-04-05 20:52:58 +00001487/// \param capturedByInit true if \p D is a __block variable
John McCall91ca10f2011-03-08 09:11:50 +00001488/// whose address is potentially changed by the initializer
David Blaikie73ca5692014-12-09 00:32:22 +00001489void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +00001490 LValue lvalue, bool capturedByInit) {
John McCall31168b02011-06-15 23:02:42 +00001491 QualType type = D->getType();
John McCall91ca10f2011-03-08 09:11:50 +00001492
1493 if (type->isReferenceType()) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +00001494 RValue rvalue = EmitReferenceBindingToExpr(init);
Eric Christopher31ab1302011-08-23 22:38:00 +00001495 if (capturedByInit)
John McCall1553b192011-06-16 04:16:24 +00001496 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001497 EmitStoreThroughLValue(rvalue, lvalue, true);
John McCall47fb9502013-03-07 21:37:08 +00001498 return;
1499 }
1500 switch (getEvaluationKind(type)) {
1501 case TEK_Scalar:
David Blaikie66e41972015-01-14 07:38:27 +00001502 EmitScalarInit(init, D, lvalue, capturedByInit);
John McCall47fb9502013-03-07 21:37:08 +00001503 return;
1504 case TEK_Complex: {
John McCall91ca10f2011-03-08 09:11:50 +00001505 ComplexPairTy complex = EmitComplexExpr(init);
John McCall1553b192011-06-16 04:16:24 +00001506 if (capturedByInit)
1507 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001508 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
John McCall47fb9502013-03-07 21:37:08 +00001509 return;
1510 }
1511 case TEK_Aggregate:
John McCalla8ec7eb2013-03-07 21:37:17 +00001512 if (type->isAtomicType()) {
1513 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1514 } else {
Richard Smithe78fac52018-04-05 20:52:58 +00001515 AggValueSlot::Overlap_t Overlap = AggValueSlot::MayOverlap;
1516 if (isa<VarDecl>(D))
1517 Overlap = AggValueSlot::DoesNotOverlap;
1518 else if (auto *FD = dyn_cast<FieldDecl>(D))
1519 Overlap = overlapForFieldInit(FD);
John McCalla8ec7eb2013-03-07 21:37:17 +00001520 // TODO: how can we delay here if D is captured by its initializer?
1521 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001522 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001523 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00001524 AggValueSlot::IsNotAliased,
1525 Overlap));
John McCalla8ec7eb2013-03-07 21:37:17 +00001526 }
John McCall47fb9502013-03-07 21:37:08 +00001527 return;
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001528 }
John McCall47fb9502013-03-07 21:37:08 +00001529 llvm_unreachable("bad evaluation kind");
John McCallc533cb72011-02-22 06:44:22 +00001530}
John McCallbd309292010-07-06 01:34:17 +00001531
John McCall82fe67b2011-07-09 01:37:26 +00001532/// Enter a destroy cleanup for the given local variable.
1533void CodeGenFunction::emitAutoVarTypeCleanup(
1534 const CodeGenFunction::AutoVarEmission &emission,
1535 QualType::DestructionKind dtorKind) {
1536 assert(dtorKind != QualType::DK_none);
1537
1538 // Note that for __block variables, we want to destroy the
1539 // original stack object, not the possibly forwarded object.
John McCall7f416cc2015-09-08 08:05:57 +00001540 Address addr = emission.getObjectAddress(*this);
John McCall82fe67b2011-07-09 01:37:26 +00001541
1542 const VarDecl *var = emission.Variable;
1543 QualType type = var->getType();
1544
1545 CleanupKind cleanupKind = NormalAndEHCleanup;
Craig Topper8a13c412014-05-21 05:09:00 +00001546 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall82fe67b2011-07-09 01:37:26 +00001547
1548 switch (dtorKind) {
1549 case QualType::DK_none:
1550 llvm_unreachable("no cleanup for trivially-destructible variable");
1551
1552 case QualType::DK_cxx_destructor:
1553 // If there's an NRVO flag on the emission, we need a different
1554 // cleanup.
1555 if (emission.NRVOFlag) {
1556 assert(!type->isArrayType());
1557 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
Akira Hatanaka673af7a2018-03-29 17:56:24 +00001558 EHStack.pushCleanup<DestroyNRVOVariableCXX>(cleanupKind, addr, dtor,
1559 emission.NRVOFlag);
John McCall82fe67b2011-07-09 01:37:26 +00001560 return;
1561 }
1562 break;
1563
1564 case QualType::DK_objc_strong_lifetime:
1565 // Suppress cleanups for pseudo-strong variables.
1566 if (var->isARCPseudoStrong()) return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001567
John McCall82fe67b2011-07-09 01:37:26 +00001568 // Otherwise, consider whether to use an EH cleanup or not.
1569 cleanupKind = getARCCleanupKind();
1570
1571 // Use the imprecise destroyer by default.
1572 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1573 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1574 break;
1575
1576 case QualType::DK_objc_weak_lifetime:
1577 break;
Akira Hatanaka7275da02018-02-28 07:15:55 +00001578
1579 case QualType::DK_nontrivial_c_struct:
1580 destroyer = CodeGenFunction::destroyNonTrivialCStruct;
Akira Hatanaka673af7a2018-03-29 17:56:24 +00001581 if (emission.NRVOFlag) {
1582 assert(!type->isArrayType());
1583 EHStack.pushCleanup<DestroyNRVOVariableC>(cleanupKind, addr,
1584 emission.NRVOFlag, type);
1585 return;
1586 }
Akira Hatanaka7275da02018-02-28 07:15:55 +00001587 break;
John McCall82fe67b2011-07-09 01:37:26 +00001588 }
1589
1590 // If we haven't chosen a more specific destroyer, use the default.
Peter Collingbourne1425b452012-01-26 03:33:36 +00001591 if (!destroyer) destroyer = getDestroyer(dtorKind);
John McCall178360e2011-07-11 08:38:19 +00001592
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001593 // Use an EH cleanup in array destructors iff the destructor itself
John McCall178360e2011-07-11 08:38:19 +00001594 // is being pushed as an EH cleanup.
1595 bool useEHCleanup = (cleanupKind & EHCleanup);
1596 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1597 useEHCleanup);
John McCall82fe67b2011-07-09 01:37:26 +00001598}
1599
John McCallc533cb72011-02-22 06:44:22 +00001600void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001601 assert(emission.Variable && "emission was not valid!");
1602
John McCallc533cb72011-02-22 06:44:22 +00001603 // If this was emitted as a global constant, we're done.
1604 if (emission.wasEmittedAsGlobal()) return;
1605
John McCall8c38d352012-04-13 18:44:05 +00001606 // If we don't have an insertion point, we're done. Sema prevents
1607 // us from jumping into any of these scopes anyway.
1608 if (!HaveInsertPoint()) return;
1609
John McCall9e2e22f2011-02-22 07:16:58 +00001610 const VarDecl &D = *emission.Variable;
John McCallc533cb72011-02-22 06:44:22 +00001611
John McCall82fe67b2011-07-09 01:37:26 +00001612 // Check the type for a cleanup.
1613 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1614 emitAutoVarTypeCleanup(emission, dtorKind);
John McCall31168b02011-06-15 23:02:42 +00001615
John McCall1bd25562011-06-24 23:21:27 +00001616 // In GC mode, honor objc_precise_lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001617 if (getLangOpts().getGC() != LangOptions::NonGC &&
John McCall1bd25562011-06-24 23:21:27 +00001618 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1619 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1620 }
1621
John McCallc533cb72011-02-22 06:44:22 +00001622 // Handle the cleanup attribute.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001623 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001624 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001625
John McCallc533cb72011-02-22 06:44:22 +00001626 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001627 assert(F && "Could not find function!");
Mike Stump11289f42009-09-09 15:08:12 +00001628
John McCalla729c622012-02-17 03:33:10 +00001629 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
John McCallc533cb72011-02-22 06:44:22 +00001630 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001631 }
Mike Stump626aecc2009-03-05 01:23:13 +00001632
John McCallc533cb72011-02-22 06:44:22 +00001633 // If this is a block variable, call _Block_object_destroy
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001634 // (on the unforwarded address). Don't enter this cleanup if we're in pure-GC
1635 // mode.
Akira Hatanaka9bd24522018-09-09 05:22:49 +00001636 if (emission.IsByRef && CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001637 BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
1638 if (emission.Variable->getType().isObjCGCWeak())
1639 Flags |= BLOCK_FIELD_IS_WEAK;
1640 enterByrefCleanup(NormalAndEHCleanup, emission.Addr, Flags,
Akira Hatanaka9978da32018-08-10 15:09:24 +00001641 /*LoadBlockVarAddr*/ false,
1642 cxxDestructorCanThrow(emission.Variable->getType()));
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001643 }
Chris Lattner03df1222007-06-02 04:53:11 +00001644}
Chris Lattner53621a52007-06-13 20:44:40 +00001645
Peter Collingbourne1425b452012-01-26 03:33:36 +00001646CodeGenFunction::Destroyer *
John McCall82fe67b2011-07-09 01:37:26 +00001647CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1648 switch (kind) {
1649 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
John McCallc2f00012011-07-09 09:09:00 +00001650 case QualType::DK_cxx_destructor:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001651 return destroyCXXObject;
John McCallc2f00012011-07-09 09:09:00 +00001652 case QualType::DK_objc_strong_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001653 return destroyARCStrongPrecise;
John McCallc2f00012011-07-09 09:09:00 +00001654 case QualType::DK_objc_weak_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001655 return destroyARCWeak;
Akira Hatanaka7275da02018-02-28 07:15:55 +00001656 case QualType::DK_nontrivial_c_struct:
1657 return destroyNonTrivialCStruct;
John McCall82fe67b2011-07-09 01:37:26 +00001658 }
Matt Beaumont-Gay934bbf52012-01-27 00:46:27 +00001659 llvm_unreachable("Unknown DestructionKind");
John McCall82fe67b2011-07-09 01:37:26 +00001660}
1661
John McCall12cc42a2013-02-01 05:11:40 +00001662/// pushEHDestroy - Push the standard destructor for the given type as
1663/// an EH-only cleanup.
1664void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00001665 Address addr, QualType type) {
John McCall12cc42a2013-02-01 05:11:40 +00001666 assert(dtorKind && "cannot push destructor for trivial type");
1667 assert(needsEHCleanup(dtorKind));
1668
1669 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1670}
1671
1672/// pushDestroy - Push the standard destructor for the given type as
1673/// at least a normal cleanup.
John McCall4bd0fb12011-07-12 16:41:08 +00001674void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00001675 Address addr, QualType type) {
John McCall4bd0fb12011-07-12 16:41:08 +00001676 assert(dtorKind && "cannot push destructor for trivial type");
1677
1678 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1679 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1680 cleanupKind & EHCleanup);
1681}
1682
John McCall7f416cc2015-09-08 08:05:57 +00001683void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001684 QualType type, Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001685 bool useEHCleanupForArray) {
John McCall4bd0fb12011-07-12 16:41:08 +00001686 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1687 destroyer, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001688}
1689
John McCall7f416cc2015-09-08 08:05:57 +00001690void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001691 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
1692}
1693
Richard Smith736a9472013-06-12 20:42:33 +00001694void CodeGenFunction::pushLifetimeExtendedDestroy(
John McCall7f416cc2015-09-08 08:05:57 +00001695 CleanupKind cleanupKind, Address addr, QualType type,
Richard Smith736a9472013-06-12 20:42:33 +00001696 Destroyer *destroyer, bool useEHCleanupForArray) {
Richard Smith736a9472013-06-12 20:42:33 +00001697 // Push an EH-only cleanup for the object now.
1698 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1699 // around in case a temporary's destructor throws an exception.
1700 if (cleanupKind & EHCleanup)
1701 EHStack.pushCleanup<DestroyObject>(
1702 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1703 destroyer, useEHCleanupForArray);
1704
1705 // Remember that we need to push a full cleanup for the object at the
1706 // end of the full-expression.
1707 pushCleanupAfterFullExpr<DestroyObject>(
1708 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1709}
1710
John McCall178360e2011-07-11 08:38:19 +00001711/// emitDestroy - Immediately perform the destruction of the given
1712/// object.
1713///
1714/// \param addr - the address of the object; a type*
1715/// \param type - the type of the object; if an array type, all
1716/// objects are destroyed in reverse order
1717/// \param destroyer - the function to call to destroy individual
1718/// elements
1719/// \param useEHCleanupForArray - whether an EH cleanup should be
1720/// used when destroying array elements, in case one of the
1721/// destructions throws an exception
John McCall7f416cc2015-09-08 08:05:57 +00001722void CodeGenFunction::emitDestroy(Address addr, QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001723 Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001724 bool useEHCleanupForArray) {
John McCall82fe67b2011-07-09 01:37:26 +00001725 const ArrayType *arrayType = getContext().getAsArrayType(type);
1726 if (!arrayType)
1727 return destroyer(*this, addr, type);
1728
John McCall7f416cc2015-09-08 08:05:57 +00001729 llvm::Value *length = emitArrayLength(arrayType, type, addr);
1730
1731 CharUnits elementAlign =
1732 addr.getAlignment()
1733 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
John McCall97eab0a2011-07-13 08:09:46 +00001734
1735 // Normally we have to check whether the array is zero-length.
1736 bool checkZeroLength = true;
1737
1738 // But if the array length is constant, we can suppress that.
1739 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1740 // ...and if it's constant zero, we can just skip the entire thing.
1741 if (constLength->isZero()) return;
1742 checkZeroLength = false;
1743 }
1744
John McCall7f416cc2015-09-08 08:05:57 +00001745 llvm::Value *begin = addr.getPointer();
John McCall82fe67b2011-07-09 01:37:26 +00001746 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
John McCall7f416cc2015-09-08 08:05:57 +00001747 emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001748 checkZeroLength, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001749}
1750
John McCall178360e2011-07-11 08:38:19 +00001751/// emitArrayDestroy - Destroys all the elements of the given array,
1752/// beginning from last to first. The array cannot be zero-length.
1753///
1754/// \param begin - a type* denoting the first element of the array
1755/// \param end - a type* denoting one past the end of the array
NAKAMURA Takumiff7a9252015-09-08 09:42:41 +00001756/// \param elementType - the element type of the array
John McCall178360e2011-07-11 08:38:19 +00001757/// \param destroyer - the function to call to destroy elements
1758/// \param useEHCleanup - whether to push an EH cleanup to destroy
1759/// the remaining elements in case the destruction of a single
1760/// element throws
John McCall82fe67b2011-07-09 01:37:26 +00001761void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1762 llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00001763 QualType elementType,
1764 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001765 Destroyer *destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001766 bool checkZeroLength,
John McCall178360e2011-07-11 08:38:19 +00001767 bool useEHCleanup) {
John McCall7f416cc2015-09-08 08:05:57 +00001768 assert(!elementType->isArrayType());
John McCall82fe67b2011-07-09 01:37:26 +00001769
1770 // The basic structure here is a do-while loop, because we don't
1771 // need to check for the zero-element case.
1772 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1773 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1774
John McCall97eab0a2011-07-13 08:09:46 +00001775 if (checkZeroLength) {
1776 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1777 "arraydestroy.isempty");
1778 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1779 }
1780
John McCall82fe67b2011-07-09 01:37:26 +00001781 // Enter the loop body, making that address the current address.
1782 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1783 EmitBlock(bodyBB);
1784 llvm::PHINode *elementPast =
1785 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1786 elementPast->addIncoming(end, entryBB);
1787
1788 // Shift the address back by one element.
1789 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1790 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1791 "arraydestroy.element");
1792
John McCall178360e2011-07-11 08:38:19 +00001793 if (useEHCleanup)
John McCall7f416cc2015-09-08 08:05:57 +00001794 pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
1795 destroyer);
John McCall178360e2011-07-11 08:38:19 +00001796
John McCall82fe67b2011-07-09 01:37:26 +00001797 // Perform the actual destruction there.
John McCall7f416cc2015-09-08 08:05:57 +00001798 destroyer(*this, Address(element, elementAlign), elementType);
John McCall82fe67b2011-07-09 01:37:26 +00001799
John McCall178360e2011-07-11 08:38:19 +00001800 if (useEHCleanup)
1801 PopCleanupBlock();
1802
John McCall82fe67b2011-07-09 01:37:26 +00001803 // Check whether we've reached the end.
1804 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1805 Builder.CreateCondBr(done, doneBB, bodyBB);
1806 elementPast->addIncoming(element, Builder.GetInsertBlock());
1807
1808 // Done.
1809 EmitBlock(doneBB);
1810}
1811
John McCall178360e2011-07-11 08:38:19 +00001812/// Perform partial array destruction as if in an EH cleanup. Unlike
1813/// emitArrayDestroy, the element type here may still be an array type.
John McCall178360e2011-07-11 08:38:19 +00001814static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1815 llvm::Value *begin, llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00001816 QualType type, CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001817 CodeGenFunction::Destroyer *destroyer) {
John McCall178360e2011-07-11 08:38:19 +00001818 // If the element type is itself an array, drill down.
John McCall97eab0a2011-07-13 08:09:46 +00001819 unsigned arrayDepth = 0;
John McCall178360e2011-07-11 08:38:19 +00001820 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1821 // VLAs don't require a GEP index to walk into.
1822 if (!isa<VariableArrayType>(arrayType))
John McCall97eab0a2011-07-13 08:09:46 +00001823 arrayDepth++;
John McCall178360e2011-07-11 08:38:19 +00001824 type = arrayType->getElementType();
1825 }
John McCall97eab0a2011-07-13 08:09:46 +00001826
1827 if (arrayDepth) {
John McCallf0f0b7a2015-09-14 18:57:08 +00001828 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
John McCall97eab0a2011-07-13 08:09:46 +00001829
John McCallf0f0b7a2015-09-14 18:57:08 +00001830 SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
Jay Foad040dd822011-07-22 08:16:57 +00001831 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1832 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
John McCall178360e2011-07-11 08:38:19 +00001833 }
1834
John McCall97eab0a2011-07-13 08:09:46 +00001835 // Destroy the array. We don't ever need an EH cleanup because we
1836 // assume that we're in an EH cleanup ourselves, so a throwing
1837 // destructor causes an immediate terminate.
John McCall7f416cc2015-09-08 08:05:57 +00001838 CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001839 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
John McCall178360e2011-07-11 08:38:19 +00001840}
1841
John McCall82fe67b2011-07-09 01:37:26 +00001842namespace {
John McCall178360e2011-07-11 08:38:19 +00001843 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1844 /// array destroy where the end pointer is regularly determined and
1845 /// does not need to be loaded from a local.
David Blaikie7e70d682015-08-18 22:40:54 +00001846 class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall178360e2011-07-11 08:38:19 +00001847 llvm::Value *ArrayBegin;
1848 llvm::Value *ArrayEnd;
1849 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001850 CodeGenFunction::Destroyer *Destroyer;
John McCall7f416cc2015-09-08 08:05:57 +00001851 CharUnits ElementAlign;
John McCall178360e2011-07-11 08:38:19 +00001852 public:
1853 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001854 QualType elementType, CharUnits elementAlign,
John McCall178360e2011-07-11 08:38:19 +00001855 CodeGenFunction::Destroyer *destroyer)
1856 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
John McCall7f416cc2015-09-08 08:05:57 +00001857 ElementType(elementType), Destroyer(destroyer),
1858 ElementAlign(elementAlign) {}
John McCall178360e2011-07-11 08:38:19 +00001859
Craig Topper4f12f102014-03-12 06:41:41 +00001860 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +00001861 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001862 ElementType, ElementAlign, Destroyer);
John McCall178360e2011-07-11 08:38:19 +00001863 }
1864 };
1865
1866 /// IrregularPartialArrayDestroy - a cleanup which performs a
1867 /// partial array destroy where the end pointer is irregularly
1868 /// determined and must be loaded from a local.
David Blaikie7e70d682015-08-18 22:40:54 +00001869 class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall82fe67b2011-07-09 01:37:26 +00001870 llvm::Value *ArrayBegin;
John McCall7f416cc2015-09-08 08:05:57 +00001871 Address ArrayEndPointer;
John McCall82fe67b2011-07-09 01:37:26 +00001872 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001873 CodeGenFunction::Destroyer *Destroyer;
John McCall7f416cc2015-09-08 08:05:57 +00001874 CharUnits ElementAlign;
John McCall82fe67b2011-07-09 01:37:26 +00001875 public:
John McCall178360e2011-07-11 08:38:19 +00001876 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00001877 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00001878 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001879 CharUnits elementAlign,
John McCall178360e2011-07-11 08:38:19 +00001880 CodeGenFunction::Destroyer *destroyer)
John McCall82fe67b2011-07-09 01:37:26 +00001881 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
John McCall7f416cc2015-09-08 08:05:57 +00001882 ElementType(elementType), Destroyer(destroyer),
1883 ElementAlign(elementAlign) {}
John McCall82fe67b2011-07-09 01:37:26 +00001884
Craig Topper4f12f102014-03-12 06:41:41 +00001885 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall82fe67b2011-07-09 01:37:26 +00001886 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
John McCall178360e2011-07-11 08:38:19 +00001887 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001888 ElementType, ElementAlign, Destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001889 }
1890 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001891} // end anonymous namespace
John McCall82fe67b2011-07-09 01:37:26 +00001892
John McCall178360e2011-07-11 08:38:19 +00001893/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
John McCall82fe67b2011-07-09 01:37:26 +00001894/// already-constructed elements of the given array. The cleanup
John McCall178360e2011-07-11 08:38:19 +00001895/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001896///
John McCall82fe67b2011-07-09 01:37:26 +00001897/// \param elementType - the immediate element type of the array;
1898/// possibly still an array type
John McCall4bd0fb12011-07-12 16:41:08 +00001899void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00001900 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00001901 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001902 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001903 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001904 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1905 arrayBegin, arrayEndPointer,
John McCall7f416cc2015-09-08 08:05:57 +00001906 elementType, elementAlign,
1907 destroyer);
John McCall178360e2011-07-11 08:38:19 +00001908}
1909
1910/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1911/// already-constructed elements of the given array. The cleanup
1912/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001913///
John McCall178360e2011-07-11 08:38:19 +00001914/// \param elementType - the immediate element type of the array;
1915/// possibly still an array type
John McCall178360e2011-07-11 08:38:19 +00001916void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1917 llvm::Value *arrayEnd,
1918 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001919 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001920 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001921 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
John McCall178360e2011-07-11 08:38:19 +00001922 arrayBegin, arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001923 elementType, elementAlign,
1924 destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001925}
1926
Nadav Rotem1da30942013-03-23 06:43:35 +00001927/// Lazily declare the @llvm.lifetime.start intrinsic.
1928llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
Matt Arsenaultd9729492017-04-10 20:18:45 +00001929 if (LifetimeStartFn)
1930 return LifetimeStartFn;
Nadav Rotem1da30942013-03-23 06:43:35 +00001931 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
Yaxun Liu7f7f3232017-04-17 20:03:11 +00001932 llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);
Nadav Rotem1da30942013-03-23 06:43:35 +00001933 return LifetimeStartFn;
1934}
1935
1936/// Lazily declare the @llvm.lifetime.end intrinsic.
1937llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
Matt Arsenaultd9729492017-04-10 20:18:45 +00001938 if (LifetimeEndFn)
1939 return LifetimeEndFn;
Nadav Rotem1da30942013-03-23 06:43:35 +00001940 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
Yaxun Liu7f7f3232017-04-17 20:03:11 +00001941 llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);
Nadav Rotem1da30942013-03-23 06:43:35 +00001942 return LifetimeEndFn;
1943}
1944
John McCall31168b02011-06-15 23:02:42 +00001945namespace {
1946 /// A cleanup to perform a release of an object at the end of a
1947 /// function. This is used to balance out the incoming +1 of a
1948 /// ns_consumed argument when we can't reasonably do that just by
1949 /// not doing the initial retain for a __block argument.
David Blaikie7e70d682015-08-18 22:40:54 +00001950 struct ConsumeARCParameter final : EHScopeStack::Cleanup {
John McCallcdda29c2013-03-13 03:10:54 +00001951 ConsumeARCParameter(llvm::Value *param,
1952 ARCPreciseLifetime_t precise)
1953 : Param(param), Precise(precise) {}
John McCall31168b02011-06-15 23:02:42 +00001954
1955 llvm::Value *Param;
John McCallcdda29c2013-03-13 03:10:54 +00001956 ARCPreciseLifetime_t Precise;
John McCall31168b02011-06-15 23:02:42 +00001957
Craig Topper4f12f102014-03-12 06:41:41 +00001958 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001959 CGF.EmitARCRelease(Param, Precise);
John McCall31168b02011-06-15 23:02:42 +00001960 }
1961 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001962} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00001963
Mike Stump11289f42009-09-09 15:08:12 +00001964/// Emit an alloca (or GlobalValue depending on target)
Chris Lattnerb781dc792008-05-08 05:58:21 +00001965/// for the specified parameter and set up LocalDeclMap.
John McCall7f416cc2015-09-08 08:05:57 +00001966void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
1967 unsigned ArgNo) {
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001968 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Guptad7959242008-10-31 09:52:39 +00001969 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001970 "Invalid argument to EmitParmDecl");
John McCall147d0212011-02-22 22:38:33 +00001971
John McCall7f416cc2015-09-08 08:05:57 +00001972 Arg.getAnyValue()->setName(D.getName());
John McCall147d0212011-02-22 22:38:33 +00001973
Adrian Prantl51936dd2013-03-14 17:53:33 +00001974 QualType Ty = D.getType();
1975
John McCall147d0212011-02-22 22:38:33 +00001976 // Use better IR generation for certain implicit parameters.
John McCall7f416cc2015-09-08 08:05:57 +00001977 if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
John McCall147d0212011-02-22 22:38:33 +00001978 // The only implicit argument a block has is its literal.
Saleem Abdulrasoolc1b46382018-02-21 21:47:51 +00001979 // This may be passed as an inalloca'ed value on Windows x86.
John McCall147d0212011-02-22 22:38:33 +00001980 if (BlockInfo) {
Saleem Abdulrasoolc1b46382018-02-21 21:47:51 +00001981 llvm::Value *V = Arg.isIndirect()
1982 ? Builder.CreateLoad(Arg.getIndirectAddress())
1983 : Arg.getDirectValue();
1984 setBlockContextParameter(IPD, ArgNo, V);
John McCall147d0212011-02-22 22:38:33 +00001985 return;
1986 }
1987 }
1988
John McCall7f416cc2015-09-08 08:05:57 +00001989 Address DeclPtr = Address::invalid();
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001990 bool DoStore = false;
1991 bool IsScalar = hasScalarEvaluationKind(Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001992 // If we already have a pointer to the argument, reuse the input pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001993 if (Arg.isIndirect()) {
1994 DeclPtr = Arg.getIndirectAddress();
Reid Kleckner5e8edba2014-04-02 00:16:53 +00001995 // If we have a prettier pointer type at this point, bitcast to that.
John McCall7f416cc2015-09-08 08:05:57 +00001996 unsigned AS = DeclPtr.getType()->getAddressSpace();
Reid Kleckner5e8edba2014-04-02 00:16:53 +00001997 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
John McCall7f416cc2015-09-08 08:05:57 +00001998 if (DeclPtr.getType() != IRTy)
1999 DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
Yaxun Liu5b330e82018-03-15 15:25:19 +00002000 // Indirect argument is in alloca address space, which may be different
2001 // from the default address space.
2002 auto AllocaAS = CGM.getASTAllocaAddressSpace();
2003 auto *V = DeclPtr.getPointer();
2004 auto SrcLangAS = getLangOpts().OpenCL ? LangAS::opencl_private : AllocaAS;
2005 auto DestLangAS =
2006 getLangOpts().OpenCL ? LangAS::opencl_private : LangAS::Default;
2007 if (SrcLangAS != DestLangAS) {
2008 assert(getContext().getTargetAddressSpace(SrcLangAS) ==
2009 CGM.getDataLayout().getAllocaAddrSpace());
2010 auto DestAS = getContext().getTargetAddressSpace(DestLangAS);
2011 auto *T = V->getType()->getPointerElementType()->getPointerTo(DestAS);
2012 DeclPtr = Address(getTargetHooks().performAddrSpaceCast(
2013 *this, V, SrcLangAS, DestLangAS, T, true),
2014 DeclPtr.getAlignment());
2015 }
John McCall7f416cc2015-09-08 08:05:57 +00002016
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002017 // Push a destructor cleanup for this parameter if the ABI requires it.
Reid Kleckner19819442014-07-25 21:39:46 +00002018 // Don't push a cleanup in a thunk for a method that will also emit a
2019 // cleanup.
Akira Hatanaka85282972018-05-15 21:00:30 +00002020 if (hasAggregateEvaluationKind(Ty) && !CurFuncIsThunk &&
2021 Ty->getAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
Akira Hatanaka7275da02018-02-28 07:15:55 +00002022 if (QualType::DestructionKind DtorKind = Ty.isDestructedType()) {
2023 assert((DtorKind == QualType::DK_cxx_destructor ||
2024 DtorKind == QualType::DK_nontrivial_c_struct) &&
2025 "unexpected destructor type");
2026 pushDestroy(DtorKind, DeclPtr, Ty);
Akira Hatanakaccda3d22018-04-27 06:57:00 +00002027 CalleeDestructedParamCleanups[cast<ParmVarDecl>(&D)] =
2028 EHStack.stable_begin();
Akira Hatanaka7275da02018-02-28 07:15:55 +00002029 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002030 }
Chris Lattner53621a52007-06-13 20:44:40 +00002031 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002032 // Check if the parameter address is controlled by OpenMP runtime.
2033 Address OpenMPLocalAddr =
2034 getLangOpts().OpenMP
2035 ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
2036 : Address::invalid();
2037 if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
2038 DeclPtr = OpenMPLocalAddr;
2039 } else {
2040 // Otherwise, create a temporary to hold the value.
2041 DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
2042 D.getName() + ".addr");
2043 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002044 DoStore = true;
2045 }
Mike Stump11289f42009-09-09 15:08:12 +00002046
John McCall7f416cc2015-09-08 08:05:57 +00002047 llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
2048
2049 LValue lv = MakeAddrLValue(DeclPtr, Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002050 if (IsScalar) {
John McCall31168b02011-06-15 23:02:42 +00002051 Qualifiers qs = Ty.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00002052 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
2053 // We honor __attribute__((ns_consumed)) for types with lifetime.
2054 // For __strong, it's handled by just skipping the initial retain;
2055 // otherwise we have to balance out the initial +1 with an extra
2056 // cleanup to do the release at the end of the function.
2057 bool isConsumed = D.hasAttr<NSConsumedAttr>();
2058
2059 // 'self' is always formally __strong, but if this is not an
2060 // init method then we don't want to retain it.
John McCalld4631322011-06-17 06:42:21 +00002061 if (D.isARCPseudoStrong()) {
John McCall31168b02011-06-15 23:02:42 +00002062 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
2063 assert(&D == method->getSelfDecl());
John McCalld4631322011-06-17 06:42:21 +00002064 assert(lt == Qualifiers::OCL_Strong);
2065 assert(qs.hasConst());
John McCall31168b02011-06-15 23:02:42 +00002066 assert(method->getMethodFamily() != OMF_init);
John McCall10123692011-06-15 23:40:09 +00002067 (void) method;
John McCall31168b02011-06-15 23:02:42 +00002068 lt = Qualifiers::OCL_ExplicitNone;
2069 }
2070
Saleem Abdulrasoolda6784e2017-06-27 18:37:51 +00002071 // Load objects passed indirectly.
2072 if (Arg.isIndirect() && !ArgVal)
2073 ArgVal = Builder.CreateLoad(DeclPtr);
2074
John McCall31168b02011-06-15 23:02:42 +00002075 if (lt == Qualifiers::OCL_Strong) {
Fariborz Jahanian134cec62013-02-21 00:40:10 +00002076 if (!isConsumed) {
2077 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2078 // use objc_storeStrong(&dest, value) for retaining the
2079 // object. But first, store a null into 'dest' because
2080 // objc_storeStrong attempts to release its old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002081 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
Fariborz Jahanian134cec62013-02-21 00:40:10 +00002082 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
John McCall7f416cc2015-09-08 08:05:57 +00002083 EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002084 DoStore = false;
Fariborz Jahanian134cec62013-02-21 00:40:10 +00002085 }
2086 else
John McCall31168b02011-06-15 23:02:42 +00002087 // Don't use objc_retainBlock for block pointers, because we
2088 // don't want to Block_copy something just because we got it
2089 // as a parameter.
John McCall7f416cc2015-09-08 08:05:57 +00002090 ArgVal = EmitARCRetainNonBlock(ArgVal);
Fariborz Jahanian134cec62013-02-21 00:40:10 +00002091 }
John McCall31168b02011-06-15 23:02:42 +00002092 } else {
2093 // Push the cleanup for a consumed parameter.
John McCallcdda29c2013-03-13 03:10:54 +00002094 if (isConsumed) {
2095 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
2096 ? ARCPreciseLifetime : ARCImpreciseLifetime);
John McCall7f416cc2015-09-08 08:05:57 +00002097 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
John McCallcdda29c2013-03-13 03:10:54 +00002098 precise);
2099 }
John McCall31168b02011-06-15 23:02:42 +00002100
2101 if (lt == Qualifiers::OCL_Weak) {
John McCall7f416cc2015-09-08 08:05:57 +00002102 EmitARCInitWeak(DeclPtr, ArgVal);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002103 DoStore = false; // The weak init is a store, no need to do two.
John McCall31168b02011-06-15 23:02:42 +00002104 }
2105 }
2106
2107 // Enter the cleanup scope.
2108 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
2109 }
Chris Lattner53621a52007-06-13 20:44:40 +00002110 }
2111
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002112 // Store the initial value into the alloca.
2113 if (DoStore)
John McCall7f416cc2015-09-08 08:05:57 +00002114 EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002115
John McCall7f416cc2015-09-08 08:05:57 +00002116 setAddrOfLocalVar(&D, DeclPtr);
Sanjiv Gupta18de6242008-05-30 10:30:31 +00002117
2118 // Emit debug info for param declaration.
Alexey Samsonov74a38682012-05-04 07:39:27 +00002119 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00002120 if (CGM.getCodeGenOpts().getDebugInfo() >=
2121 codegenoptions::LimitedDebugInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00002122 DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00002123 }
2124 }
Julien Lerouge5a6b6982011-09-09 22:41:49 +00002125
2126 if (D.hasAttr<AnnotateAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00002127 EmitVarAnnotations(&D, DeclPtr.getPointer());
Vedant Kumar42c17ec2017-03-14 01:56:34 +00002128
2129 // We can only check return value nullability if all arguments to the
2130 // function satisfy their nullability preconditions. This makes it necessary
2131 // to emit null checks for args in the function body itself.
2132 if (requiresReturnValueNullabilityCheck()) {
2133 auto Nullability = Ty->getNullability(getContext());
2134 if (Nullability && *Nullability == NullabilityKind::NonNull) {
2135 SanitizerScope SanScope(this);
2136 RetValNullabilityPrecondition =
2137 Builder.CreateAnd(RetValNullabilityPrecondition,
2138 Builder.CreateIsNotNull(Arg.getAnyValue()));
2139 }
2140 }
Chris Lattner53621a52007-06-13 20:44:40 +00002141}
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002142
Alexey Bataevc5b1d322016-03-04 09:22:22 +00002143void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
2144 CodeGenFunction *CGF) {
2145 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
2146 return;
2147 getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
2148}