blob: 5959d889b45516ca88d65dde236e8f7b00520ae6 [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"
Richard Trieu63688182018-12-11 03:18:39 +000029#include "clang/Basic/CodeGenOptions.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000030#include "clang/Basic/SourceManager.h"
Chris Lattnerb781dc792008-05-08 05:58:21 +000031#include "clang/Basic/TargetInfo.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000032#include "clang/CodeGen/CGFunctionInfo.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:
Kelvin Li1408f912018-09-26 04:28:39 +0000108 case Decl::OMPRequires:
Michael Han84324352013-02-22 17:15:32 +0000109 case Decl::Empty:
Chris Lattner84915fa2007-06-02 04:16:21 +0000110 // None of these decls require codegen support.
111 return;
David Blaikieb7d1e1f2013-02-02 00:39:32 +0000112
David Blaikief121b932013-05-20 22:50:41 +0000113 case Decl::NamespaceAlias:
114 if (CGDebugInfo *DI = getDebugInfo())
Amjad Abouddc4531e2016-04-30 01:44:38 +0000115 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
David Blaikief121b932013-05-20 22:50:41 +0000116 return;
David Blaikiebd483762013-05-20 04:58:53 +0000117 case Decl::Using: // using X; [C++]
118 if (CGDebugInfo *DI = getDebugInfo())
Amjad Abouddc4531e2016-04-30 01:44:38 +0000119 DI->EmitUsingDecl(cast<UsingDecl>(D));
David Blaikiebd483762013-05-20 04:58:53 +0000120 return;
Richard Smith151c4562016-12-20 21:35:28 +0000121 case Decl::UsingPack:
122 for (auto *Using : cast<UsingPackDecl>(D).expansions())
123 EmitDecl(*Using);
124 return;
David Blaikie9f88fe82013-04-22 06:13:21 +0000125 case Decl::UsingDirective: // using namespace X; [C++]
126 if (CGDebugInfo *DI = getDebugInfo())
127 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
128 return;
Richard Smithbdb84f32016-07-22 23:36:59 +0000129 case Decl::Var:
130 case Decl::Decomposition: {
Daniel Dunbara7998072008-08-29 17:28:43 +0000131 const VarDecl &VD = cast<VarDecl>(D);
John McCall1c9c3fd2010-10-15 04:57:14 +0000132 assert(VD.isLocalVarDecl() &&
Daniel Dunbara7998072008-08-29 17:28:43 +0000133 "Should not see file-scope variables inside a function!");
Richard Smithda383632016-08-15 01:33:41 +0000134 EmitVarDecl(VD);
135 if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
136 for (auto *B : DD->bindings())
137 if (auto *HD = B->getHoldingVar())
138 EmitVarDecl(*HD);
139 return;
Chris Lattner84915fa2007-06-02 04:16:21 +0000140 }
Mike Stump11289f42009-09-09 15:08:12 +0000141
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000142 case Decl::OMPDeclareReduction:
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000143 return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000144
Richard Smithdda56e42011-04-15 14:24:37 +0000145 case Decl::Typedef: // typedef int X;
146 case Decl::TypeAlias: { // using X = int; [C++0x]
147 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000148 QualType Ty = TD.getUnderlyingType();
Mike Stump11289f42009-09-09 15:08:12 +0000149
Anders Carlsson5d985f52008-12-20 21:51:53 +0000150 if (Ty->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000151 EmitVariablyModifiedType(Ty);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000152 }
Daniel Dunbara7998072008-08-29 17:28:43 +0000153 }
Chris Lattner84915fa2007-06-02 04:16:21 +0000154}
Chris Lattner03df1222007-06-02 04:53:11 +0000155
John McCall1c9c3fd2010-10-15 04:57:14 +0000156/// EmitVarDecl - This method handles emission of any variable declaration
Chris Lattner03df1222007-06-02 04:53:11 +0000157/// inside a function, including static vars etc.
John McCall1c9c3fd2010-10-15 04:57:14 +0000158void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Yaxun Liu4f33b3d2017-05-15 14:47:47 +0000159 if (D.hasExternalStorage())
160 // Don't emit it now, allow it to be emitted lazily on its first use.
161 return;
162
163 // Some function-scope variable does not have static storage but still
164 // needs to be emitted like a static variable, e.g. a function-scope
165 // variable in constant address space in OpenCL.
166 if (D.getStorageDuration() != SD_Automatic) {
Alexey Baderbed40092017-11-15 11:38:17 +0000167 // Static sampler variables translated to function calls.
168 if (D.getType()->isSamplerT())
169 return;
170
Eric Christopher31ab1302011-08-23 22:38:00 +0000171 llvm::GlobalValue::LinkageTypes Linkage =
David Majnemer27d69db2014-04-28 22:17:59 +0000172 CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000173
David Majnemer27d69db2014-04-28 22:17:59 +0000174 // FIXME: We need to force the emission/use of a guard variable for
175 // some variables even if we can constant-evaluate them because
176 // we can't guarantee every translation unit will constant-evaluate them.
Eric Christopher31ab1302011-08-23 22:38:00 +0000177
John McCall1c9c3fd2010-10-15 04:57:14 +0000178 return EmitStaticVarDecl(D, Linkage);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000179 }
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000180
Anastasia Stulovabcea6962015-09-30 14:08:20 +0000181 if (D.getType().getAddressSpace() == LangAS::opencl_local)
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000182 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
183
184 assert(D.hasLocalStorage());
185 return EmitAutoVarDecl(D);
Chris Lattner03df1222007-06-02 04:53:11 +0000186}
187
Reid Kleckner453e0562014-10-08 01:07:54 +0000188static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
189 if (CGM.getLangOpts().CPlusPlus)
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000190 return CGM.getMangledName(&D).str();
191
Reid Kleckner453e0562014-10-08 01:07:54 +0000192 // If this isn't C++, we don't need a mangled name, just a pretty one.
193 assert(!D.isExternallyVisible() && "name shouldn't matter");
194 std::string ContextName;
195 const DeclContext *DC = D.getDeclContext();
Alexey Bataev43f74392015-05-07 06:28:46 +0000196 if (auto *CD = dyn_cast<CapturedDecl>(DC))
197 DC = cast<DeclContext>(CD->getNonClosureContext());
Reid Kleckner453e0562014-10-08 01:07:54 +0000198 if (const auto *FD = dyn_cast<FunctionDecl>(DC))
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000199 ContextName = CGM.getMangledName(FD);
Reid Kleckner453e0562014-10-08 01:07:54 +0000200 else if (const auto *BD = dyn_cast<BlockDecl>(DC))
201 ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
202 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
203 ContextName = OMD->getSelector().getAsString();
Chris Lattnere99c1102009-12-05 08:22:11 +0000204 else
David Blaikie83d382b2011-09-23 05:06:16 +0000205 llvm_unreachable("Unknown context for static var decl");
Eric Christopher31ab1302011-08-23 22:38:00 +0000206
Reid Kleckner453e0562014-10-08 01:07:54 +0000207 ContextName += "." + D.getNameAsString();
208 return ContextName;
Chris Lattnere99c1102009-12-05 08:22:11 +0000209}
210
Reid Kleckner453e0562014-10-08 01:07:54 +0000211llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
212 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
213 // In general, we don't always emit static var decls once before we reference
214 // them. It is possible to reference them before emitting the function that
215 // contains them, and it is possible to emit the containing function multiple
216 // times.
217 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
218 return ExistingGV;
219
Chris Lattnerfc4379f2008-04-06 23:10:54 +0000220 QualType Ty = D.getType();
Eli Friedmana682d392008-02-15 12:20:59 +0000221 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begemanfaae0812008-04-19 04:17:09 +0000222
Benjamin Kramerddbb2b82011-11-20 21:05:04 +0000223 // Use the label if the variable is renamed with the asm-label extension.
224 std::string Name;
Benjamin Kramer5642e192011-11-21 15:47:23 +0000225 if (D.hasAttr<AsmLabelAttr>())
Reid Kleckner453e0562014-10-08 01:07:54 +0000226 Name = getMangledName(&D);
Benjamin Kramer5642e192011-11-21 15:47:23 +0000227 else
Reid Kleckner453e0562014-10-08 01:07:54 +0000228 Name = getStaticDeclName(*this, D);
Nate Begemanfaae0812008-04-19 04:17:09 +0000229
Reid Kleckner453e0562014-10-08 01:07:54 +0000230 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
Alexander Richardson6d989432017-10-15 18:48:14 +0000231 LangAS AS = GetGlobalVarAddressSpace(&D);
Yaxun Liucbf647c2017-07-08 13:24:52 +0000232 unsigned TargetAS = getContext().getTargetAddressSpace(AS);
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000233
Yaxun Liua64a4912018-04-02 17:38:24 +0000234 // OpenCL variables in local address space and CUDA shared
235 // variables cannot have an initializer.
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000236 llvm::Constant *Init = nullptr;
Yaxun Liua64a4912018-04-02 17:38:24 +0000237 if (Ty.getAddressSpace() == LangAS::opencl_local ||
238 D.hasAttr<CUDASharedAttr>())
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000239 Init = llvm::UndefValue::get(LTy);
Yaxun Liua64a4912018-04-02 17:38:24 +0000240 else
241 Init = EmitNullConstant(Ty);
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000242
Yaxun Liucbf647c2017-07-08 13:24:52 +0000243 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
244 getModule(), LTy, Ty.isConstant(getContext()), Linkage, Init, Name,
245 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
Ken Dyck160146e2010-01-27 17:10:57 +0000246 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000247
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +0000248 if (supportsCOMDAT() && GV->isWeakForLinker())
249 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Rafael Espindola0d4fb982015-01-12 22:13:53 +0000250
Richard Smithfd3834f2013-04-13 02:43:54 +0000251 if (D.getTLSKind())
Reid Kleckner453e0562014-10-08 01:07:54 +0000252 setTLSMode(GV, D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000253
Rafael Espindola922f2aa2018-02-23 19:30:48 +0000254 setGVProperties(GV, &D);
255
Eli Benderskycb399432014-03-24 22:05:38 +0000256 // Make sure the result is of the correct type.
Alexander Richardson6d989432017-10-15 18:48:14 +0000257 LangAS ExpectedAS = Ty.getAddressSpace();
Reid Kleckner453e0562014-10-08 01:07:54 +0000258 llvm::Constant *Addr = GV;
Yaxun Liucbf647c2017-07-08 13:24:52 +0000259 if (AS != ExpectedAS) {
260 Addr = getTargetCodeGenInfo().performAddrSpaceCast(
261 *this, GV, AS, ExpectedAS,
262 LTy->getPointerTo(getContext().getTargetAddressSpace(ExpectedAS)));
Eli Benderskycb399432014-03-24 22:05:38 +0000263 }
264
Reid Kleckner453e0562014-10-08 01:07:54 +0000265 setStaticLocalDeclAddress(&D, Addr);
266
267 // Ensure that the static local gets initialized by making sure the parent
268 // function gets emitted eventually.
269 const Decl *DC = cast<Decl>(D.getDeclContext());
270
271 // We can't name blocks or captured statements directly, so try to emit their
272 // parents.
273 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
274 DC = DC->getNonClosureContext();
275 // FIXME: Ensure that global blocks get emitted.
276 if (!DC)
277 return Addr;
278 }
279
280 GlobalDecl GD;
281 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
282 GD = GlobalDecl(CD, Ctor_Base);
283 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
284 GD = GlobalDecl(DD, Dtor_Base);
285 else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
286 GD = GlobalDecl(FD);
287 else {
288 // Don't do anything for Obj-C method decls or global closures. We should
289 // never defer them.
290 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
291 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +0000292 if (GD.getDecl()) {
293 // Disable emission of the parent function for the OpenMP device codegen.
294 CGOpenMPRuntime::DisableAutoDeclareTargetRAII NoDeclTarget(*this);
Reid Kleckner453e0562014-10-08 01:07:54 +0000295 (void)GetAddrOfGlobal(GD);
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +0000296 }
Reid Kleckner453e0562014-10-08 01:07:54 +0000297
298 return Addr;
Daniel Dunbar22a87f92009-02-25 19:24:29 +0000299}
300
Richard Smith6331c402012-02-13 22:16:19 +0000301/// hasNontrivialDestruction - Determine whether a type's destruction is
302/// non-trivial. If so, and the variable uses static initialization, we must
303/// register its destructor to run on exit.
304static bool hasNontrivialDestruction(QualType T) {
305 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
306 return RD && !RD->hasTrivialDestructor();
307}
308
Chandler Carruth84537952012-03-30 19:44:53 +0000309/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
310/// global variable that has already been created for it. If the initializer
311/// has a different type than GV does, this may free GV and return a different
312/// one. Otherwise it just returns GV.
313llvm::GlobalVariable *
John McCall1c9c3fd2010-10-15 04:57:14 +0000314CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
Chandler Carruth84537952012-03-30 19:44:53 +0000315 llvm::GlobalVariable *GV) {
John McCallde0fe072017-08-15 21:42:52 +0000316 ConstantEmitter emitter(*this);
317 llvm::Constant *Init = emitter.tryEmitForInitializer(D);
John McCall70013b62010-07-15 23:40:35 +0000318
Chris Lattnere99c1102009-12-05 08:22:11 +0000319 // If constant emission failed, then this should be a C++ static
320 // initializer.
Chandler Carruth84537952012-03-30 19:44:53 +0000321 if (!Init) {
Richard Smith9c6890a2012-11-01 22:30:59 +0000322 if (!getLangOpts().CPlusPlus)
Chris Lattnere99c1102009-12-05 08:22:11 +0000323 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
Matthias Braun44bfe032017-01-10 17:43:01 +0000324 else if (HaveInsertPoint()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000325 // Since we have a static initializer, this global variable can't
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000326 // be constant.
Chandler Carruth84537952012-03-30 19:44:53 +0000327 GV->setConstant(false);
John McCall68ff0372010-09-08 01:44:27 +0000328
Chandler Carruth84537952012-03-30 19:44:53 +0000329 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000330 }
Chandler Carruth84537952012-03-30 19:44:53 +0000331 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000332 }
John McCall70013b62010-07-15 23:40:35 +0000333
Chris Lattnere99c1102009-12-05 08:22:11 +0000334 // The initializer may differ in type from the global. Rewrite
335 // the global to match the initializer. (We have to do this
336 // because some types, like unions, can't be completely represented
337 // in the LLVM type system.)
Chandler Carruth84537952012-03-30 19:44:53 +0000338 if (GV->getType()->getElementType() != Init->getType()) {
339 llvm::GlobalVariable *OldGV = GV;
340
341 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
342 OldGV->isConstant(),
343 OldGV->getLinkage(), Init, "",
344 /*InsertBefore*/ OldGV,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +0000345 OldGV->getThreadLocalMode(),
Chandler Carruth84537952012-03-30 19:44:53 +0000346 CGM.getContext().getTargetAddressSpace(D.getType()));
347 GV->setVisibility(OldGV->getVisibility());
Rafael Espindola699f5d62018-02-07 22:15:33 +0000348 GV->setDSOLocal(OldGV->isDSOLocal());
Reid Klecknereab97d32015-07-20 20:35:30 +0000349 GV->setComdat(OldGV->getComdat());
Eric Christopher31ab1302011-08-23 22:38:00 +0000350
Chris Lattnere99c1102009-12-05 08:22:11 +0000351 // Steal the name of the old global
Chandler Carruth84537952012-03-30 19:44:53 +0000352 GV->takeName(OldGV);
Eric Christopher31ab1302011-08-23 22:38:00 +0000353
Chris Lattnere99c1102009-12-05 08:22:11 +0000354 // Replace all uses of the old global with the new global
Chandler Carruth84537952012-03-30 19:44:53 +0000355 llvm::Constant *NewPtrForOldDecl =
356 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
357 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eric Christopher31ab1302011-08-23 22:38:00 +0000358
Chris Lattnere99c1102009-12-05 08:22:11 +0000359 // Erase the old global, since it is no longer used.
Chandler Carruth84537952012-03-30 19:44:53 +0000360 OldGV->eraseFromParent();
Chris Lattnere99c1102009-12-05 08:22:11 +0000361 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000362
Chandler Carruth84537952012-03-30 19:44:53 +0000363 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
364 GV->setInitializer(Init);
Richard Smith6331c402012-02-13 22:16:19 +0000365
John McCallde0fe072017-08-15 21:42:52 +0000366 emitter.finalize(GV);
367
Matthias Braun44bfe032017-01-10 17:43:01 +0000368 if (hasNontrivialDestruction(D.getType()) && HaveInsertPoint()) {
Richard Smith6331c402012-02-13 22:16:19 +0000369 // We have a constant initializer, but a nontrivial destructor. We still
370 // need to perform a guarded "initialization" in order to register the
Richard Smithe070fd22012-02-17 06:48:11 +0000371 // destructor.
Chandler Carruth84537952012-03-30 19:44:53 +0000372 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
Richard Smith6331c402012-02-13 22:16:19 +0000373 }
374
Chandler Carruth84537952012-03-30 19:44:53 +0000375 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000376}
377
John McCall1c9c3fd2010-10-15 04:57:14 +0000378void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000379 llvm::GlobalValue::LinkageTypes Linkage) {
John McCallb88a5662012-03-30 21:00:39 +0000380 // Check to see if we already have a global variable for this
381 // declaration. This can happen when double-emitting function
382 // bodies, e.g. with complete and base constructors.
Reid Kleckner453e0562014-10-08 01:07:54 +0000383 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
John McCall7f416cc2015-09-08 08:05:57 +0000384 CharUnits alignment = getContext().getDeclAlign(&D);
Daniel Dunbara374e602009-02-25 19:45:19 +0000385
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000386 // Store into LocalDeclMap before generating initializer to handle
387 // circular references.
John McCall7f416cc2015-09-08 08:05:57 +0000388 setAddrOfLocalVar(&D, Address(addr, alignment));
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000389
John McCall4a39ab82010-05-04 20:45:42 +0000390 // We can't have a VLA here, but we can have a pointer to a VLA,
391 // even though that doesn't really make any sense.
Eli Friedmanbc633be2009-04-20 03:54:15 +0000392 // Make sure to evaluate VLA bounds now so that we have them for later.
393 if (D.getType()->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000394 EmitVariablyModifiedType(D.getType());
Eric Christopher31ab1302011-08-23 22:38:00 +0000395
John McCallb88a5662012-03-30 21:00:39 +0000396 // Save the type in case adding the initializer forces a type change.
397 llvm::Type *expectedType = addr->getType();
Eli Friedmanbc633be2009-04-20 03:54:15 +0000398
Eli Benderskycb399432014-03-24 22:05:38 +0000399 llvm::GlobalVariable *var =
400 cast<llvm::GlobalVariable>(addr->stripPointerCasts());
Artem Belevich4d430ba2016-05-09 22:09:56 +0000401
402 // CUDA's local and local static __shared__ variables should not
403 // have any non-empty initializers. This is ensured by Sema.
404 // Whatever initializer such variable may have when it gets here is
405 // a no-op and should not be emitted.
406 bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
407 D.hasAttr<CUDASharedAttr>();
Chris Lattnere99c1102009-12-05 08:22:11 +0000408 // If this value has an initializer, emit it.
Artem Belevich4d430ba2016-05-09 22:09:56 +0000409 if (D.getInit() && !isCudaSharedVar)
John McCallb88a5662012-03-30 21:00:39 +0000410 var = AddInitializerToStaticVarDecl(D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000411
John McCall7f416cc2015-09-08 08:05:57 +0000412 var->setAlignment(alignment.getQuantity());
Chris Lattner4d941092010-03-10 23:59:59 +0000413
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000414 if (D.hasAttr<AnnotateAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000415 CGM.AddGlobalAnnotations(&D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000416
Javed Absar2a67c9e2017-06-05 10:11:57 +0000417 if (auto *SA = D.getAttr<PragmaClangBSSSectionAttr>())
418 var->addAttribute("bss-section", SA->getName());
419 if (auto *SA = D.getAttr<PragmaClangDataSectionAttr>())
420 var->addAttribute("data-section", SA->getName());
421 if (auto *SA = D.getAttr<PragmaClangRodataSectionAttr>())
422 var->addAttribute("rodata-section", SA->getName());
423
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000424 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000425 var->setSection(SA->getName());
Mike Stump11289f42009-09-09 15:08:12 +0000426
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000427 if (D.hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +0000428 CGM.addUsedGlobal(var);
Daniel Dunbar128a1382009-02-13 22:08:43 +0000429
Chandler Carruth84537952012-03-30 19:44:53 +0000430 // We may have to cast the constant because of the initializer
431 // mismatch above.
432 //
433 // FIXME: It is really dangerous to store this in the map; if anyone
434 // RAUW's the GV uses of this constant will be invalid.
Eli Benderskycb399432014-03-24 22:05:38 +0000435 llvm::Constant *castedAddr =
436 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
John McCall7f416cc2015-09-08 08:05:57 +0000437 if (var != castedAddr)
438 LocalDeclMap.find(&D)->second = Address(castedAddr, alignment);
John McCallb88a5662012-03-30 21:00:39 +0000439 CGM.setStaticLocalDeclAddress(&D, castedAddr);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000440
Alexey Samsonov4b8de112014-08-01 21:35:28 +0000441 CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000442
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000443 // Emit global variable debug descriptor for static vars.
Anders Carlsson63784f42009-02-13 08:11:52 +0000444 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov74a38682012-05-04 07:39:27 +0000445 if (DI &&
Benjamin Kramer8c305922016-02-02 11:06:51 +0000446 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
Daniel Dunbarb9fd9022008-10-17 16:15:48 +0000447 DI->setLocation(D.getLocation());
John McCallb88a5662012-03-30 21:00:39 +0000448 DI->EmitGlobalVariable(var, &D);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000449 }
Anders Carlssonf94cd1f2007-10-17 00:52:43 +0000450}
Mike Stump11289f42009-09-09 15:08:12 +0000451
John McCall2b7fc382010-07-13 20:32:21 +0000452namespace {
David Blaikie7e70d682015-08-18 22:40:54 +0000453 struct DestroyObject final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000454 DestroyObject(Address addr, QualType type,
John McCall178360e2011-07-11 08:38:19 +0000455 CodeGenFunction::Destroyer *destroyer,
456 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +0000457 : addr(addr), type(type), destroyer(destroyer),
John McCall178360e2011-07-11 08:38:19 +0000458 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall2b7fc382010-07-13 20:32:21 +0000459
John McCall7f416cc2015-09-08 08:05:57 +0000460 Address addr;
John McCall82fe67b2011-07-09 01:37:26 +0000461 QualType type;
Peter Collingbourne1425b452012-01-26 03:33:36 +0000462 CodeGenFunction::Destroyer *destroyer;
John McCall178360e2011-07-11 08:38:19 +0000463 bool useEHCleanupForArray;
John McCall2b7fc382010-07-13 20:32:21 +0000464
Craig Topper4f12f102014-03-12 06:41:41 +0000465 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +0000466 // Don't use an EH cleanup recursively from an EH cleanup.
John McCall30317fd2011-07-12 20:27:29 +0000467 bool useEHCleanupForArray =
468 flags.isForNormalCleanup() && this->useEHCleanupForArray;
John McCall178360e2011-07-11 08:38:19 +0000469
470 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
John McCall2b7fc382010-07-13 20:32:21 +0000471 }
472 };
473
Akira Hatanaka673af7a2018-03-29 17:56:24 +0000474 template <class Derived>
475 struct DestroyNRVOVariable : EHScopeStack::Cleanup {
476 DestroyNRVOVariable(Address addr, llvm::Value *NRVOFlag)
477 : NRVOFlag(NRVOFlag), Loc(addr) {}
John McCall2b7fc382010-07-13 20:32:21 +0000478
John McCall2b7fc382010-07-13 20:32:21 +0000479 llvm::Value *NRVOFlag;
John McCall7f416cc2015-09-08 08:05:57 +0000480 Address Loc;
John McCall2b7fc382010-07-13 20:32:21 +0000481
Craig Topper4f12f102014-03-12 06:41:41 +0000482 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall2b7fc382010-07-13 20:32:21 +0000483 // Along the exceptions path we always execute the dtor.
John McCall30317fd2011-07-12 20:27:29 +0000484 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
John McCall2b7fc382010-07-13 20:32:21 +0000485
Craig Topper8a13c412014-05-21 05:09:00 +0000486 llvm::BasicBlock *SkipDtorBB = nullptr;
John McCall2b7fc382010-07-13 20:32:21 +0000487 if (NRVO) {
488 // If we exited via NRVO, we skip the destructor call.
489 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
490 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
John McCall7f416cc2015-09-08 08:05:57 +0000491 llvm::Value *DidNRVO =
492 CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
John McCall2b7fc382010-07-13 20:32:21 +0000493 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
494 CGF.EmitBlock(RunDtorBB);
495 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000496
Akira Hatanaka673af7a2018-03-29 17:56:24 +0000497 static_cast<Derived *>(this)->emitDestructorCall(CGF);
John McCall2b7fc382010-07-13 20:32:21 +0000498
499 if (NRVO) CGF.EmitBlock(SkipDtorBB);
500 }
Akira Hatanaka673af7a2018-03-29 17:56:24 +0000501
502 virtual ~DestroyNRVOVariable() = default;
503 };
504
505 struct DestroyNRVOVariableCXX final
506 : DestroyNRVOVariable<DestroyNRVOVariableCXX> {
507 DestroyNRVOVariableCXX(Address addr, const CXXDestructorDecl *Dtor,
508 llvm::Value *NRVOFlag)
509 : DestroyNRVOVariable<DestroyNRVOVariableCXX>(addr, NRVOFlag),
510 Dtor(Dtor) {}
511
512 const CXXDestructorDecl *Dtor;
513
514 void emitDestructorCall(CodeGenFunction &CGF) {
515 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
516 /*ForVirtualBase=*/false,
517 /*Delegating=*/false, Loc);
518 }
519 };
520
521 struct DestroyNRVOVariableC final
522 : DestroyNRVOVariable<DestroyNRVOVariableC> {
523 DestroyNRVOVariableC(Address addr, llvm::Value *NRVOFlag, QualType Ty)
524 : DestroyNRVOVariable<DestroyNRVOVariableC>(addr, NRVOFlag), Ty(Ty) {}
525
526 QualType Ty;
527
528 void emitDestructorCall(CodeGenFunction &CGF) {
529 CGF.destroyNonTrivialCStruct(CGF, Loc, Ty);
530 }
John McCall2b7fc382010-07-13 20:32:21 +0000531 };
John McCall2b7fc382010-07-13 20:32:21 +0000532
David Blaikie7e70d682015-08-18 22:40:54 +0000533 struct CallStackRestore final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000534 Address Stack;
535 CallStackRestore(Address Stack) : Stack(Stack) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000536 void Emit(CodeGenFunction &CGF, Flags flags) override {
Benjamin Kramer76399eb2011-09-27 21:06:10 +0000537 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
John McCalla464ff92010-07-21 06:13:08 +0000538 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
539 CGF.Builder.CreateCall(F, V);
540 }
541 };
542
David Blaikie7e70d682015-08-18 22:40:54 +0000543 struct ExtendGCLifetime final : EHScopeStack::Cleanup {
John McCall1bd25562011-06-24 23:21:27 +0000544 const VarDecl &Var;
545 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
546
Craig Topper4f12f102014-03-12 06:41:41 +0000547 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1bd25562011-06-24 23:21:27 +0000548 // Compute the address of the local variable, in case it's a
549 // byref or something.
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000550 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
John McCall113bee02012-03-10 09:33:50 +0000551 Var.getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +0000552 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
553 SourceLocation());
John McCall1bd25562011-06-24 23:21:27 +0000554 CGF.EmitExtendGCLifetime(value);
555 }
556 };
557
David Blaikie7e70d682015-08-18 22:40:54 +0000558 struct CallCleanupFunction final : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000559 llvm::Constant *CleanupFn;
560 const CGFunctionInfo &FnInfo;
John McCalla464ff92010-07-21 06:13:08 +0000561 const VarDecl &Var;
Eric Christopher31ab1302011-08-23 22:38:00 +0000562
John McCalla464ff92010-07-21 06:13:08 +0000563 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCallc533cb72011-02-22 06:44:22 +0000564 const VarDecl *Var)
565 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalla464ff92010-07-21 06:13:08 +0000566
Craig Topper4f12f102014-03-12 06:41:41 +0000567 void Emit(CodeGenFunction &CGF, Flags flags) override {
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000568 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
John McCall113bee02012-03-10 09:33:50 +0000569 Var.getType(), VK_LValue, SourceLocation());
John McCallc533cb72011-02-22 06:44:22 +0000570 // Compute the address of the local variable, in case it's a byref
571 // or something.
John McCall7f416cc2015-09-08 08:05:57 +0000572 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer();
John McCallc533cb72011-02-22 06:44:22 +0000573
John McCalla464ff92010-07-21 06:13:08 +0000574 // In some cases, the type of the function argument will be different from
575 // the type of the pointer. An example of this is
576 // void f(void* arg);
577 // __attribute__((cleanup(f))) void *g;
578 //
579 // To fix this we insert a bitcast here.
580 QualType ArgTy = FnInfo.arg_begin()->type;
581 llvm::Value *Arg =
582 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
583
584 CallArgList Args;
Eli Friedman43dca6a2011-05-02 17:57:46 +0000585 Args.add(RValue::get(Arg),
586 CGF.getContext().getPointerType(Var.getType()));
John McCallb92ab1a2016-10-26 23:46:34 +0000587 auto Callee = CGCallee::forDirect(CleanupFn);
588 CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
John McCalla464ff92010-07-21 06:13:08 +0000589 }
590 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000591} // end anonymous namespace
John McCalla464ff92010-07-21 06:13:08 +0000592
John McCall31168b02011-06-15 23:02:42 +0000593/// EmitAutoVarWithLifetime - Does the setup required for an automatic
594/// variable with lifetime.
595static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
John McCall7f416cc2015-09-08 08:05:57 +0000596 Address addr,
John McCall31168b02011-06-15 23:02:42 +0000597 Qualifiers::ObjCLifetime lifetime) {
598 switch (lifetime) {
599 case Qualifiers::OCL_None:
600 llvm_unreachable("present but none");
601
602 case Qualifiers::OCL_ExplicitNone:
603 // nothing to do
604 break;
605
606 case Qualifiers::OCL_Strong: {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000607 CodeGenFunction::Destroyer *destroyer =
John McCall4bd0fb12011-07-12 16:41:08 +0000608 (var.hasAttr<ObjCPreciseLifetimeAttr>()
609 ? CodeGenFunction::destroyARCStrongPrecise
610 : CodeGenFunction::destroyARCStrongImprecise);
611
612 CleanupKind cleanupKind = CGF.getARCCleanupKind();
613 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
614 cleanupKind & EHCleanup);
John McCall31168b02011-06-15 23:02:42 +0000615 break;
616 }
617 case Qualifiers::OCL_Autoreleasing:
618 // nothing to do
619 break;
Eric Christopher31ab1302011-08-23 22:38:00 +0000620
John McCall31168b02011-06-15 23:02:42 +0000621 case Qualifiers::OCL_Weak:
622 // __weak objects always get EH cleanups; otherwise, exceptions
623 // could cause really nasty crashes instead of mere leaks.
John McCall4bd0fb12011-07-12 16:41:08 +0000624 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
625 CodeGenFunction::destroyARCWeak,
626 /*useEHCleanup*/ true);
John McCall31168b02011-06-15 23:02:42 +0000627 break;
628 }
629}
630
631static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
632 if (const Expr *e = dyn_cast<Expr>(s)) {
633 // Skip the most common kinds of expressions that make
634 // hierarchy-walking expensive.
635 s = e = e->IgnoreParenCasts();
636
637 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
638 return (ref->getDecl() == &var);
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000639 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
640 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +0000641 for (const auto &I : block->captures()) {
642 if (I.getVariable() == &var)
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000643 return true;
644 }
645 }
John McCall31168b02011-06-15 23:02:42 +0000646 }
647
Benjamin Kramer642f1732015-07-02 21:03:14 +0000648 for (const Stmt *SubStmt : s->children())
649 // SubStmt might be null; as in missing decl or conditional of an if-stmt.
650 if (SubStmt && isAccessedBy(var, SubStmt))
John McCall31168b02011-06-15 23:02:42 +0000651 return true;
652
653 return false;
654}
655
656static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
657 if (!decl) return false;
658 if (!isa<VarDecl>(decl)) return false;
659 const VarDecl *var = cast<VarDecl>(decl);
660 return isAccessedBy(*var, e);
661}
662
John McCallf8a9b662015-10-21 18:06:31 +0000663static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
664 const LValue &destLV, const Expr *init) {
John McCall0204e342015-11-16 22:11:41 +0000665 bool needsCast = false;
666
John McCallf8a9b662015-10-21 18:06:31 +0000667 while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
668 switch (castExpr->getCastKind()) {
669 // Look through casts that don't require representation changes.
670 case CK_NoOp:
671 case CK_BitCast:
672 case CK_BlockPointerToObjCPointerCast:
John McCall0204e342015-11-16 22:11:41 +0000673 needsCast = true;
John McCallf8a9b662015-10-21 18:06:31 +0000674 break;
675
676 // If we find an l-value to r-value cast from a __weak variable,
677 // emit this operation as a copy or move.
678 case CK_LValueToRValue: {
679 const Expr *srcExpr = castExpr->getSubExpr();
680 if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
681 return false;
682
683 // Emit the source l-value.
684 LValue srcLV = CGF.EmitLValue(srcExpr);
685
John McCall0204e342015-11-16 22:11:41 +0000686 // Handle a formal type change to avoid asserting.
687 auto srcAddr = srcLV.getAddress();
688 if (needsCast) {
689 srcAddr = CGF.Builder.CreateElementBitCast(srcAddr,
690 destLV.getAddress().getElementType());
691 }
692
John McCallf8a9b662015-10-21 18:06:31 +0000693 // If it was an l-value, use objc_copyWeak.
694 if (srcExpr->getValueKind() == VK_LValue) {
John McCall0204e342015-11-16 22:11:41 +0000695 CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr);
John McCallf8a9b662015-10-21 18:06:31 +0000696 } else {
697 assert(srcExpr->getValueKind() == VK_XValue);
John McCall0204e342015-11-16 22:11:41 +0000698 CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr);
John McCallf8a9b662015-10-21 18:06:31 +0000699 }
700 return true;
701 }
702
703 // Stop at anything else.
704 default:
705 return false;
706 }
707
708 init = castExpr->getSubExpr();
John McCallf8a9b662015-10-21 18:06:31 +0000709 }
710 return false;
711}
712
John McCall1553b192011-06-16 04:16:24 +0000713static void drillIntoBlockVariable(CodeGenFunction &CGF,
714 LValue &lvalue,
715 const VarDecl *var) {
John McCall7f416cc2015-09-08 08:05:57 +0000716 lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var));
John McCall1553b192011-06-16 04:16:24 +0000717}
718
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000719void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS,
720 SourceLocation Loc) {
721 if (!SanOpts.has(SanitizerKind::NullabilityAssign))
722 return;
723
724 auto Nullability = LHS.getType()->getNullability(getContext());
725 if (!Nullability || *Nullability != NullabilityKind::NonNull)
726 return;
727
728 // Check if the right hand side of the assignment is nonnull, if the left
729 // hand side must be nonnull.
730 SanitizerScope SanScope(this);
731 llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS);
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000732 llvm::Constant *StaticData[] = {
733 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(LHS.getType()),
Simon Pilgrim2df19982017-03-14 21:43:52 +0000734 llvm::ConstantInt::get(Int8Ty, 0), // The LogAlignment info is unused.
Vedant Kumar2b9f48a2017-03-14 16:48:29 +0000735 llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)};
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000736 EmitCheck({{IsNotNull, SanitizerKind::NullabilityAssign}},
737 SanitizerHandler::TypeMismatch, StaticData, RHS);
738}
739
David Blaikie73ca5692014-12-09 00:32:22 +0000740void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +0000741 LValue lvalue, bool capturedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000742 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +0000743 if (!lifetime) {
744 llvm::Value *value = EmitScalarExpr(init);
John McCall1553b192011-06-16 04:16:24 +0000745 if (capturedByInit)
746 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000747 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
David Blaikie66e41972015-01-14 07:38:27 +0000748 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
John McCall31168b02011-06-15 23:02:42 +0000749 return;
750 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000751
Fariborz Jahaniana5a469e2014-03-14 15:40:54 +0000752 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
753 init = DIE->getExpr();
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000754
John McCall31168b02011-06-15 23:02:42 +0000755 // If we're emitting a value with lifetime, we have to do the
756 // initialization *before* we leave the cleanup scopes.
Bill Wendling7c44da22018-10-31 03:48:47 +0000757 if (const FullExpr *fe = dyn_cast<FullExpr>(init)) {
758 enterFullExpression(fe);
759 init = fe->getSubExpr();
John McCall08ef4662011-11-10 08:15:53 +0000760 }
761 CodeGenFunction::RunCleanupsScope Scope(*this);
John McCall31168b02011-06-15 23:02:42 +0000762
763 // We have to maintain the illusion that the variable is
764 // zero-initialized. If the variable might be accessed in its
765 // initializer, zero-initialize before running the initializer, then
766 // actually perform the initialization with an assign.
767 bool accessedByInit = false;
768 if (lifetime != Qualifiers::OCL_ExplicitNone)
John McCallb726a552011-07-28 07:23:35 +0000769 accessedByInit = (capturedByInit || isAccessedBy(D, init));
John McCall31168b02011-06-15 23:02:42 +0000770 if (accessedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000771 LValue tempLV = lvalue;
John McCall31168b02011-06-15 23:02:42 +0000772 // Drill down to the __block object if necessary.
John McCall31168b02011-06-15 23:02:42 +0000773 if (capturedByInit) {
774 // We can use a simple GEP for this because it can't have been
775 // moved yet.
John McCall7f416cc2015-09-08 08:05:57 +0000776 tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(),
777 cast<VarDecl>(D),
778 /*follow*/ false));
John McCall31168b02011-06-15 23:02:42 +0000779 }
780
John McCall7f416cc2015-09-08 08:05:57 +0000781 auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType());
Yaxun Liu402804b2016-12-15 08:09:08 +0000782 llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());
Eric Christopher31ab1302011-08-23 22:38:00 +0000783
John McCall31168b02011-06-15 23:02:42 +0000784 // If __weak, we want to use a barrier under certain conditions.
785 if (lifetime == Qualifiers::OCL_Weak)
John McCall1553b192011-06-16 04:16:24 +0000786 EmitARCInitWeak(tempLV.getAddress(), zero);
John McCall31168b02011-06-15 23:02:42 +0000787
788 // Otherwise just do a simple store.
789 else
David Chisnallfa35df62012-01-16 17:27:18 +0000790 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000791 }
792
793 // Emit the initializer.
Craig Topper8a13c412014-05-21 05:09:00 +0000794 llvm::Value *value = nullptr;
John McCall31168b02011-06-15 23:02:42 +0000795
796 switch (lifetime) {
797 case Qualifiers::OCL_None:
798 llvm_unreachable("present but none");
799
Erik Pilkington1e368822019-01-04 18:33:06 +0000800 case Qualifiers::OCL_Strong: {
801 if (!D || !isa<VarDecl>(D) || !cast<VarDecl>(D)->isARCPseudoStrong()) {
802 value = EmitARCRetainScalarExpr(init);
803 break;
804 }
805 // If D is pseudo-strong, treat it like __unsafe_unretained here. This means
806 // that we omit the retain, and causes non-autoreleased return values to be
807 // immediately released.
808 LLVM_FALLTHROUGH;
809 }
810
John McCall31168b02011-06-15 23:02:42 +0000811 case Qualifiers::OCL_ExplicitNone:
John McCalle399e5b2016-01-27 18:32:30 +0000812 value = EmitARCUnsafeUnretainedScalarExpr(init);
John McCall31168b02011-06-15 23:02:42 +0000813 break;
814
John McCall31168b02011-06-15 23:02:42 +0000815 case Qualifiers::OCL_Weak: {
John McCallf8a9b662015-10-21 18:06:31 +0000816 // If it's not accessed by the initializer, try to emit the
817 // initialization with a copy or move.
818 if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
819 return;
820 }
821
John McCall31168b02011-06-15 23:02:42 +0000822 // No way to optimize a producing initializer into this. It's not
823 // worth optimizing for, because the value will immediately
824 // disappear in the common case.
825 value = EmitScalarExpr(init);
826
John McCall1553b192011-06-16 04:16:24 +0000827 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000828 if (accessedByInit)
John McCall1553b192011-06-16 04:16:24 +0000829 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +0000830 else
John McCall1553b192011-06-16 04:16:24 +0000831 EmitARCInitWeak(lvalue.getAddress(), value);
John McCall31168b02011-06-15 23:02:42 +0000832 return;
833 }
834
835 case Qualifiers::OCL_Autoreleasing:
836 value = EmitARCRetainAutoreleaseScalarExpr(init);
837 break;
838 }
839
John McCall1553b192011-06-16 04:16:24 +0000840 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000841
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000842 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
843
John McCall31168b02011-06-15 23:02:42 +0000844 // If the variable might have been accessed by its initializer, we
845 // might have to initialize with a barrier. We have to do this for
846 // both __weak and __strong, but __weak got filtered out above.
847 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000848 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
David Chisnallfa35df62012-01-16 17:27:18 +0000849 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCallcdda29c2013-03-13 03:10:54 +0000850 EmitARCRelease(oldValue, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +0000851 return;
852 }
853
David Chisnallfa35df62012-01-16 17:27:18 +0000854 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000855}
Chris Lattnerb85025f2010-12-01 02:05:19 +0000856
JF Bastiened92f602018-07-20 23:37:12 +0000857/// Decide whether we can emit the non-zero parts of the specified initializer
858/// with equal or fewer than NumStores scalar stores.
859static bool canEmitInitWithFewStoresAfterBZero(llvm::Constant *Init,
860 unsigned &NumStores) {
Chris Lattnere6af8862010-12-02 01:58:41 +0000861 // Zero and Undef never requires any extra stores.
862 if (isa<llvm::ConstantAggregateZero>(Init) ||
863 isa<llvm::ConstantPointerNull>(Init) ||
864 isa<llvm::UndefValue>(Init))
865 return true;
866 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
867 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
868 isa<llvm::ConstantExpr>(Init))
869 return Init->isNullValue() || NumStores--;
870
871 // See if we can emit each element.
872 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
873 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
874 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
JF Bastiened92f602018-07-20 23:37:12 +0000875 if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
Chris Lattnere6af8862010-12-02 01:58:41 +0000876 return false;
877 }
878 return true;
879 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000880
Chris Lattner236b3572012-01-31 04:36:19 +0000881 if (llvm::ConstantDataSequential *CDS =
882 dyn_cast<llvm::ConstantDataSequential>(Init)) {
883 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
884 llvm::Constant *Elt = CDS->getElementAsConstant(i);
JF Bastiened92f602018-07-20 23:37:12 +0000885 if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
Chris Lattner236b3572012-01-31 04:36:19 +0000886 return false;
887 }
888 return true;
889 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000890
Chris Lattnerb85025f2010-12-01 02:05:19 +0000891 // Anything else is hard and scary.
892 return false;
893}
894
JF Bastiened92f602018-07-20 23:37:12 +0000895/// For inits that canEmitInitWithFewStoresAfterBZero returned true for, emit
896/// the scalar stores that would be required.
897static void emitStoresForInitAfterBZero(CodeGenModule &CGM,
898 llvm::Constant *Init, Address Loc,
899 bool isVolatile, CGBuilderTy &Builder) {
Benjamin Kramer29f9a002012-08-27 22:07:02 +0000900 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
JF Bastiened92f602018-07-20 23:37:12 +0000901 "called emitStoresForInitAfterBZero for zero or undef value.");
Eric Christopher31ab1302011-08-23 22:38:00 +0000902
Chris Lattnere6af8862010-12-02 01:58:41 +0000903 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
904 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
905 isa<llvm::ConstantExpr>(Init)) {
JF Bastien9aab85a2018-07-13 20:33:23 +0000906 Builder.CreateStore(Init, Loc, isVolatile);
Chris Lattner236b3572012-01-31 04:36:19 +0000907 return;
908 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000909
910 if (llvm::ConstantDataSequential *CDS =
911 dyn_cast<llvm::ConstantDataSequential>(Init)) {
Chris Lattner236b3572012-01-31 04:36:19 +0000912 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
913 llvm::Constant *Elt = CDS->getElementAsConstant(i);
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000914
915 // If necessary, get a pointer to the element and emit it.
916 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
JF Bastiened92f602018-07-20 23:37:12 +0000917 emitStoresForInitAfterBZero(
JF Bastien9aab85a2018-07-13 20:33:23 +0000918 CGM, Elt,
919 Builder.CreateConstInBoundsGEP2_32(Loc, 0, i, CGM.getDataLayout()),
David Blaikie17ea2662015-04-04 21:07:17 +0000920 isVolatile, Builder);
Chris Lattner236b3572012-01-31 04:36:19 +0000921 }
Chris Lattnere6af8862010-12-02 01:58:41 +0000922 return;
923 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000924
Chris Lattnere6af8862010-12-02 01:58:41 +0000925 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
926 "Unknown value type!");
Eric Christopher31ab1302011-08-23 22:38:00 +0000927
Chris Lattnere6af8862010-12-02 01:58:41 +0000928 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
929 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000930
931 // If necessary, get a pointer to the element and emit it.
932 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
JF Bastiened92f602018-07-20 23:37:12 +0000933 emitStoresForInitAfterBZero(
JF Bastien9aab85a2018-07-13 20:33:23 +0000934 CGM, Elt,
935 Builder.CreateConstInBoundsGEP2_32(Loc, 0, i, CGM.getDataLayout()),
David Blaikie17ea2662015-04-04 21:07:17 +0000936 isVolatile, Builder);
Chris Lattnere6af8862010-12-02 01:58:41 +0000937 }
Chris Lattnerb85025f2010-12-01 02:05:19 +0000938}
939
JF Bastiened92f602018-07-20 23:37:12 +0000940/// Decide whether we should use bzero plus some stores to initialize a local
941/// variable instead of using a memcpy from a constant global. It is beneficial
942/// to use bzero if the global is all zeros, or mostly zeros and large.
943static bool shouldUseBZeroPlusStoresToInitialize(llvm::Constant *Init,
944 uint64_t GlobalSize) {
945 // If a global is all zeros, always use a bzero.
Chris Lattnerb85025f2010-12-01 02:05:19 +0000946 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
947
Chris Lattnerb85025f2010-12-01 02:05:19 +0000948 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
949 // do it if it will require 6 or fewer scalar stores.
950 // TODO: Should budget depends on the size? Avoiding a large global warrants
951 // plopping in more stores.
952 unsigned StoreBudget = 6;
953 uint64_t SizeLimit = 32;
Eric Christopher31ab1302011-08-23 22:38:00 +0000954
955 return GlobalSize > SizeLimit &&
JF Bastiened92f602018-07-20 23:37:12 +0000956 canEmitInitWithFewStoresAfterBZero(Init, StoreBudget);
Chris Lattnerb85025f2010-12-01 02:05:19 +0000957}
958
JF Bastien65089292018-07-25 04:29:03 +0000959/// Decide whether we should use memset to initialize a local variable instead
960/// of using a memcpy from a constant global. Assumes we've already decided to
961/// not user bzero.
962/// FIXME We could be more clever, as we are for bzero above, and generate
963/// memset followed by stores. It's unclear that's worth the effort.
JF Bastien2f0582f2018-09-21 13:54:09 +0000964static llvm::Value *shouldUseMemSetToInitialize(llvm::Constant *Init,
965 uint64_t GlobalSize) {
JF Bastien65089292018-07-25 04:29:03 +0000966 uint64_t SizeLimit = 32;
967 if (GlobalSize <= SizeLimit)
JF Bastien2f0582f2018-09-21 13:54:09 +0000968 return nullptr;
969 return llvm::isBytewiseValue(Init);
JF Bastien65089292018-07-25 04:29:03 +0000970}
971
JF Bastien14daa202018-12-18 05:12:21 +0000972static llvm::Constant *patternFor(CodeGenModule &CGM, llvm::Type *Ty) {
973 // The following value is a guaranteed unmappable pointer value and has a
974 // repeated byte-pattern which makes it easier to synthesize. We use it for
975 // pointers as well as integers so that aggregates are likely to be
976 // initialized with this repeated value.
977 constexpr uint64_t LargeValue = 0xAAAAAAAAAAAAAAAAull;
978 // For 32-bit platforms it's a bit trickier because, across systems, only the
979 // zero page can reasonably be expected to be unmapped, and even then we need
980 // a very low address. We use a smaller value, and that value sadly doesn't
981 // have a repeated byte-pattern. We don't use it for integers.
982 constexpr uint32_t SmallValue = 0x000000AA;
983 // Floating-point values are initialized as NaNs because they propagate. Using
984 // a repeated byte pattern means that it will be easier to initialize
985 // all-floating-point aggregates and arrays with memset. Further, aggregates
986 // which mix integral and a few floats might also initialize with memset
987 // followed by a handful of stores for the floats. Using fairly unique NaNs
988 // also means they'll be easier to distinguish in a crash.
989 constexpr bool NegativeNaN = true;
990 constexpr uint64_t NaNPayload = 0xFFFFFFFFFFFFFFFFull;
991 if (Ty->isIntOrIntVectorTy()) {
992 unsigned BitWidth = cast<llvm::IntegerType>(
993 Ty->isVectorTy() ? Ty->getVectorElementType() : Ty)
994 ->getBitWidth();
995 if (BitWidth <= 64)
996 return llvm::ConstantInt::get(Ty, LargeValue);
997 return llvm::ConstantInt::get(
998 Ty, llvm::APInt::getSplat(BitWidth, llvm::APInt(64, LargeValue)));
999 }
1000 if (Ty->isPtrOrPtrVectorTy()) {
1001 auto *PtrTy = cast<llvm::PointerType>(
1002 Ty->isVectorTy() ? Ty->getVectorElementType() : Ty);
1003 unsigned PtrWidth = CGM.getContext().getTargetInfo().getPointerWidth(
1004 PtrTy->getAddressSpace());
1005 llvm::Type *IntTy = llvm::IntegerType::get(CGM.getLLVMContext(), PtrWidth);
1006 uint64_t IntValue;
1007 switch (PtrWidth) {
1008 default:
1009 llvm_unreachable("pattern initialization of unsupported pointer width");
1010 case 64:
1011 IntValue = LargeValue;
1012 break;
1013 case 32:
1014 IntValue = SmallValue;
1015 break;
1016 }
1017 auto *Int = llvm::ConstantInt::get(IntTy, IntValue);
1018 return llvm::ConstantExpr::getIntToPtr(Int, PtrTy);
1019 }
1020 if (Ty->isFPOrFPVectorTy()) {
1021 unsigned BitWidth = llvm::APFloat::semanticsSizeInBits(
1022 (Ty->isVectorTy() ? Ty->getVectorElementType() : Ty)
1023 ->getFltSemantics());
1024 llvm::APInt Payload(64, NaNPayload);
1025 if (BitWidth >= 64)
1026 Payload = llvm::APInt::getSplat(BitWidth, Payload);
1027 return llvm::ConstantFP::getQNaN(Ty, NegativeNaN, &Payload);
1028 }
1029 if (Ty->isArrayTy()) {
1030 // Note: this doesn't touch tail padding (at the end of an object, before
1031 // the next array object). It is instead handled by replaceUndef.
1032 auto *ArrTy = cast<llvm::ArrayType>(Ty);
1033 llvm::SmallVector<llvm::Constant *, 8> Element(
1034 ArrTy->getNumElements(), patternFor(CGM, ArrTy->getElementType()));
1035 return llvm::ConstantArray::get(ArrTy, Element);
1036 }
1037
1038 // Note: this doesn't touch struct padding. It will initialize as much union
1039 // padding as is required for the largest type in the union. Padding is
1040 // instead handled by replaceUndef. Stores to structs with volatile members
1041 // don't have a volatile qualifier when initialized according to C++. This is
1042 // fine because stack-based volatiles don't really have volatile semantics
1043 // anyways, and the initialization shouldn't be observable.
1044 auto *StructTy = cast<llvm::StructType>(Ty);
1045 llvm::SmallVector<llvm::Constant *, 8> Struct(StructTy->getNumElements());
1046 for (unsigned El = 0; El != Struct.size(); ++El)
1047 Struct[El] = patternFor(CGM, StructTy->getElementType(El));
1048 return llvm::ConstantStruct::get(StructTy, Struct);
1049}
1050
JF Bastien3a881e62018-11-15 00:19:18 +00001051static Address createUnnamedGlobalFrom(CodeGenModule &CGM, const VarDecl &D,
1052 CGBuilderTy &Builder,
1053 llvm::Constant *Constant,
1054 CharUnits Align) {
1055 auto FunctionName = [&](const DeclContext *DC) -> std::string {
1056 if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
1057 if (const auto *CC = dyn_cast<CXXConstructorDecl>(FD))
1058 return CC->getNameAsString();
1059 if (const auto *CD = dyn_cast<CXXDestructorDecl>(FD))
1060 return CD->getNameAsString();
1061 return CGM.getMangledName(FD);
1062 } else if (const auto *OM = dyn_cast<ObjCMethodDecl>(DC)) {
1063 return OM->getNameAsString();
Mikael Holmenee846762018-11-15 13:01:54 +00001064 } else if (isa<BlockDecl>(DC)) {
JF Bastien3a881e62018-11-15 00:19:18 +00001065 return "<block>";
Mikael Holmenee846762018-11-15 13:01:54 +00001066 } else if (isa<CapturedDecl>(DC)) {
JF Bastien3a881e62018-11-15 00:19:18 +00001067 return "<captured>";
1068 } else {
1069 llvm::llvm_unreachable_internal("expected a function or method");
1070 }
1071 };
1072
1073 auto *Ty = Constant->getType();
1074 bool isConstant = true;
1075 llvm::GlobalVariable *InsertBefore = nullptr;
1076 unsigned AS = CGM.getContext().getTargetAddressSpace(
1077 CGM.getStringLiteralAddressSpace());
1078 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1079 CGM.getModule(), Ty, isConstant, llvm::GlobalValue::PrivateLinkage,
1080 Constant,
1081 "__const." + FunctionName(D.getParentFunctionOrMethod()) + "." +
1082 D.getName(),
1083 InsertBefore, llvm::GlobalValue::NotThreadLocal, AS);
1084 GV->setAlignment(Align.getQuantity());
1085 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1086
1087 Address SrcPtr = Address(GV, Align);
1088 llvm::Type *BP = llvm::PointerType::getInt8PtrTy(CGM.getLLVMContext(), AS);
1089 if (SrcPtr.getType() != BP)
1090 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
1091 return SrcPtr;
1092}
1093
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001094static void emitStoresForConstant(CodeGenModule &CGM, const VarDecl &D,
1095 Address Loc, bool isVolatile,
1096 CGBuilderTy &Builder,
1097 llvm::Constant *constant) {
JF Bastien14daa202018-12-18 05:12:21 +00001098 auto *Ty = constant->getType();
1099 bool isScalar = Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy() ||
1100 Ty->isFPOrFPVectorTy();
1101 if (isScalar) {
1102 Builder.CreateStore(constant, Loc, isVolatile);
1103 return;
1104 }
1105
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001106 auto *Int8Ty = llvm::IntegerType::getInt8Ty(CGM.getLLVMContext());
1107 auto *IntPtrTy = CGM.getDataLayout().getIntPtrType(CGM.getLLVMContext());
1108
1109 // If the initializer is all or mostly the same, codegen with bzero / memset
1110 // then do a few stores afterward.
JF Bastien14daa202018-12-18 05:12:21 +00001111 uint64_t ConstantSize = CGM.getDataLayout().getTypeAllocSize(Ty);
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001112 auto *SizeVal = llvm::ConstantInt::get(IntPtrTy, ConstantSize);
1113 if (shouldUseBZeroPlusStoresToInitialize(constant, ConstantSize)) {
1114 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1115 isVolatile);
1116
1117 bool valueAlreadyCorrect =
1118 constant->isNullValue() || isa<llvm::UndefValue>(constant);
1119 if (!valueAlreadyCorrect) {
JF Bastien14daa202018-12-18 05:12:21 +00001120 Loc = Builder.CreateBitCast(Loc, Ty->getPointerTo(Loc.getAddressSpace()));
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001121 emitStoresForInitAfterBZero(CGM, constant, Loc, isVolatile, Builder);
1122 }
1123 return;
1124 }
1125
JF Bastien2f0582f2018-09-21 13:54:09 +00001126 llvm::Value *Pattern = shouldUseMemSetToInitialize(constant, ConstantSize);
1127 if (Pattern) {
1128 uint64_t Value = 0x00;
1129 if (!isa<llvm::UndefValue>(Pattern)) {
1130 const llvm::APInt &AP = cast<llvm::ConstantInt>(Pattern)->getValue();
1131 assert(AP.getBitWidth() <= 8);
1132 Value = AP.getLimitedValue();
1133 }
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001134 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, Value), SizeVal,
1135 isVolatile);
1136 return;
1137 }
1138
JF Bastien3a881e62018-11-15 00:19:18 +00001139 Builder.CreateMemCpy(
1140 Loc,
1141 createUnnamedGlobalFrom(CGM, D, Builder, constant, Loc.getAlignment()),
1142 SizeVal, isVolatile);
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001143}
1144
JF Bastien14daa202018-12-18 05:12:21 +00001145static void emitStoresForZeroInit(CodeGenModule &CGM, const VarDecl &D,
1146 Address Loc, bool isVolatile,
1147 CGBuilderTy &Builder) {
1148 llvm::Type *ElTy = Loc.getElementType();
1149 llvm::Constant *constant = llvm::Constant::getNullValue(ElTy);
1150 emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant);
1151}
1152
1153static void emitStoresForPatternInit(CodeGenModule &CGM, const VarDecl &D,
1154 Address Loc, bool isVolatile,
1155 CGBuilderTy &Builder) {
1156 llvm::Type *ElTy = Loc.getElementType();
1157 llvm::Constant *constant = patternFor(CGM, ElTy);
1158 assert(!isa<llvm::UndefValue>(constant));
1159 emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant);
1160}
1161
1162static bool containsUndef(llvm::Constant *constant) {
1163 auto *Ty = constant->getType();
1164 if (isa<llvm::UndefValue>(constant))
1165 return true;
1166 if (Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy())
1167 for (llvm::Use &Op : constant->operands())
1168 if (containsUndef(cast<llvm::Constant>(Op)))
1169 return true;
1170 return false;
1171}
1172
1173static llvm::Constant *replaceUndef(llvm::Constant *constant) {
1174 // FIXME: when doing pattern initialization, replace undef with 0xAA instead.
1175 // FIXME: also replace padding between values by creating a new struct type
1176 // which has no padding.
1177 auto *Ty = constant->getType();
1178 if (isa<llvm::UndefValue>(constant))
1179 return llvm::Constant::getNullValue(Ty);
1180 if (!(Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()))
1181 return constant;
1182 if (!containsUndef(constant))
1183 return constant;
1184 llvm::SmallVector<llvm::Constant *, 8> Values(constant->getNumOperands());
1185 for (unsigned Op = 0, NumOp = constant->getNumOperands(); Op != NumOp; ++Op) {
1186 auto *OpValue = cast<llvm::Constant>(constant->getOperand(Op));
1187 Values[Op] = replaceUndef(OpValue);
1188 }
1189 if (Ty->isStructTy())
1190 return llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Values);
1191 if (Ty->isArrayTy())
1192 return llvm::ConstantArray::get(cast<llvm::ArrayType>(Ty), Values);
1193 assert(Ty->isVectorTy());
1194 return llvm::ConstantVector::get(Values);
1195}
1196
Nick Lewycky8a7d90b2010-12-30 20:21:55 +00001197/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Chris Lattner03df1222007-06-02 04:53:11 +00001198/// variable declaration with auto, register, or no storage class specifier.
Chris Lattnerb781dc792008-05-08 05:58:21 +00001199/// These turn into simple stack objects, or GlobalValues depending on target.
John McCallc533cb72011-02-22 06:44:22 +00001200void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
1201 AutoVarEmission emission = EmitAutoVarAlloca(D);
1202 EmitAutoVarInit(emission);
1203 EmitAutoVarCleanups(emission);
1204}
Chris Lattner03df1222007-06-02 04:53:11 +00001205
David Majnemerdc012fa2015-04-22 21:38:15 +00001206/// Emit a lifetime.begin marker if some criteria are satisfied.
1207/// \return a pointer to the temporary size Value if a marker was emitted, null
1208/// otherwise
1209llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
1210 llvm::Value *Addr) {
Vitaly Buka1c943322016-10-26 01:59:57 +00001211 if (!ShouldEmitLifetimeMarkers)
Reid Kleckner1ef49212015-04-23 18:07:13 +00001212 return nullptr;
1213
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001214 assert(Addr->getType()->getPointerAddressSpace() ==
1215 CGM.getDataLayout().getAllocaAddrSpace() &&
1216 "Pointer should be in alloca address space");
David Majnemerdc012fa2015-04-22 21:38:15 +00001217 llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
Yaxun Liu7f7f3232017-04-17 20:03:11 +00001218 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
Alexey Samsonovd918ff62015-06-12 22:31:32 +00001219 llvm::CallInst *C =
1220 Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +00001221 C->setDoesNotThrow();
1222 return SizeV;
1223}
1224
1225void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001226 assert(Addr->getType()->getPointerAddressSpace() ==
1227 CGM.getDataLayout().getAllocaAddrSpace() &&
1228 "Pointer should be in alloca address space");
Yaxun Liu7f7f3232017-04-17 20:03:11 +00001229 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
Alexey Samsonovd918ff62015-06-12 22:31:32 +00001230 llvm::CallInst *C =
1231 Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +00001232 C->setDoesNotThrow();
1233}
1234
Sander de Smalen891af03a2018-02-03 13:55:59 +00001235void CodeGenFunction::EmitAndRegisterVariableArrayDimensions(
1236 CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo) {
1237 // For each dimension stores its QualType and corresponding
1238 // size-expression Value.
1239 SmallVector<CodeGenFunction::VlaSizePair, 4> Dimensions;
Adrian Prantla40cce82018-11-09 19:17:56 +00001240 SmallVector<IdentifierInfo *, 4> VLAExprNames;
Sander de Smalen891af03a2018-02-03 13:55:59 +00001241
1242 // Break down the array into individual dimensions.
1243 QualType Type1D = D.getType();
1244 while (getContext().getAsVariableArrayType(Type1D)) {
1245 auto VlaSize = getVLAElements1D(Type1D);
1246 if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1247 Dimensions.emplace_back(C, Type1D.getUnqualifiedType());
1248 else {
Adrian Prantla40cce82018-11-09 19:17:56 +00001249 // Generate a locally unique name for the size expression.
1250 Twine Name = Twine("__vla_expr") + Twine(VLAExprCounter++);
1251 SmallString<12> Buffer;
1252 StringRef NameRef = Name.toStringRef(Buffer);
1253 auto &Ident = getContext().Idents.getOwn(NameRef);
1254 VLAExprNames.push_back(&Ident);
1255 auto SizeExprAddr =
1256 CreateDefaultAlignTempAlloca(VlaSize.NumElts->getType(), NameRef);
Sander de Smalen891af03a2018-02-03 13:55:59 +00001257 Builder.CreateStore(VlaSize.NumElts, SizeExprAddr);
1258 Dimensions.emplace_back(SizeExprAddr.getPointer(),
1259 Type1D.getUnqualifiedType());
1260 }
1261 Type1D = VlaSize.Type;
1262 }
1263
1264 if (!EmitDebugInfo)
1265 return;
1266
1267 // Register each dimension's size-expression with a DILocalVariable,
1268 // so that it can be used by CGDebugInfo when instantiating a DISubrange
1269 // to describe this array.
Adrian Prantla40cce82018-11-09 19:17:56 +00001270 unsigned NameIdx = 0;
Sander de Smalen891af03a2018-02-03 13:55:59 +00001271 for (auto &VlaSize : Dimensions) {
1272 llvm::Metadata *MD;
1273 if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1274 MD = llvm::ConstantAsMetadata::get(C);
1275 else {
1276 // Create an artificial VarDecl to generate debug info for.
Adrian Prantla40cce82018-11-09 19:17:56 +00001277 IdentifierInfo *NameIdent = VLAExprNames[NameIdx++];
Sander de Smalen891af03a2018-02-03 13:55:59 +00001278 auto VlaExprTy = VlaSize.NumElts->getType()->getPointerElementType();
1279 auto QT = getContext().getIntTypeForBitwidth(
1280 VlaExprTy->getScalarSizeInBits(), false);
1281 auto *ArtificialDecl = VarDecl::Create(
1282 getContext(), const_cast<DeclContext *>(D.getDeclContext()),
Adrian Prantla40cce82018-11-09 19:17:56 +00001283 D.getLocation(), D.getLocation(), NameIdent, QT,
Sander de Smalen891af03a2018-02-03 13:55:59 +00001284 getContext().CreateTypeSourceInfo(QT), SC_Auto);
Sander de Smalen9084a3b2018-02-13 07:49:34 +00001285 ArtificialDecl->setImplicit();
Sander de Smalen891af03a2018-02-03 13:55:59 +00001286
1287 MD = DI->EmitDeclareOfAutoVariable(ArtificialDecl, VlaSize.NumElts,
1288 Builder);
1289 }
1290 assert(MD && "No Size expression debug node created");
1291 DI->registerVLASizeExpression(VlaSize.Type, MD);
1292 }
1293}
1294
John McCallc533cb72011-02-22 06:44:22 +00001295/// EmitAutoVarAlloca - Emit the alloca and debug information for a
Alp Tokerf6a24ce2013-12-05 16:25:25 +00001296/// local variable. Does not emit initialization or destruction.
John McCallc533cb72011-02-22 06:44:22 +00001297CodeGenFunction::AutoVarEmission
1298CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
1299 QualType Ty = D.getType();
Yaxun Liub7318e02017-10-13 03:37:48 +00001300 assert(
1301 Ty.getAddressSpace() == LangAS::Default ||
1302 (Ty.getAddressSpace() == LangAS::opencl_private && getLangOpts().OpenCL));
John McCallc533cb72011-02-22 06:44:22 +00001303
1304 AutoVarEmission emission(D);
1305
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001306 bool isEscapingByRef = D.isEscapingByref();
1307 emission.IsEscapingByRef = isEscapingByRef;
John McCallc533cb72011-02-22 06:44:22 +00001308
1309 CharUnits alignment = getContext().getDeclAlign(&D);
John McCallc533cb72011-02-22 06:44:22 +00001310
John McCall23c29fe2011-06-24 21:55:10 +00001311 // If the type is variably-modified, emit all the VLA sizes for it.
1312 if (Ty->isVariablyModifiedType())
1313 EmitVariablyModifiedType(Ty);
1314
Sander de Smalen891af03a2018-02-03 13:55:59 +00001315 auto *DI = getDebugInfo();
1316 bool EmitDebugInfo = DI && CGM.getCodeGenOpts().getDebugInfo() >=
1317 codegenoptions::LimitedDebugInfo;
1318
John McCall7f416cc2015-09-08 08:05:57 +00001319 Address address = Address::invalid();
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001320 Address AllocaAddr = Address::invalid();
Eli Friedmana682d392008-02-15 12:20:59 +00001321 if (Ty->isConstantSizeType()) {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001322 bool NRVO = getLangOpts().ElideConstructors &&
1323 D.isNRVOVariable();
John McCallc533cb72011-02-22 06:44:22 +00001324
Richard Smith2bcde3a2013-06-02 00:09:52 +00001325 // If this value is an array or struct with a statically determinable
1326 // constant initializer, there are optimizations we can do.
Rafael Espindola609f5d92013-03-26 18:41:47 +00001327 //
1328 // TODO: We should constant-evaluate the initializer of any variable,
1329 // as long as it is initialized by a constant expression. Currently,
1330 // isConstantInitializer produces wrong answers for structs with
1331 // reference or bitfield members, and a few other cases, and checking
1332 // for POD-ness protects us from some of these.
Richard Smith2bcde3a2013-06-02 00:09:52 +00001333 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
1334 (D.isConstexpr() ||
1335 ((Ty.isPODType(getContext()) ||
1336 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
1337 D.getInit()->isConstantInitializer(getContext(), false)))) {
John McCallc533cb72011-02-22 06:44:22 +00001338
Rafael Espindola609f5d92013-03-26 18:41:47 +00001339 // If the variable's a const type, and it's neither an NRVO
1340 // candidate nor a __block variable and has no mutable members,
1341 // emit it as a global instead.
Anastasia Stulovae4a1c382016-11-29 17:01:19 +00001342 // Exception is if a variable is located in non-constant address space
1343 // in OpenCL.
1344 if ((!getLangOpts().OpenCL ||
1345 Ty.getAddressSpace() == LangAS::opencl_constant) &&
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001346 (CGM.getCodeGenOpts().MergeAllConstants && !NRVO &&
1347 !isEscapingByRef && CGM.isTypeConstant(Ty, true))) {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001348 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCallc533cb72011-02-22 06:44:22 +00001349
John McCall7f416cc2015-09-08 08:05:57 +00001350 // Signal this condition to later callbacks.
1351 emission.Addr = Address::invalid();
Rafael Espindola609f5d92013-03-26 18:41:47 +00001352 assert(emission.wasEmittedAsGlobal());
1353 return emission;
Tanya Lattnerf9d41df2009-11-04 01:18:09 +00001354 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001355
Rafael Espindola609f5d92013-03-26 18:41:47 +00001356 // Otherwise, tell the initialization code that we're in this case.
1357 emission.IsConstantAggregate = true;
1358 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001359
Rafael Espindola609f5d92013-03-26 18:41:47 +00001360 // A normal fixed sized variable becomes an alloca in the entry block,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001361 // unless:
1362 // - it's an NRVO variable.
1363 // - we are compiling OpenMP and it's an OpenMP local variable.
Eric Christopher31ab1302011-08-23 22:38:00 +00001364
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001365 Address OpenMPLocalAddr =
1366 getLangOpts().OpenMP
1367 ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
1368 : Address::invalid();
1369 if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
1370 address = OpenMPLocalAddr;
1371 } else if (NRVO) {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001372 // The named return value optimization: allocate this variable in the
1373 // return slot, so that we can elide the copy when returning this
1374 // variable (C++0x [class.copy]p34).
John McCall7f416cc2015-09-08 08:05:57 +00001375 address = ReturnValue;
Eric Christopher31ab1302011-08-23 22:38:00 +00001376
Rafael Espindola609f5d92013-03-26 18:41:47 +00001377 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
Akira Hatanaka673af7a2018-03-29 17:56:24 +00001378 const auto *RD = RecordTy->getDecl();
1379 const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1380 if ((CXXRD && !CXXRD->hasTrivialDestructor()) ||
1381 RD->isNonTrivialToPrimitiveDestroy()) {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001382 // Create a flag that is used to indicate when the NRVO was applied
1383 // to this variable. Set it to zero to indicate that NRVO was not
1384 // applied.
1385 llvm::Value *Zero = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +00001386 Address NRVOFlag =
1387 CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
Rafael Espindola609f5d92013-03-26 18:41:47 +00001388 EnsureInsertPoint();
1389 Builder.CreateStore(Zero, NRVOFlag);
Eric Christopher31ab1302011-08-23 22:38:00 +00001390
Rafael Espindola609f5d92013-03-26 18:41:47 +00001391 // Record the NRVO flag for this variable.
John McCall7f416cc2015-09-08 08:05:57 +00001392 NRVOFlags[&D] = NRVOFlag.getPointer();
1393 emission.NRVOFlag = NRVOFlag.getPointer();
Nadav Rotem1da30942013-03-23 06:43:35 +00001394 }
Douglas Gregor290c93e2010-05-15 06:46:45 +00001395 }
Chris Lattnerb781dc792008-05-08 05:58:21 +00001396 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001397 CharUnits allocaAlignment;
1398 llvm::Type *allocaTy;
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001399 if (isEscapingByRef) {
John McCall7f416cc2015-09-08 08:05:57 +00001400 auto &byrefInfo = getBlockByrefInfo(&D);
1401 allocaTy = byrefInfo.Type;
1402 allocaAlignment = byrefInfo.ByrefAlignment;
1403 } else {
1404 allocaTy = ConvertTypeForMem(Ty);
1405 allocaAlignment = alignment;
1406 }
Rafael Espindola609f5d92013-03-26 18:41:47 +00001407
John McCall999110f2015-09-08 09:18:30 +00001408 // Create the alloca. Note that we set the name separately from
1409 // building the instruction so that it's there even in no-asserts
1410 // builds.
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001411 address = CreateTempAlloca(allocaTy, allocaAlignment, D.getName(),
1412 /*ArraySize=*/nullptr, &AllocaAddr);
Rafael Espindola609f5d92013-03-26 18:41:47 +00001413
Reid Kleckner1f88e932015-10-07 21:03:41 +00001414 // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1415 // the catch parameter starts in the catchpad instruction, and we can't
1416 // insert code in those basic blocks.
1417 bool IsMSCatchParam =
1418 D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1419
Vitaly Buka64c80b42016-10-26 05:42:30 +00001420 // Emit a lifetime intrinsic if meaningful. There's no point in doing this
1421 // if we don't have a valid insertion point (?).
Reid Kleckner1f88e932015-10-07 21:03:41 +00001422 if (HaveInsertPoint() && !IsMSCatchParam) {
Akira Hatanakafdcd18b2017-01-25 22:55:13 +00001423 // If there's a jump into the lifetime of this variable, its lifetime
1424 // gets broken up into several regions in IR, which requires more work
1425 // to handle correctly. For now, just omit the intrinsics; this is a
1426 // rare case, and it's better to just be conservatively correct.
1427 // PR28267.
1428 //
1429 // We have to do this in all language modes if there's a jump past the
1430 // declaration. We also have to do it in C if there's a jump to an
1431 // earlier point in the current block because non-VLA lifetimes begin as
1432 // soon as the containing block is entered, not when its variables
1433 // actually come into scope; suppressing the lifetime annotations
1434 // completely in this case is unnecessarily pessimistic, but again, this
1435 // is rare.
1436 if (!Bypasses.IsBypassed(&D) &&
1437 !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
Vitaly Buka64c80b42016-10-26 05:42:30 +00001438 uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
1439 emission.SizeForLifetimeMarkers =
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001440 EmitLifetimeStart(size, AllocaAddr.getPointer());
Vitaly Buka64c80b42016-10-26 05:42:30 +00001441 }
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +00001442 } else {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001443 assert(!emission.useLifetimeMarkers());
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +00001444 }
Chris Lattnerb781dc792008-05-08 05:58:21 +00001445 }
Chris Lattner03df1222007-06-02 04:53:11 +00001446 } else {
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001447 EnsureInsertPoint();
1448
Anders Carlsson15949b32009-02-09 20:41:50 +00001449 if (!DidCallStackSave) {
Anders Carlsson30032882008-12-12 07:38:43 +00001450 // Save the stack.
John McCall7f416cc2015-09-08 08:05:57 +00001451 Address Stack =
1452 CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
Mike Stump11289f42009-09-09 15:08:12 +00001453
Anders Carlsson30032882008-12-12 07:38:43 +00001454 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
David Blaikie4ba525b2015-07-14 17:27:39 +00001455 llvm::Value *V = Builder.CreateCall(F);
Anders Carlsson30032882008-12-12 07:38:43 +00001456 Builder.CreateStore(V, Stack);
Anders Carlsson15949b32009-02-09 20:41:50 +00001457
1458 DidCallStackSave = true;
Mike Stump11289f42009-09-09 15:08:12 +00001459
John McCalla464ff92010-07-21 06:13:08 +00001460 // Push a cleanup block and restore the stack there.
John McCalle4df6c82011-01-28 08:37:24 +00001461 // FIXME: in general circumstances, this should be an EH cleanup.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001462 pushStackRestore(NormalCleanup, Stack);
Anders Carlsson30032882008-12-12 07:38:43 +00001463 }
Mike Stump11289f42009-09-09 15:08:12 +00001464
Sander de Smalen891af03a2018-02-03 13:55:59 +00001465 auto VlaSize = getVLASize(Ty);
1466 llvm::Type *llvmTy = ConvertTypeForMem(VlaSize.Type);
Anders Carlsson30032882008-12-12 07:38:43 +00001467
1468 // Allocate memory for the array.
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001469 address = CreateTempAlloca(llvmTy, alignment, "vla", VlaSize.NumElts,
1470 &AllocaAddr);
Sander de Smalen891af03a2018-02-03 13:55:59 +00001471
1472 // If we have debug info enabled, properly describe the VLA dimensions for
1473 // this type by registering the vla size expression for each of the
1474 // dimensions.
1475 EmitAndRegisterVariableArrayDimensions(DI, D, EmitDebugInfo);
Chris Lattner03df1222007-06-02 04:53:11 +00001476 }
Eli Friedmanf4084702008-12-20 23:11:59 +00001477
John McCall7f416cc2015-09-08 08:05:57 +00001478 setAddrOfLocalVar(&D, address);
1479 emission.Addr = address;
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001480 emission.AllocaAddr = AllocaAddr;
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001481
1482 // Emit debug info for local var declaration.
Sander de Smalen891af03a2018-02-03 13:55:59 +00001483 if (EmitDebugInfo && HaveInsertPoint()) {
1484 DI->setLocation(D.getLocation());
1485 (void)DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
1486 }
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001487
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001488 if (D.hasAttr<AnnotateAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00001489 EmitVarAnnotations(&D, address.getPointer());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001490
Kuba Mracek5e5e4e72017-04-14 16:53:25 +00001491 // Make sure we call @llvm.lifetime.end.
1492 if (emission.useLifetimeMarkers())
1493 EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001494 emission.getOriginalAllocatedAddress(),
Kuba Mracek5e5e4e72017-04-14 16:53:25 +00001495 emission.getSizeForLifetimeMarkers());
1496
John McCallc533cb72011-02-22 06:44:22 +00001497 return emission;
1498}
1499
JF Bastien6b239722018-05-19 04:21:26 +00001500static bool isCapturedBy(const VarDecl &, const Expr *);
1501
1502/// Determines whether the given __block variable is potentially
1503/// captured by the given statement.
1504static bool isCapturedBy(const VarDecl &Var, const Stmt *S) {
1505 if (const Expr *E = dyn_cast<Expr>(S))
1506 return isCapturedBy(Var, E);
1507 for (const Stmt *SubStmt : S->children())
1508 if (isCapturedBy(Var, SubStmt))
1509 return true;
1510 return false;
1511}
1512
John McCallc533cb72011-02-22 06:44:22 +00001513/// Determines whether the given __block variable is potentially
1514/// captured by the given expression.
JF Bastien6b239722018-05-19 04:21:26 +00001515static bool isCapturedBy(const VarDecl &Var, const Expr *E) {
John McCallc533cb72011-02-22 06:44:22 +00001516 // Skip the most common kinds of expressions that make
1517 // hierarchy-walking expensive.
JF Bastien6b239722018-05-19 04:21:26 +00001518 E = E->IgnoreParenCasts();
John McCallc533cb72011-02-22 06:44:22 +00001519
JF Bastien6b239722018-05-19 04:21:26 +00001520 if (const BlockExpr *BE = dyn_cast<BlockExpr>(E)) {
1521 const BlockDecl *Block = BE->getBlockDecl();
1522 for (const auto &I : Block->captures()) {
1523 if (I.getVariable() == &Var)
John McCallc533cb72011-02-22 06:44:22 +00001524 return true;
1525 }
1526
1527 // No need to walk into the subexpressions.
1528 return false;
1529 }
1530
JF Bastien6b239722018-05-19 04:21:26 +00001531 if (const StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001532 const CompoundStmt *CS = SE->getSubStmt();
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001533 for (const auto *BI : CS->body())
JF Bastien6b239722018-05-19 04:21:26 +00001534 if (const auto *BIE = dyn_cast<Expr>(BI)) {
1535 if (isCapturedBy(Var, BIE))
1536 return true;
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001537 }
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001538 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001539 // special case declarations
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001540 for (const auto *I : DS->decls()) {
1541 if (const auto *VD = dyn_cast<VarDecl>((I))) {
1542 const Expr *Init = VD->getInit();
JF Bastien6b239722018-05-19 04:21:26 +00001543 if (Init && isCapturedBy(Var, Init))
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001544 return true;
1545 }
1546 }
1547 }
1548 else
1549 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1550 // Later, provide code to poke into statements for capture analysis.
1551 return true;
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001552 return false;
1553 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001554
JF Bastien6b239722018-05-19 04:21:26 +00001555 for (const Stmt *SubStmt : E->children())
1556 if (isCapturedBy(Var, SubStmt))
John McCallc533cb72011-02-22 06:44:22 +00001557 return true;
1558
1559 return false;
1560}
1561
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001562/// Determine whether the given initializer is trivial in the sense
Douglas Gregor82e1af22011-07-01 21:08:19 +00001563/// that it requires no code to be generated.
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001564bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
Douglas Gregor82e1af22011-07-01 21:08:19 +00001565 if (!Init)
1566 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001567
Douglas Gregor82e1af22011-07-01 21:08:19 +00001568 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1569 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1570 if (Constructor->isTrivial() &&
1571 Constructor->isDefaultConstructor() &&
1572 !Construct->requiresZeroInitialization())
1573 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001574
Douglas Gregor82e1af22011-07-01 21:08:19 +00001575 return false;
1576}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001577
John McCallc533cb72011-02-22 06:44:22 +00001578void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001579 assert(emission.Variable && "emission was not valid!");
1580
John McCallc533cb72011-02-22 06:44:22 +00001581 // If this was emitted as a global constant, we're done.
1582 if (emission.wasEmittedAsGlobal()) return;
1583
John McCall9e2e22f2011-02-22 07:16:58 +00001584 const VarDecl &D = *emission.Variable;
Adrian Prantl95b24e92015-02-03 20:00:54 +00001585 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
John McCallc533cb72011-02-22 06:44:22 +00001586 QualType type = D.getType();
1587
JF Bastien14daa202018-12-18 05:12:21 +00001588 bool isVolatile = type.isVolatileQualified();
1589
Chris Lattner07eb7332007-07-12 00:39:48 +00001590 // If this local has an initializer, emit it now.
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001591 const Expr *Init = D.getInit();
1592
1593 // If we are at an unreachable point, we don't need to emit the initializer
1594 // unless it contains a label.
1595 if (!HaveInsertPoint()) {
John McCallc533cb72011-02-22 06:44:22 +00001596 if (!Init || !ContainsLabel(Init)) return;
1597 EnsureInsertPoint();
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001598 }
1599
John McCall73064872011-03-31 01:59:53 +00001600 // Initialize the structure of a __block variable.
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001601 if (emission.IsEscapingByRef)
John McCall73064872011-03-31 01:59:53 +00001602 emitByrefStructureInit(emission);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001603
Akira Hatanaka7275da02018-02-28 07:15:55 +00001604 // Initialize the variable here if it doesn't have a initializer and it is a
1605 // C struct that is non-trivial to initialize or an array containing such a
1606 // struct.
1607 if (!Init &&
1608 type.isNonTrivialToPrimitiveDefaultInitialize() ==
1609 QualType::PDIK_Struct) {
1610 LValue Dst = MakeAddrLValue(emission.getAllocatedAddress(), type);
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001611 if (emission.IsEscapingByRef)
Akira Hatanaka7275da02018-02-28 07:15:55 +00001612 drillIntoBlockVariable(*this, Dst, &D);
1613 defaultInitNonTrivialCStructVar(Dst);
1614 return;
1615 }
1616
John McCallc533cb72011-02-22 06:44:22 +00001617 // Check whether this is a byref variable that's potentially
1618 // captured and moved by its own initializer. If so, we'll need to
1619 // emit the initializer first, then copy into the variable.
JF Bastien14daa202018-12-18 05:12:21 +00001620 bool capturedByInit =
1621 Init && emission.IsEscapingByRef && isCapturedBy(D, Init);
John McCallc533cb72011-02-22 06:44:22 +00001622
John McCall7f416cc2015-09-08 08:05:57 +00001623 Address Loc =
JF Bastien14daa202018-12-18 05:12:21 +00001624 capturedByInit ? emission.Addr : emission.getObjectAddress(*this);
1625
1626 // Note: constexpr already initializes everything correctly.
1627 LangOptions::TrivialAutoVarInitKind trivialAutoVarInit =
1628 (D.isConstexpr()
1629 ? LangOptions::TrivialAutoVarInitKind::Uninitialized
1630 : (D.getAttr<UninitializedAttr>()
1631 ? LangOptions::TrivialAutoVarInitKind::Uninitialized
1632 : getContext().getLangOpts().getTrivialAutoVarInit()));
1633
1634 auto initializeWhatIsTechnicallyUninitialized = [&]() {
1635 if (trivialAutoVarInit ==
1636 LangOptions::TrivialAutoVarInitKind::Uninitialized)
1637 return;
1638
1639 CharUnits Size = getContext().getTypeSizeInChars(type);
1640 if (!Size.isZero()) {
1641 switch (trivialAutoVarInit) {
1642 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
1643 llvm_unreachable("Uninitialized handled above");
1644 case LangOptions::TrivialAutoVarInitKind::Zero:
1645 emitStoresForZeroInit(CGM, D, Loc, isVolatile, Builder);
1646 break;
1647 case LangOptions::TrivialAutoVarInitKind::Pattern:
1648 emitStoresForPatternInit(CGM, D, Loc, isVolatile, Builder);
1649 break;
1650 }
1651 return;
1652 }
1653
1654 // VLAs look zero-sized to getTypeInfo. We can't emit constant stores to
1655 // them, so emit a memcpy with the VLA size to initialize each element.
1656 // Technically zero-sized or negative-sized VLAs are undefined, and UBSan
1657 // will catch that code, but there exists code which generates zero-sized
1658 // VLAs. Be nice and initialize whatever they requested.
1659 const VariableArrayType *VlaType =
1660 dyn_cast_or_null<VariableArrayType>(getContext().getAsArrayType(type));
1661 if (!VlaType)
1662 return;
1663 auto VlaSize = getVLASize(VlaType);
1664 auto SizeVal = VlaSize.NumElts;
1665 CharUnits EltSize = getContext().getTypeSizeInChars(VlaSize.Type);
1666 switch (trivialAutoVarInit) {
1667 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
1668 llvm_unreachable("Uninitialized handled above");
1669
1670 case LangOptions::TrivialAutoVarInitKind::Zero:
1671 if (!EltSize.isOne())
1672 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
1673 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1674 isVolatile);
1675 break;
1676
1677 case LangOptions::TrivialAutoVarInitKind::Pattern: {
1678 llvm::Type *ElTy = Loc.getElementType();
1679 llvm::Constant *Constant = patternFor(CGM, ElTy);
1680 CharUnits ConstantAlign = getContext().getTypeAlignInChars(VlaSize.Type);
1681 llvm::BasicBlock *SetupBB = createBasicBlock("vla-setup.loop");
1682 llvm::BasicBlock *LoopBB = createBasicBlock("vla-init.loop");
1683 llvm::BasicBlock *ContBB = createBasicBlock("vla-init.cont");
1684 llvm::Value *IsZeroSizedVLA = Builder.CreateICmpEQ(
1685 SizeVal, llvm::ConstantInt::get(SizeVal->getType(), 0),
1686 "vla.iszerosized");
1687 Builder.CreateCondBr(IsZeroSizedVLA, ContBB, SetupBB);
1688 EmitBlock(SetupBB);
1689 if (!EltSize.isOne())
1690 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
1691 llvm::Value *BaseSizeInChars =
1692 llvm::ConstantInt::get(IntPtrTy, EltSize.getQuantity());
1693 Address Begin = Builder.CreateElementBitCast(Loc, Int8Ty, "vla.begin");
1694 llvm::Value *End =
1695 Builder.CreateInBoundsGEP(Begin.getPointer(), SizeVal, "vla.end");
1696 llvm::BasicBlock *OriginBB = Builder.GetInsertBlock();
1697 EmitBlock(LoopBB);
1698 llvm::PHINode *Cur = Builder.CreatePHI(Begin.getType(), 2, "vla.cur");
1699 Cur->addIncoming(Begin.getPointer(), OriginBB);
1700 CharUnits CurAlign = Loc.getAlignment().alignmentOfArrayElement(EltSize);
1701 Builder.CreateMemCpy(
1702 Address(Cur, CurAlign),
1703 createUnnamedGlobalFrom(CGM, D, Builder, Constant, ConstantAlign),
1704 BaseSizeInChars, isVolatile);
1705 llvm::Value *Next =
1706 Builder.CreateInBoundsGEP(Int8Ty, Cur, BaseSizeInChars, "vla.next");
1707 llvm::Value *Done = Builder.CreateICmpEQ(Next, End, "vla-init.isdone");
1708 Builder.CreateCondBr(Done, ContBB, LoopBB);
1709 Cur->addIncoming(Next, LoopBB);
1710 EmitBlock(ContBB);
1711 } break;
1712 }
1713 };
1714
1715 if (isTrivialInitializer(Init)) {
1716 initializeWhatIsTechnicallyUninitialized();
1717 return;
1718 }
John McCallc533cb72011-02-22 06:44:22 +00001719
Craig Topper8a13c412014-05-21 05:09:00 +00001720 llvm::Constant *constant = nullptr;
Richard Smith2bcde3a2013-06-02 00:09:52 +00001721 if (emission.IsConstantAggregate || D.isConstexpr()) {
Richard Smithfddd3842011-12-30 21:15:51 +00001722 assert(!capturedByInit && "constant init contains a capturing block?");
John McCallde0fe072017-08-15 21:42:52 +00001723 constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(D);
JF Bastien14daa202018-12-18 05:12:21 +00001724 if (constant && trivialAutoVarInit !=
1725 LangOptions::TrivialAutoVarInitKind::Uninitialized)
1726 constant = replaceUndef(constant);
Richard Smithfddd3842011-12-30 21:15:51 +00001727 }
1728
1729 if (!constant) {
JF Bastien14daa202018-12-18 05:12:21 +00001730 initializeWhatIsTechnicallyUninitialized();
John McCall7f416cc2015-09-08 08:05:57 +00001731 LValue lv = MakeAddrLValue(Loc, type);
John McCall1553b192011-06-16 04:16:24 +00001732 lv.setNonGC(true);
David Blaikie66e41972015-01-14 07:38:27 +00001733 return EmitExprAsInit(Init, &D, lv, capturedByInit);
John McCall1553b192011-06-16 04:16:24 +00001734 }
John McCall91ca10f2011-03-08 09:11:50 +00001735
Richard Smith2bcde3a2013-06-02 00:09:52 +00001736 if (!emission.IsConstantAggregate) {
1737 // For simple scalar/complex initialization, store the value directly.
John McCall7f416cc2015-09-08 08:05:57 +00001738 LValue lv = MakeAddrLValue(Loc, type);
Richard Smith2bcde3a2013-06-02 00:09:52 +00001739 lv.setNonGC(true);
1740 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1741 }
1742
Yaxun Liudaceb1e2018-05-14 19:20:12 +00001743 llvm::Type *BP = CGM.Int8Ty->getPointerTo(Loc.getAddressSpace());
John McCall7f416cc2015-09-08 08:05:57 +00001744 if (Loc.getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001745 Loc = Builder.CreateBitCast(Loc, BP);
Mon P Wangcc2ab0c2010-04-04 03:10:52 +00001746
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001747 emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant);
John McCall91ca10f2011-03-08 09:11:50 +00001748}
1749
Richard Smithe78fac52018-04-05 20:52:58 +00001750/// Emit an expression as an initializer for an object (variable, field, etc.)
1751/// at the given location. The expression is not necessarily the normal
1752/// initializer for the object, and the address is not necessarily
John McCall91ca10f2011-03-08 09:11:50 +00001753/// its normal location.
1754///
1755/// \param init the initializing expression
Richard Smithe78fac52018-04-05 20:52:58 +00001756/// \param D the object to act as if we're initializing
John McCall91ca10f2011-03-08 09:11:50 +00001757/// \param loc the address to initialize; its type is a pointer
Richard Smithe78fac52018-04-05 20:52:58 +00001758/// to the LLVM mapping of the object's type
John McCall91ca10f2011-03-08 09:11:50 +00001759/// \param alignment the alignment of the address
Richard Smithe78fac52018-04-05 20:52:58 +00001760/// \param capturedByInit true if \p D is a __block variable
John McCall91ca10f2011-03-08 09:11:50 +00001761/// whose address is potentially changed by the initializer
David Blaikie73ca5692014-12-09 00:32:22 +00001762void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +00001763 LValue lvalue, bool capturedByInit) {
John McCall31168b02011-06-15 23:02:42 +00001764 QualType type = D->getType();
John McCall91ca10f2011-03-08 09:11:50 +00001765
1766 if (type->isReferenceType()) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +00001767 RValue rvalue = EmitReferenceBindingToExpr(init);
Eric Christopher31ab1302011-08-23 22:38:00 +00001768 if (capturedByInit)
John McCall1553b192011-06-16 04:16:24 +00001769 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001770 EmitStoreThroughLValue(rvalue, lvalue, true);
John McCall47fb9502013-03-07 21:37:08 +00001771 return;
1772 }
1773 switch (getEvaluationKind(type)) {
1774 case TEK_Scalar:
David Blaikie66e41972015-01-14 07:38:27 +00001775 EmitScalarInit(init, D, lvalue, capturedByInit);
John McCall47fb9502013-03-07 21:37:08 +00001776 return;
1777 case TEK_Complex: {
John McCall91ca10f2011-03-08 09:11:50 +00001778 ComplexPairTy complex = EmitComplexExpr(init);
John McCall1553b192011-06-16 04:16:24 +00001779 if (capturedByInit)
1780 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001781 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
John McCall47fb9502013-03-07 21:37:08 +00001782 return;
1783 }
1784 case TEK_Aggregate:
John McCalla8ec7eb2013-03-07 21:37:17 +00001785 if (type->isAtomicType()) {
1786 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1787 } else {
Richard Smithe78fac52018-04-05 20:52:58 +00001788 AggValueSlot::Overlap_t Overlap = AggValueSlot::MayOverlap;
1789 if (isa<VarDecl>(D))
1790 Overlap = AggValueSlot::DoesNotOverlap;
1791 else if (auto *FD = dyn_cast<FieldDecl>(D))
1792 Overlap = overlapForFieldInit(FD);
John McCalla8ec7eb2013-03-07 21:37:17 +00001793 // TODO: how can we delay here if D is captured by its initializer?
1794 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001795 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001796 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00001797 AggValueSlot::IsNotAliased,
1798 Overlap));
John McCalla8ec7eb2013-03-07 21:37:17 +00001799 }
John McCall47fb9502013-03-07 21:37:08 +00001800 return;
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001801 }
John McCall47fb9502013-03-07 21:37:08 +00001802 llvm_unreachable("bad evaluation kind");
John McCallc533cb72011-02-22 06:44:22 +00001803}
John McCallbd309292010-07-06 01:34:17 +00001804
John McCall82fe67b2011-07-09 01:37:26 +00001805/// Enter a destroy cleanup for the given local variable.
1806void CodeGenFunction::emitAutoVarTypeCleanup(
1807 const CodeGenFunction::AutoVarEmission &emission,
1808 QualType::DestructionKind dtorKind) {
1809 assert(dtorKind != QualType::DK_none);
1810
1811 // Note that for __block variables, we want to destroy the
1812 // original stack object, not the possibly forwarded object.
John McCall7f416cc2015-09-08 08:05:57 +00001813 Address addr = emission.getObjectAddress(*this);
John McCall82fe67b2011-07-09 01:37:26 +00001814
1815 const VarDecl *var = emission.Variable;
1816 QualType type = var->getType();
1817
1818 CleanupKind cleanupKind = NormalAndEHCleanup;
Craig Topper8a13c412014-05-21 05:09:00 +00001819 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall82fe67b2011-07-09 01:37:26 +00001820
1821 switch (dtorKind) {
1822 case QualType::DK_none:
1823 llvm_unreachable("no cleanup for trivially-destructible variable");
1824
1825 case QualType::DK_cxx_destructor:
1826 // If there's an NRVO flag on the emission, we need a different
1827 // cleanup.
1828 if (emission.NRVOFlag) {
1829 assert(!type->isArrayType());
1830 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
Akira Hatanaka673af7a2018-03-29 17:56:24 +00001831 EHStack.pushCleanup<DestroyNRVOVariableCXX>(cleanupKind, addr, dtor,
1832 emission.NRVOFlag);
John McCall82fe67b2011-07-09 01:37:26 +00001833 return;
1834 }
1835 break;
1836
1837 case QualType::DK_objc_strong_lifetime:
1838 // Suppress cleanups for pseudo-strong variables.
1839 if (var->isARCPseudoStrong()) return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001840
John McCall82fe67b2011-07-09 01:37:26 +00001841 // Otherwise, consider whether to use an EH cleanup or not.
1842 cleanupKind = getARCCleanupKind();
1843
1844 // Use the imprecise destroyer by default.
1845 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1846 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1847 break;
1848
1849 case QualType::DK_objc_weak_lifetime:
1850 break;
Akira Hatanaka7275da02018-02-28 07:15:55 +00001851
1852 case QualType::DK_nontrivial_c_struct:
1853 destroyer = CodeGenFunction::destroyNonTrivialCStruct;
Akira Hatanaka673af7a2018-03-29 17:56:24 +00001854 if (emission.NRVOFlag) {
1855 assert(!type->isArrayType());
1856 EHStack.pushCleanup<DestroyNRVOVariableC>(cleanupKind, addr,
1857 emission.NRVOFlag, type);
1858 return;
1859 }
Akira Hatanaka7275da02018-02-28 07:15:55 +00001860 break;
John McCall82fe67b2011-07-09 01:37:26 +00001861 }
1862
1863 // If we haven't chosen a more specific destroyer, use the default.
Peter Collingbourne1425b452012-01-26 03:33:36 +00001864 if (!destroyer) destroyer = getDestroyer(dtorKind);
John McCall178360e2011-07-11 08:38:19 +00001865
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001866 // Use an EH cleanup in array destructors iff the destructor itself
John McCall178360e2011-07-11 08:38:19 +00001867 // is being pushed as an EH cleanup.
1868 bool useEHCleanup = (cleanupKind & EHCleanup);
1869 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1870 useEHCleanup);
John McCall82fe67b2011-07-09 01:37:26 +00001871}
1872
John McCallc533cb72011-02-22 06:44:22 +00001873void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001874 assert(emission.Variable && "emission was not valid!");
1875
John McCallc533cb72011-02-22 06:44:22 +00001876 // If this was emitted as a global constant, we're done.
1877 if (emission.wasEmittedAsGlobal()) return;
1878
John McCall8c38d352012-04-13 18:44:05 +00001879 // If we don't have an insertion point, we're done. Sema prevents
1880 // us from jumping into any of these scopes anyway.
1881 if (!HaveInsertPoint()) return;
1882
John McCall9e2e22f2011-02-22 07:16:58 +00001883 const VarDecl &D = *emission.Variable;
John McCallc533cb72011-02-22 06:44:22 +00001884
John McCall82fe67b2011-07-09 01:37:26 +00001885 // Check the type for a cleanup.
1886 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1887 emitAutoVarTypeCleanup(emission, dtorKind);
John McCall31168b02011-06-15 23:02:42 +00001888
John McCall1bd25562011-06-24 23:21:27 +00001889 // In GC mode, honor objc_precise_lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001890 if (getLangOpts().getGC() != LangOptions::NonGC &&
John McCall1bd25562011-06-24 23:21:27 +00001891 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1892 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1893 }
1894
John McCallc533cb72011-02-22 06:44:22 +00001895 // Handle the cleanup attribute.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001896 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001897 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001898
John McCallc533cb72011-02-22 06:44:22 +00001899 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001900 assert(F && "Could not find function!");
Mike Stump11289f42009-09-09 15:08:12 +00001901
John McCalla729c622012-02-17 03:33:10 +00001902 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
John McCallc533cb72011-02-22 06:44:22 +00001903 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001904 }
Mike Stump626aecc2009-03-05 01:23:13 +00001905
John McCallc533cb72011-02-22 06:44:22 +00001906 // If this is a block variable, call _Block_object_destroy
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001907 // (on the unforwarded address). Don't enter this cleanup if we're in pure-GC
1908 // mode.
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001909 if (emission.IsEscapingByRef &&
1910 CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001911 BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
1912 if (emission.Variable->getType().isObjCGCWeak())
1913 Flags |= BLOCK_FIELD_IS_WEAK;
1914 enterByrefCleanup(NormalAndEHCleanup, emission.Addr, Flags,
Akira Hatanaka9978da32018-08-10 15:09:24 +00001915 /*LoadBlockVarAddr*/ false,
1916 cxxDestructorCanThrow(emission.Variable->getType()));
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001917 }
Chris Lattner03df1222007-06-02 04:53:11 +00001918}
Chris Lattner53621a52007-06-13 20:44:40 +00001919
Peter Collingbourne1425b452012-01-26 03:33:36 +00001920CodeGenFunction::Destroyer *
John McCall82fe67b2011-07-09 01:37:26 +00001921CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1922 switch (kind) {
1923 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
John McCallc2f00012011-07-09 09:09:00 +00001924 case QualType::DK_cxx_destructor:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001925 return destroyCXXObject;
John McCallc2f00012011-07-09 09:09:00 +00001926 case QualType::DK_objc_strong_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001927 return destroyARCStrongPrecise;
John McCallc2f00012011-07-09 09:09:00 +00001928 case QualType::DK_objc_weak_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001929 return destroyARCWeak;
Akira Hatanaka7275da02018-02-28 07:15:55 +00001930 case QualType::DK_nontrivial_c_struct:
1931 return destroyNonTrivialCStruct;
John McCall82fe67b2011-07-09 01:37:26 +00001932 }
Matt Beaumont-Gay934bbf52012-01-27 00:46:27 +00001933 llvm_unreachable("Unknown DestructionKind");
John McCall82fe67b2011-07-09 01:37:26 +00001934}
1935
John McCall12cc42a2013-02-01 05:11:40 +00001936/// pushEHDestroy - Push the standard destructor for the given type as
1937/// an EH-only cleanup.
1938void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00001939 Address addr, QualType type) {
John McCall12cc42a2013-02-01 05:11:40 +00001940 assert(dtorKind && "cannot push destructor for trivial type");
1941 assert(needsEHCleanup(dtorKind));
1942
1943 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1944}
1945
1946/// pushDestroy - Push the standard destructor for the given type as
1947/// at least a normal cleanup.
John McCall4bd0fb12011-07-12 16:41:08 +00001948void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00001949 Address addr, QualType type) {
John McCall4bd0fb12011-07-12 16:41:08 +00001950 assert(dtorKind && "cannot push destructor for trivial type");
1951
1952 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1953 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1954 cleanupKind & EHCleanup);
1955}
1956
John McCall7f416cc2015-09-08 08:05:57 +00001957void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001958 QualType type, Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001959 bool useEHCleanupForArray) {
John McCall4bd0fb12011-07-12 16:41:08 +00001960 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1961 destroyer, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001962}
1963
John McCall7f416cc2015-09-08 08:05:57 +00001964void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001965 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
1966}
1967
Richard Smith736a9472013-06-12 20:42:33 +00001968void CodeGenFunction::pushLifetimeExtendedDestroy(
John McCall7f416cc2015-09-08 08:05:57 +00001969 CleanupKind cleanupKind, Address addr, QualType type,
Richard Smith736a9472013-06-12 20:42:33 +00001970 Destroyer *destroyer, bool useEHCleanupForArray) {
Richard Smith736a9472013-06-12 20:42:33 +00001971 // Push an EH-only cleanup for the object now.
1972 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1973 // around in case a temporary's destructor throws an exception.
1974 if (cleanupKind & EHCleanup)
1975 EHStack.pushCleanup<DestroyObject>(
1976 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1977 destroyer, useEHCleanupForArray);
1978
1979 // Remember that we need to push a full cleanup for the object at the
1980 // end of the full-expression.
1981 pushCleanupAfterFullExpr<DestroyObject>(
1982 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1983}
1984
John McCall178360e2011-07-11 08:38:19 +00001985/// emitDestroy - Immediately perform the destruction of the given
1986/// object.
1987///
1988/// \param addr - the address of the object; a type*
1989/// \param type - the type of the object; if an array type, all
1990/// objects are destroyed in reverse order
1991/// \param destroyer - the function to call to destroy individual
1992/// elements
1993/// \param useEHCleanupForArray - whether an EH cleanup should be
1994/// used when destroying array elements, in case one of the
1995/// destructions throws an exception
John McCall7f416cc2015-09-08 08:05:57 +00001996void CodeGenFunction::emitDestroy(Address addr, QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001997 Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001998 bool useEHCleanupForArray) {
John McCall82fe67b2011-07-09 01:37:26 +00001999 const ArrayType *arrayType = getContext().getAsArrayType(type);
2000 if (!arrayType)
2001 return destroyer(*this, addr, type);
2002
John McCall7f416cc2015-09-08 08:05:57 +00002003 llvm::Value *length = emitArrayLength(arrayType, type, addr);
2004
2005 CharUnits elementAlign =
2006 addr.getAlignment()
2007 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
John McCall97eab0a2011-07-13 08:09:46 +00002008
2009 // Normally we have to check whether the array is zero-length.
2010 bool checkZeroLength = true;
2011
2012 // But if the array length is constant, we can suppress that.
2013 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
2014 // ...and if it's constant zero, we can just skip the entire thing.
2015 if (constLength->isZero()) return;
2016 checkZeroLength = false;
2017 }
2018
John McCall7f416cc2015-09-08 08:05:57 +00002019 llvm::Value *begin = addr.getPointer();
John McCall82fe67b2011-07-09 01:37:26 +00002020 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
John McCall7f416cc2015-09-08 08:05:57 +00002021 emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00002022 checkZeroLength, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00002023}
2024
John McCall178360e2011-07-11 08:38:19 +00002025/// emitArrayDestroy - Destroys all the elements of the given array,
2026/// beginning from last to first. The array cannot be zero-length.
2027///
2028/// \param begin - a type* denoting the first element of the array
2029/// \param end - a type* denoting one past the end of the array
NAKAMURA Takumiff7a9252015-09-08 09:42:41 +00002030/// \param elementType - the element type of the array
John McCall178360e2011-07-11 08:38:19 +00002031/// \param destroyer - the function to call to destroy elements
2032/// \param useEHCleanup - whether to push an EH cleanup to destroy
2033/// the remaining elements in case the destruction of a single
2034/// element throws
John McCall82fe67b2011-07-09 01:37:26 +00002035void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
2036 llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00002037 QualType elementType,
2038 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00002039 Destroyer *destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00002040 bool checkZeroLength,
John McCall178360e2011-07-11 08:38:19 +00002041 bool useEHCleanup) {
John McCall7f416cc2015-09-08 08:05:57 +00002042 assert(!elementType->isArrayType());
John McCall82fe67b2011-07-09 01:37:26 +00002043
2044 // The basic structure here is a do-while loop, because we don't
2045 // need to check for the zero-element case.
2046 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
2047 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
2048
John McCall97eab0a2011-07-13 08:09:46 +00002049 if (checkZeroLength) {
2050 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
2051 "arraydestroy.isempty");
2052 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
2053 }
2054
John McCall82fe67b2011-07-09 01:37:26 +00002055 // Enter the loop body, making that address the current address.
2056 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
2057 EmitBlock(bodyBB);
2058 llvm::PHINode *elementPast =
2059 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
2060 elementPast->addIncoming(end, entryBB);
2061
2062 // Shift the address back by one element.
2063 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
2064 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
2065 "arraydestroy.element");
2066
John McCall178360e2011-07-11 08:38:19 +00002067 if (useEHCleanup)
John McCall7f416cc2015-09-08 08:05:57 +00002068 pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
2069 destroyer);
John McCall178360e2011-07-11 08:38:19 +00002070
John McCall82fe67b2011-07-09 01:37:26 +00002071 // Perform the actual destruction there.
John McCall7f416cc2015-09-08 08:05:57 +00002072 destroyer(*this, Address(element, elementAlign), elementType);
John McCall82fe67b2011-07-09 01:37:26 +00002073
John McCall178360e2011-07-11 08:38:19 +00002074 if (useEHCleanup)
2075 PopCleanupBlock();
2076
John McCall82fe67b2011-07-09 01:37:26 +00002077 // Check whether we've reached the end.
2078 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
2079 Builder.CreateCondBr(done, doneBB, bodyBB);
2080 elementPast->addIncoming(element, Builder.GetInsertBlock());
2081
2082 // Done.
2083 EmitBlock(doneBB);
2084}
2085
John McCall178360e2011-07-11 08:38:19 +00002086/// Perform partial array destruction as if in an EH cleanup. Unlike
2087/// emitArrayDestroy, the element type here may still be an array type.
John McCall178360e2011-07-11 08:38:19 +00002088static void emitPartialArrayDestroy(CodeGenFunction &CGF,
2089 llvm::Value *begin, llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00002090 QualType type, CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00002091 CodeGenFunction::Destroyer *destroyer) {
John McCall178360e2011-07-11 08:38:19 +00002092 // If the element type is itself an array, drill down.
John McCall97eab0a2011-07-13 08:09:46 +00002093 unsigned arrayDepth = 0;
John McCall178360e2011-07-11 08:38:19 +00002094 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
2095 // VLAs don't require a GEP index to walk into.
2096 if (!isa<VariableArrayType>(arrayType))
John McCall97eab0a2011-07-13 08:09:46 +00002097 arrayDepth++;
John McCall178360e2011-07-11 08:38:19 +00002098 type = arrayType->getElementType();
2099 }
John McCall97eab0a2011-07-13 08:09:46 +00002100
2101 if (arrayDepth) {
John McCallf0f0b7a2015-09-14 18:57:08 +00002102 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
John McCall97eab0a2011-07-13 08:09:46 +00002103
John McCallf0f0b7a2015-09-14 18:57:08 +00002104 SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
Jay Foad040dd822011-07-22 08:16:57 +00002105 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
2106 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
John McCall178360e2011-07-11 08:38:19 +00002107 }
2108
John McCall97eab0a2011-07-13 08:09:46 +00002109 // Destroy the array. We don't ever need an EH cleanup because we
2110 // assume that we're in an EH cleanup ourselves, so a throwing
2111 // destructor causes an immediate terminate.
John McCall7f416cc2015-09-08 08:05:57 +00002112 CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00002113 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
John McCall178360e2011-07-11 08:38:19 +00002114}
2115
John McCall82fe67b2011-07-09 01:37:26 +00002116namespace {
John McCall178360e2011-07-11 08:38:19 +00002117 /// RegularPartialArrayDestroy - a cleanup which performs a partial
2118 /// array destroy where the end pointer is regularly determined and
2119 /// does not need to be loaded from a local.
David Blaikie7e70d682015-08-18 22:40:54 +00002120 class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall178360e2011-07-11 08:38:19 +00002121 llvm::Value *ArrayBegin;
2122 llvm::Value *ArrayEnd;
2123 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00002124 CodeGenFunction::Destroyer *Destroyer;
John McCall7f416cc2015-09-08 08:05:57 +00002125 CharUnits ElementAlign;
John McCall178360e2011-07-11 08:38:19 +00002126 public:
2127 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00002128 QualType elementType, CharUnits elementAlign,
John McCall178360e2011-07-11 08:38:19 +00002129 CodeGenFunction::Destroyer *destroyer)
2130 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
John McCall7f416cc2015-09-08 08:05:57 +00002131 ElementType(elementType), Destroyer(destroyer),
2132 ElementAlign(elementAlign) {}
John McCall178360e2011-07-11 08:38:19 +00002133
Craig Topper4f12f102014-03-12 06:41:41 +00002134 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +00002135 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00002136 ElementType, ElementAlign, Destroyer);
John McCall178360e2011-07-11 08:38:19 +00002137 }
2138 };
2139
2140 /// IrregularPartialArrayDestroy - a cleanup which performs a
2141 /// partial array destroy where the end pointer is irregularly
2142 /// determined and must be loaded from a local.
David Blaikie7e70d682015-08-18 22:40:54 +00002143 class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall82fe67b2011-07-09 01:37:26 +00002144 llvm::Value *ArrayBegin;
John McCall7f416cc2015-09-08 08:05:57 +00002145 Address ArrayEndPointer;
John McCall82fe67b2011-07-09 01:37:26 +00002146 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00002147 CodeGenFunction::Destroyer *Destroyer;
John McCall7f416cc2015-09-08 08:05:57 +00002148 CharUnits ElementAlign;
John McCall82fe67b2011-07-09 01:37:26 +00002149 public:
John McCall178360e2011-07-11 08:38:19 +00002150 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00002151 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00002152 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00002153 CharUnits elementAlign,
John McCall178360e2011-07-11 08:38:19 +00002154 CodeGenFunction::Destroyer *destroyer)
John McCall82fe67b2011-07-09 01:37:26 +00002155 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
John McCall7f416cc2015-09-08 08:05:57 +00002156 ElementType(elementType), Destroyer(destroyer),
2157 ElementAlign(elementAlign) {}
John McCall82fe67b2011-07-09 01:37:26 +00002158
Craig Topper4f12f102014-03-12 06:41:41 +00002159 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall82fe67b2011-07-09 01:37:26 +00002160 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
John McCall178360e2011-07-11 08:38:19 +00002161 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00002162 ElementType, ElementAlign, Destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00002163 }
2164 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002165} // end anonymous namespace
John McCall82fe67b2011-07-09 01:37:26 +00002166
John McCall178360e2011-07-11 08:38:19 +00002167/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
John McCall82fe67b2011-07-09 01:37:26 +00002168/// already-constructed elements of the given array. The cleanup
John McCall178360e2011-07-11 08:38:19 +00002169/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00002170///
John McCall82fe67b2011-07-09 01:37:26 +00002171/// \param elementType - the immediate element type of the array;
2172/// possibly still an array type
John McCall4bd0fb12011-07-12 16:41:08 +00002173void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00002174 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00002175 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00002176 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00002177 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00002178 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
2179 arrayBegin, arrayEndPointer,
John McCall7f416cc2015-09-08 08:05:57 +00002180 elementType, elementAlign,
2181 destroyer);
John McCall178360e2011-07-11 08:38:19 +00002182}
2183
2184/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
2185/// already-constructed elements of the given array. The cleanup
2186/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00002187///
John McCall178360e2011-07-11 08:38:19 +00002188/// \param elementType - the immediate element type of the array;
2189/// possibly still an array type
John McCall178360e2011-07-11 08:38:19 +00002190void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
2191 llvm::Value *arrayEnd,
2192 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00002193 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00002194 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00002195 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
John McCall178360e2011-07-11 08:38:19 +00002196 arrayBegin, arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00002197 elementType, elementAlign,
2198 destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00002199}
2200
Nadav Rotem1da30942013-03-23 06:43:35 +00002201/// Lazily declare the @llvm.lifetime.start intrinsic.
2202llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
Matt Arsenaultd9729492017-04-10 20:18:45 +00002203 if (LifetimeStartFn)
2204 return LifetimeStartFn;
Nadav Rotem1da30942013-03-23 06:43:35 +00002205 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
Yaxun Liu7f7f3232017-04-17 20:03:11 +00002206 llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);
Nadav Rotem1da30942013-03-23 06:43:35 +00002207 return LifetimeStartFn;
2208}
2209
2210/// Lazily declare the @llvm.lifetime.end intrinsic.
2211llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
Matt Arsenaultd9729492017-04-10 20:18:45 +00002212 if (LifetimeEndFn)
2213 return LifetimeEndFn;
Nadav Rotem1da30942013-03-23 06:43:35 +00002214 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
Yaxun Liu7f7f3232017-04-17 20:03:11 +00002215 llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);
Nadav Rotem1da30942013-03-23 06:43:35 +00002216 return LifetimeEndFn;
2217}
2218
John McCall31168b02011-06-15 23:02:42 +00002219namespace {
2220 /// A cleanup to perform a release of an object at the end of a
2221 /// function. This is used to balance out the incoming +1 of a
2222 /// ns_consumed argument when we can't reasonably do that just by
2223 /// not doing the initial retain for a __block argument.
David Blaikie7e70d682015-08-18 22:40:54 +00002224 struct ConsumeARCParameter final : EHScopeStack::Cleanup {
John McCallcdda29c2013-03-13 03:10:54 +00002225 ConsumeARCParameter(llvm::Value *param,
2226 ARCPreciseLifetime_t precise)
2227 : Param(param), Precise(precise) {}
John McCall31168b02011-06-15 23:02:42 +00002228
2229 llvm::Value *Param;
John McCallcdda29c2013-03-13 03:10:54 +00002230 ARCPreciseLifetime_t Precise;
John McCall31168b02011-06-15 23:02:42 +00002231
Craig Topper4f12f102014-03-12 06:41:41 +00002232 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00002233 CGF.EmitARCRelease(Param, Precise);
John McCall31168b02011-06-15 23:02:42 +00002234 }
2235 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002236} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00002237
Mike Stump11289f42009-09-09 15:08:12 +00002238/// Emit an alloca (or GlobalValue depending on target)
Chris Lattnerb781dc792008-05-08 05:58:21 +00002239/// for the specified parameter and set up LocalDeclMap.
John McCall7f416cc2015-09-08 08:05:57 +00002240void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
2241 unsigned ArgNo) {
Daniel Dunbara94ecd22008-08-16 03:19:19 +00002242 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Guptad7959242008-10-31 09:52:39 +00002243 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbara94ecd22008-08-16 03:19:19 +00002244 "Invalid argument to EmitParmDecl");
John McCall147d0212011-02-22 22:38:33 +00002245
John McCall7f416cc2015-09-08 08:05:57 +00002246 Arg.getAnyValue()->setName(D.getName());
John McCall147d0212011-02-22 22:38:33 +00002247
Adrian Prantl51936dd2013-03-14 17:53:33 +00002248 QualType Ty = D.getType();
2249
John McCall147d0212011-02-22 22:38:33 +00002250 // Use better IR generation for certain implicit parameters.
John McCall7f416cc2015-09-08 08:05:57 +00002251 if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
John McCall147d0212011-02-22 22:38:33 +00002252 // The only implicit argument a block has is its literal.
Saleem Abdulrasoolc1b46382018-02-21 21:47:51 +00002253 // This may be passed as an inalloca'ed value on Windows x86.
John McCall147d0212011-02-22 22:38:33 +00002254 if (BlockInfo) {
Saleem Abdulrasoolc1b46382018-02-21 21:47:51 +00002255 llvm::Value *V = Arg.isIndirect()
2256 ? Builder.CreateLoad(Arg.getIndirectAddress())
2257 : Arg.getDirectValue();
2258 setBlockContextParameter(IPD, ArgNo, V);
John McCall147d0212011-02-22 22:38:33 +00002259 return;
2260 }
2261 }
2262
John McCall7f416cc2015-09-08 08:05:57 +00002263 Address DeclPtr = Address::invalid();
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002264 bool DoStore = false;
2265 bool IsScalar = hasScalarEvaluationKind(Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002266 // If we already have a pointer to the argument, reuse the input pointer.
John McCall7f416cc2015-09-08 08:05:57 +00002267 if (Arg.isIndirect()) {
2268 DeclPtr = Arg.getIndirectAddress();
Reid Kleckner5e8edba2014-04-02 00:16:53 +00002269 // If we have a prettier pointer type at this point, bitcast to that.
John McCall7f416cc2015-09-08 08:05:57 +00002270 unsigned AS = DeclPtr.getType()->getAddressSpace();
Reid Kleckner5e8edba2014-04-02 00:16:53 +00002271 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
John McCall7f416cc2015-09-08 08:05:57 +00002272 if (DeclPtr.getType() != IRTy)
2273 DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
Yaxun Liu5b330e82018-03-15 15:25:19 +00002274 // Indirect argument is in alloca address space, which may be different
2275 // from the default address space.
2276 auto AllocaAS = CGM.getASTAllocaAddressSpace();
2277 auto *V = DeclPtr.getPointer();
2278 auto SrcLangAS = getLangOpts().OpenCL ? LangAS::opencl_private : AllocaAS;
2279 auto DestLangAS =
2280 getLangOpts().OpenCL ? LangAS::opencl_private : LangAS::Default;
2281 if (SrcLangAS != DestLangAS) {
2282 assert(getContext().getTargetAddressSpace(SrcLangAS) ==
2283 CGM.getDataLayout().getAllocaAddrSpace());
2284 auto DestAS = getContext().getTargetAddressSpace(DestLangAS);
2285 auto *T = V->getType()->getPointerElementType()->getPointerTo(DestAS);
2286 DeclPtr = Address(getTargetHooks().performAddrSpaceCast(
2287 *this, V, SrcLangAS, DestLangAS, T, true),
2288 DeclPtr.getAlignment());
2289 }
John McCall7f416cc2015-09-08 08:05:57 +00002290
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002291 // Push a destructor cleanup for this parameter if the ABI requires it.
Reid Kleckner19819442014-07-25 21:39:46 +00002292 // Don't push a cleanup in a thunk for a method that will also emit a
2293 // cleanup.
Akira Hatanaka85282972018-05-15 21:00:30 +00002294 if (hasAggregateEvaluationKind(Ty) && !CurFuncIsThunk &&
2295 Ty->getAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
Akira Hatanaka7275da02018-02-28 07:15:55 +00002296 if (QualType::DestructionKind DtorKind = Ty.isDestructedType()) {
2297 assert((DtorKind == QualType::DK_cxx_destructor ||
2298 DtorKind == QualType::DK_nontrivial_c_struct) &&
2299 "unexpected destructor type");
2300 pushDestroy(DtorKind, DeclPtr, Ty);
Akira Hatanakaccda3d22018-04-27 06:57:00 +00002301 CalleeDestructedParamCleanups[cast<ParmVarDecl>(&D)] =
2302 EHStack.stable_begin();
Akira Hatanaka7275da02018-02-28 07:15:55 +00002303 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002304 }
Chris Lattner53621a52007-06-13 20:44:40 +00002305 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002306 // Check if the parameter address is controlled by OpenMP runtime.
2307 Address OpenMPLocalAddr =
2308 getLangOpts().OpenMP
2309 ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
2310 : Address::invalid();
2311 if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
2312 DeclPtr = OpenMPLocalAddr;
2313 } else {
2314 // Otherwise, create a temporary to hold the value.
2315 DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
2316 D.getName() + ".addr");
2317 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002318 DoStore = true;
2319 }
Mike Stump11289f42009-09-09 15:08:12 +00002320
John McCall7f416cc2015-09-08 08:05:57 +00002321 llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
2322
2323 LValue lv = MakeAddrLValue(DeclPtr, Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002324 if (IsScalar) {
John McCall31168b02011-06-15 23:02:42 +00002325 Qualifiers qs = Ty.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00002326 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
2327 // We honor __attribute__((ns_consumed)) for types with lifetime.
2328 // For __strong, it's handled by just skipping the initial retain;
2329 // otherwise we have to balance out the initial +1 with an extra
2330 // cleanup to do the release at the end of the function.
2331 bool isConsumed = D.hasAttr<NSConsumedAttr>();
2332
Erik Pilkington1e368822019-01-04 18:33:06 +00002333 // If a parameter is pseudo-strong then we can omit the implicit retain.
John McCalld4631322011-06-17 06:42:21 +00002334 if (D.isARCPseudoStrong()) {
Erik Pilkington1e368822019-01-04 18:33:06 +00002335 assert(lt == Qualifiers::OCL_Strong &&
2336 "pseudo-strong variable isn't strong?");
2337 assert(qs.hasConst() && "pseudo-strong variable should be const!");
John McCall31168b02011-06-15 23:02:42 +00002338 lt = Qualifiers::OCL_ExplicitNone;
2339 }
2340
Saleem Abdulrasoolda6784e2017-06-27 18:37:51 +00002341 // Load objects passed indirectly.
2342 if (Arg.isIndirect() && !ArgVal)
2343 ArgVal = Builder.CreateLoad(DeclPtr);
2344
John McCall31168b02011-06-15 23:02:42 +00002345 if (lt == Qualifiers::OCL_Strong) {
Fariborz Jahanian134cec62013-02-21 00:40:10 +00002346 if (!isConsumed) {
2347 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2348 // use objc_storeStrong(&dest, value) for retaining the
2349 // object. But first, store a null into 'dest' because
2350 // objc_storeStrong attempts to release its old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002351 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
Fariborz Jahanian134cec62013-02-21 00:40:10 +00002352 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
John McCall7f416cc2015-09-08 08:05:57 +00002353 EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002354 DoStore = false;
Fariborz Jahanian134cec62013-02-21 00:40:10 +00002355 }
2356 else
John McCall31168b02011-06-15 23:02:42 +00002357 // Don't use objc_retainBlock for block pointers, because we
2358 // don't want to Block_copy something just because we got it
2359 // as a parameter.
John McCall7f416cc2015-09-08 08:05:57 +00002360 ArgVal = EmitARCRetainNonBlock(ArgVal);
Fariborz Jahanian134cec62013-02-21 00:40:10 +00002361 }
John McCall31168b02011-06-15 23:02:42 +00002362 } else {
2363 // Push the cleanup for a consumed parameter.
John McCallcdda29c2013-03-13 03:10:54 +00002364 if (isConsumed) {
2365 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
2366 ? ARCPreciseLifetime : ARCImpreciseLifetime);
John McCall7f416cc2015-09-08 08:05:57 +00002367 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
John McCallcdda29c2013-03-13 03:10:54 +00002368 precise);
2369 }
John McCall31168b02011-06-15 23:02:42 +00002370
2371 if (lt == Qualifiers::OCL_Weak) {
John McCall7f416cc2015-09-08 08:05:57 +00002372 EmitARCInitWeak(DeclPtr, ArgVal);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002373 DoStore = false; // The weak init is a store, no need to do two.
John McCall31168b02011-06-15 23:02:42 +00002374 }
2375 }
2376
2377 // Enter the cleanup scope.
2378 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
2379 }
Chris Lattner53621a52007-06-13 20:44:40 +00002380 }
2381
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002382 // Store the initial value into the alloca.
2383 if (DoStore)
John McCall7f416cc2015-09-08 08:05:57 +00002384 EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002385
John McCall7f416cc2015-09-08 08:05:57 +00002386 setAddrOfLocalVar(&D, DeclPtr);
Sanjiv Gupta18de6242008-05-30 10:30:31 +00002387
2388 // Emit debug info for param declaration.
Alexey Samsonov74a38682012-05-04 07:39:27 +00002389 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00002390 if (CGM.getCodeGenOpts().getDebugInfo() >=
2391 codegenoptions::LimitedDebugInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00002392 DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00002393 }
2394 }
Julien Lerouge5a6b6982011-09-09 22:41:49 +00002395
2396 if (D.hasAttr<AnnotateAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00002397 EmitVarAnnotations(&D, DeclPtr.getPointer());
Vedant Kumar42c17ec2017-03-14 01:56:34 +00002398
2399 // We can only check return value nullability if all arguments to the
2400 // function satisfy their nullability preconditions. This makes it necessary
2401 // to emit null checks for args in the function body itself.
2402 if (requiresReturnValueNullabilityCheck()) {
2403 auto Nullability = Ty->getNullability(getContext());
2404 if (Nullability && *Nullability == NullabilityKind::NonNull) {
2405 SanitizerScope SanScope(this);
2406 RetValNullabilityPrecondition =
2407 Builder.CreateAnd(RetValNullabilityPrecondition,
2408 Builder.CreateIsNotNull(Arg.getAnyValue()));
2409 }
2410 }
Chris Lattner53621a52007-06-13 20:44:40 +00002411}
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002412
Alexey Bataevc5b1d322016-03-04 09:22:22 +00002413void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
2414 CodeGenFunction *CGF) {
2415 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
2416 return;
2417 getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
2418}
Kelvin Li1408f912018-09-26 04:28:39 +00002419
2420void CodeGenModule::EmitOMPRequiresDecl(const OMPRequiresDecl *D) {
Patrick Lyster8f7f5862018-11-19 15:09:33 +00002421 getOpenMPRuntime().checkArchForUnifiedAddressing(*this, D);
Kelvin Li1408f912018-09-26 04:28:39 +00002422}