blob: 72fd902ecee27739a22a3d1ba4a78ec7d4e05d99 [file] [log] [blame]
Chris Lattner84915fa2007-06-02 04:16:21 +00001//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner84915fa2007-06-02 04:16:21 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This contains code to emit Decl nodes as LLVM code.
10//
11//===----------------------------------------------------------------------===//
12
John McCall7f416cc2015-09-08 08:05:57 +000013#include "CGBlocks.h"
Reid Klecknere5a321b2016-09-07 18:21:30 +000014#include "CGCXXABI.h"
David Majnemerdc012fa2015-04-22 21:38:15 +000015#include "CGCleanup.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "CGDebugInfo.h"
Peter Collingbourne2dbb7082011-09-19 21:14:35 +000017#include "CGOpenCLRuntime.h"
Alexey Bataevc5b1d322016-03-04 09:22:22 +000018#include "CGOpenMPRuntime.h"
Yaxun Liu6d96f1632017-05-18 18:51:09 +000019#include "CodeGenFunction.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "CodeGenModule.h"
John McCallde0fe072017-08-15 21:42:52 +000021#include "ConstantEmitter.h"
Yaxun Liu6d96f1632017-05-18 18:51:09 +000022#include "TargetInfo.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000023#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000024#include "clang/AST/CharUnits.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000025#include "clang/AST/Decl.h"
Anders Carlsson4c03d982008-08-25 01:38:19 +000026#include "clang/AST/DeclObjC.h"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000027#include "clang/AST/DeclOpenMP.h"
Richard Trieu63688182018-12-11 03:18:39 +000028#include "clang/Basic/CodeGenOptions.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000029#include "clang/Basic/SourceManager.h"
Chris Lattnerb781dc792008-05-08 05:58:21 +000030#include "clang/Basic/TargetInfo.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000031#include "clang/CodeGen/CGFunctionInfo.h"
JF Bastien2f0582f2018-09-21 13:54:09 +000032#include "llvm/Analysis/ValueTracking.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000033#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/GlobalVariable.h"
35#include "llvm/IR/Intrinsics.h"
36#include "llvm/IR/Type.h"
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +000037
Chris Lattner84915fa2007-06-02 04:16:21 +000038using namespace clang;
39using namespace CodeGen;
40
Chris Lattner1ad38f82007-06-09 01:20:56 +000041void CodeGenFunction::EmitDecl(const Decl &D) {
Chris Lattner1ad38f82007-06-09 01:20:56 +000042 switch (D.getKind()) {
David Majnemerd9b1a4f2015-11-04 03:40:30 +000043 case Decl::BuiltinTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000044 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +000045 case Decl::ExternCContext:
Douglas Gregor19043f02010-04-23 02:02:43 +000046 case Decl::Namespace:
47 case Decl::UnresolvedUsingTypename:
48 case Decl::ClassTemplateSpecialization:
49 case Decl::ClassTemplatePartialSpecialization:
Larisse Voufo39a1e502013-08-06 01:03:05 +000050 case Decl::VarTemplateSpecialization:
51 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor19043f02010-04-23 02:02:43 +000052 case Decl::TemplateTypeParm:
53 case Decl::UnresolvedUsingValue:
Alexis Hunted053252010-05-30 07:21:58 +000054 case Decl::NonTypeTemplateParm:
Richard Smithbc491202017-02-17 20:05:37 +000055 case Decl::CXXDeductionGuide:
Douglas Gregor19043f02010-04-23 02:02:43 +000056 case Decl::CXXMethod:
57 case Decl::CXXConstructor:
58 case Decl::CXXDestructor:
59 case Decl::CXXConversion:
60 case Decl::Field:
John McCall5e77d762013-04-16 07:28:30 +000061 case Decl::MSProperty:
Francois Pichetdf946c32010-11-21 06:49:41 +000062 case Decl::IndirectField:
Douglas Gregor19043f02010-04-23 02:02:43 +000063 case Decl::ObjCIvar:
Eric Christopher31ab1302011-08-23 22:38:00 +000064 case Decl::ObjCAtDefsField:
Chris Lattnerba9dddb2007-10-08 21:37:32 +000065 case Decl::ParmVar:
Douglas Gregor19043f02010-04-23 02:02:43 +000066 case Decl::ImplicitParam:
67 case Decl::ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +000068 case Decl::VarTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000069 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +000070 case Decl::TypeAliasTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000071 case Decl::TemplateTemplateParm:
72 case Decl::ObjCMethod:
73 case Decl::ObjCCategory:
74 case Decl::ObjCProtocol:
75 case Decl::ObjCInterface:
76 case Decl::ObjCCategoryImpl:
77 case Decl::ObjCImplementation:
78 case Decl::ObjCProperty:
79 case Decl::ObjCCompatibleAlias:
Nico Weber66220292016-03-02 17:28:48 +000080 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +000081 case Decl::PragmaDetectMismatch:
Abramo Bagnarad7340582010-06-05 05:09:32 +000082 case Decl::AccessSpec:
Douglas Gregor19043f02010-04-23 02:02:43 +000083 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +000084 case Decl::Export:
Douglas Gregor19043f02010-04-23 02:02:43 +000085 case Decl::ObjCPropertyImpl:
Douglas Gregor19043f02010-04-23 02:02:43 +000086 case Decl::FileScopeAsm:
87 case Decl::Friend:
88 case Decl::FriendTemplate:
89 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +000090 case Decl::Captured:
Francois Pichet00c7e6c2011-08-14 03:52:19 +000091 case Decl::ClassScopeFunctionSpecialization:
David Blaikiebd483762013-05-20 04:58:53 +000092 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +000093 case Decl::ConstructorUsingShadow:
Douglas Gregor85f3f952015-07-07 03:57:15 +000094 case Decl::ObjCTypeParam:
Richard Smithda383632016-08-15 01:33:41 +000095 case Decl::Binding:
David Blaikie83d382b2011-09-23 05:06:16 +000096 llvm_unreachable("Declaration should not be in declstmts!");
Amjad Abouddc4531e2016-04-30 01:44:38 +000097 case Decl::Function: // void X();
98 case Decl::Record: // struct/union/class X;
99 case Decl::Enum: // enum X;
100 case Decl::EnumConstant: // enum ? { X = ? }
101 case Decl::CXXRecord: // struct/union/class X; [C++]
Anders Carlssonce2cd012009-12-03 17:26:31 +0000102 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
Chris Lattner43e7f312011-02-18 02:08:43 +0000103 case Decl::Label: // __label__ x;
Douglas Gregorba345522011-12-02 23:23:56 +0000104 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +0000105 case Decl::OMPThreadPrivate:
Alexey Bataev4244be22016-02-11 05:35:55 +0000106 case Decl::OMPCapturedExpr:
Kelvin Li1408f912018-09-26 04:28:39 +0000107 case Decl::OMPRequires:
Michael Han84324352013-02-22 17:15:32 +0000108 case Decl::Empty:
Chris Lattner84915fa2007-06-02 04:16:21 +0000109 // None of these decls require codegen support.
110 return;
David Blaikieb7d1e1f2013-02-02 00:39:32 +0000111
David Blaikief121b932013-05-20 22:50:41 +0000112 case Decl::NamespaceAlias:
113 if (CGDebugInfo *DI = getDebugInfo())
Amjad Abouddc4531e2016-04-30 01:44:38 +0000114 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
David Blaikief121b932013-05-20 22:50:41 +0000115 return;
David Blaikiebd483762013-05-20 04:58:53 +0000116 case Decl::Using: // using X; [C++]
117 if (CGDebugInfo *DI = getDebugInfo())
Amjad Abouddc4531e2016-04-30 01:44:38 +0000118 DI->EmitUsingDecl(cast<UsingDecl>(D));
David Blaikiebd483762013-05-20 04:58:53 +0000119 return;
Richard Smith151c4562016-12-20 21:35:28 +0000120 case Decl::UsingPack:
121 for (auto *Using : cast<UsingPackDecl>(D).expansions())
122 EmitDecl(*Using);
123 return;
David Blaikie9f88fe82013-04-22 06:13:21 +0000124 case Decl::UsingDirective: // using namespace X; [C++]
125 if (CGDebugInfo *DI = getDebugInfo())
126 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
127 return;
Richard Smithbdb84f32016-07-22 23:36:59 +0000128 case Decl::Var:
129 case Decl::Decomposition: {
Daniel Dunbara7998072008-08-29 17:28:43 +0000130 const VarDecl &VD = cast<VarDecl>(D);
John McCall1c9c3fd2010-10-15 04:57:14 +0000131 assert(VD.isLocalVarDecl() &&
Daniel Dunbara7998072008-08-29 17:28:43 +0000132 "Should not see file-scope variables inside a function!");
Richard Smithda383632016-08-15 01:33:41 +0000133 EmitVarDecl(VD);
134 if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
135 for (auto *B : DD->bindings())
136 if (auto *HD = B->getHoldingVar())
137 EmitVarDecl(*HD);
138 return;
Chris Lattner84915fa2007-06-02 04:16:21 +0000139 }
Mike Stump11289f42009-09-09 15:08:12 +0000140
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000141 case Decl::OMPDeclareReduction:
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000142 return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000143
Michael Kruse251e1482019-02-01 20:25:04 +0000144 case Decl::OMPDeclareMapper:
145 return CGM.EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(&D), this);
146
Richard Smithdda56e42011-04-15 14:24:37 +0000147 case Decl::Typedef: // typedef int X;
148 case Decl::TypeAlias: { // using X = int; [C++0x]
149 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000150 QualType Ty = TD.getUnderlyingType();
Mike Stump11289f42009-09-09 15:08:12 +0000151
Anders Carlsson5d985f52008-12-20 21:51:53 +0000152 if (Ty->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000153 EmitVariablyModifiedType(Ty);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000154 }
Daniel Dunbara7998072008-08-29 17:28:43 +0000155 }
Chris Lattner84915fa2007-06-02 04:16:21 +0000156}
Chris Lattner03df1222007-06-02 04:53:11 +0000157
John McCall1c9c3fd2010-10-15 04:57:14 +0000158/// EmitVarDecl - This method handles emission of any variable declaration
Chris Lattner03df1222007-06-02 04:53:11 +0000159/// inside a function, including static vars etc.
John McCall1c9c3fd2010-10-15 04:57:14 +0000160void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Yaxun Liu4f33b3d2017-05-15 14:47:47 +0000161 if (D.hasExternalStorage())
162 // Don't emit it now, allow it to be emitted lazily on its first use.
163 return;
164
165 // Some function-scope variable does not have static storage but still
166 // needs to be emitted like a static variable, e.g. a function-scope
167 // variable in constant address space in OpenCL.
168 if (D.getStorageDuration() != SD_Automatic) {
Alexey Baderbed40092017-11-15 11:38:17 +0000169 // Static sampler variables translated to function calls.
170 if (D.getType()->isSamplerT())
171 return;
172
Eric Christopher31ab1302011-08-23 22:38:00 +0000173 llvm::GlobalValue::LinkageTypes Linkage =
David Majnemer27d69db2014-04-28 22:17:59 +0000174 CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000175
David Majnemer27d69db2014-04-28 22:17:59 +0000176 // FIXME: We need to force the emission/use of a guard variable for
177 // some variables even if we can constant-evaluate them because
178 // we can't guarantee every translation unit will constant-evaluate them.
Eric Christopher31ab1302011-08-23 22:38:00 +0000179
John McCall1c9c3fd2010-10-15 04:57:14 +0000180 return EmitStaticVarDecl(D, Linkage);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000181 }
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000182
Anastasia Stulovabcea6962015-09-30 14:08:20 +0000183 if (D.getType().getAddressSpace() == LangAS::opencl_local)
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000184 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
185
186 assert(D.hasLocalStorage());
187 return EmitAutoVarDecl(D);
Chris Lattner03df1222007-06-02 04:53:11 +0000188}
189
Reid Kleckner453e0562014-10-08 01:07:54 +0000190static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
191 if (CGM.getLangOpts().CPlusPlus)
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000192 return CGM.getMangledName(&D).str();
193
Reid Kleckner453e0562014-10-08 01:07:54 +0000194 // If this isn't C++, we don't need a mangled name, just a pretty one.
195 assert(!D.isExternallyVisible() && "name shouldn't matter");
196 std::string ContextName;
197 const DeclContext *DC = D.getDeclContext();
Alexey Bataev43f74392015-05-07 06:28:46 +0000198 if (auto *CD = dyn_cast<CapturedDecl>(DC))
199 DC = cast<DeclContext>(CD->getNonClosureContext());
Reid Kleckner453e0562014-10-08 01:07:54 +0000200 if (const auto *FD = dyn_cast<FunctionDecl>(DC))
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000201 ContextName = CGM.getMangledName(FD);
Reid Kleckner453e0562014-10-08 01:07:54 +0000202 else if (const auto *BD = dyn_cast<BlockDecl>(DC))
203 ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
204 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
205 ContextName = OMD->getSelector().getAsString();
Chris Lattnere99c1102009-12-05 08:22:11 +0000206 else
David Blaikie83d382b2011-09-23 05:06:16 +0000207 llvm_unreachable("Unknown context for static var decl");
Eric Christopher31ab1302011-08-23 22:38:00 +0000208
Reid Kleckner453e0562014-10-08 01:07:54 +0000209 ContextName += "." + D.getNameAsString();
210 return ContextName;
Chris Lattnere99c1102009-12-05 08:22:11 +0000211}
212
Reid Kleckner453e0562014-10-08 01:07:54 +0000213llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
214 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
215 // In general, we don't always emit static var decls once before we reference
216 // them. It is possible to reference them before emitting the function that
217 // contains them, and it is possible to emit the containing function multiple
218 // times.
219 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
220 return ExistingGV;
221
Chris Lattnerfc4379f2008-04-06 23:10:54 +0000222 QualType Ty = D.getType();
Eli Friedmana682d392008-02-15 12:20:59 +0000223 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begemanfaae0812008-04-19 04:17:09 +0000224
Benjamin Kramerddbb2b82011-11-20 21:05:04 +0000225 // Use the label if the variable is renamed with the asm-label extension.
226 std::string Name;
Benjamin Kramer5642e192011-11-21 15:47:23 +0000227 if (D.hasAttr<AsmLabelAttr>())
Reid Kleckner453e0562014-10-08 01:07:54 +0000228 Name = getMangledName(&D);
Benjamin Kramer5642e192011-11-21 15:47:23 +0000229 else
Reid Kleckner453e0562014-10-08 01:07:54 +0000230 Name = getStaticDeclName(*this, D);
Nate Begemanfaae0812008-04-19 04:17:09 +0000231
Reid Kleckner453e0562014-10-08 01:07:54 +0000232 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
Alexander Richardson6d989432017-10-15 18:48:14 +0000233 LangAS AS = GetGlobalVarAddressSpace(&D);
Yaxun Liucbf647c2017-07-08 13:24:52 +0000234 unsigned TargetAS = getContext().getTargetAddressSpace(AS);
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000235
Yaxun Liua64a4912018-04-02 17:38:24 +0000236 // OpenCL variables in local address space and CUDA shared
237 // variables cannot have an initializer.
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000238 llvm::Constant *Init = nullptr;
Yaxun Liua64a4912018-04-02 17:38:24 +0000239 if (Ty.getAddressSpace() == LangAS::opencl_local ||
240 D.hasAttr<CUDASharedAttr>())
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000241 Init = llvm::UndefValue::get(LTy);
Yaxun Liua64a4912018-04-02 17:38:24 +0000242 else
243 Init = EmitNullConstant(Ty);
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000244
Yaxun Liucbf647c2017-07-08 13:24:52 +0000245 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
246 getModule(), LTy, Ty.isConstant(getContext()), Linkage, Init, Name,
247 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
Ken Dyck160146e2010-01-27 17:10:57 +0000248 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000249
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +0000250 if (supportsCOMDAT() && GV->isWeakForLinker())
251 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Rafael Espindola0d4fb982015-01-12 22:13:53 +0000252
Richard Smithfd3834f2013-04-13 02:43:54 +0000253 if (D.getTLSKind())
Reid Kleckner453e0562014-10-08 01:07:54 +0000254 setTLSMode(GV, D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000255
Rafael Espindola922f2aa2018-02-23 19:30:48 +0000256 setGVProperties(GV, &D);
257
Eli Benderskycb399432014-03-24 22:05:38 +0000258 // Make sure the result is of the correct type.
Alexander Richardson6d989432017-10-15 18:48:14 +0000259 LangAS ExpectedAS = Ty.getAddressSpace();
Reid Kleckner453e0562014-10-08 01:07:54 +0000260 llvm::Constant *Addr = GV;
Yaxun Liucbf647c2017-07-08 13:24:52 +0000261 if (AS != ExpectedAS) {
262 Addr = getTargetCodeGenInfo().performAddrSpaceCast(
263 *this, GV, AS, ExpectedAS,
264 LTy->getPointerTo(getContext().getTargetAddressSpace(ExpectedAS)));
Eli Benderskycb399432014-03-24 22:05:38 +0000265 }
266
Reid Kleckner453e0562014-10-08 01:07:54 +0000267 setStaticLocalDeclAddress(&D, Addr);
268
269 // Ensure that the static local gets initialized by making sure the parent
270 // function gets emitted eventually.
271 const Decl *DC = cast<Decl>(D.getDeclContext());
272
273 // We can't name blocks or captured statements directly, so try to emit their
274 // parents.
275 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
276 DC = DC->getNonClosureContext();
277 // FIXME: Ensure that global blocks get emitted.
278 if (!DC)
279 return Addr;
280 }
281
282 GlobalDecl GD;
283 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
284 GD = GlobalDecl(CD, Ctor_Base);
285 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
286 GD = GlobalDecl(DD, Dtor_Base);
287 else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
288 GD = GlobalDecl(FD);
289 else {
290 // Don't do anything for Obj-C method decls or global closures. We should
291 // never defer them.
292 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
293 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +0000294 if (GD.getDecl()) {
295 // Disable emission of the parent function for the OpenMP device codegen.
296 CGOpenMPRuntime::DisableAutoDeclareTargetRAII NoDeclTarget(*this);
Reid Kleckner453e0562014-10-08 01:07:54 +0000297 (void)GetAddrOfGlobal(GD);
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +0000298 }
Reid Kleckner453e0562014-10-08 01:07:54 +0000299
300 return Addr;
Daniel Dunbar22a87f92009-02-25 19:24:29 +0000301}
302
Richard Smith6331c402012-02-13 22:16:19 +0000303/// hasNontrivialDestruction - Determine whether a type's destruction is
304/// non-trivial. If so, and the variable uses static initialization, we must
305/// register its destructor to run on exit.
306static bool hasNontrivialDestruction(QualType T) {
307 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
308 return RD && !RD->hasTrivialDestructor();
309}
310
Chandler Carruth84537952012-03-30 19:44:53 +0000311/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
312/// global variable that has already been created for it. If the initializer
313/// has a different type than GV does, this may free GV and return a different
314/// one. Otherwise it just returns GV.
315llvm::GlobalVariable *
John McCall1c9c3fd2010-10-15 04:57:14 +0000316CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
Chandler Carruth84537952012-03-30 19:44:53 +0000317 llvm::GlobalVariable *GV) {
John McCallde0fe072017-08-15 21:42:52 +0000318 ConstantEmitter emitter(*this);
319 llvm::Constant *Init = emitter.tryEmitForInitializer(D);
John McCall70013b62010-07-15 23:40:35 +0000320
Chris Lattnere99c1102009-12-05 08:22:11 +0000321 // If constant emission failed, then this should be a C++ static
322 // initializer.
Chandler Carruth84537952012-03-30 19:44:53 +0000323 if (!Init) {
Richard Smith9c6890a2012-11-01 22:30:59 +0000324 if (!getLangOpts().CPlusPlus)
Chris Lattnere99c1102009-12-05 08:22:11 +0000325 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
Matthias Braun44bfe032017-01-10 17:43:01 +0000326 else if (HaveInsertPoint()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000327 // Since we have a static initializer, this global variable can't
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000328 // be constant.
Chandler Carruth84537952012-03-30 19:44:53 +0000329 GV->setConstant(false);
John McCall68ff0372010-09-08 01:44:27 +0000330
Chandler Carruth84537952012-03-30 19:44:53 +0000331 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000332 }
Chandler Carruth84537952012-03-30 19:44:53 +0000333 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000334 }
John McCall70013b62010-07-15 23:40:35 +0000335
Chris Lattnere99c1102009-12-05 08:22:11 +0000336 // The initializer may differ in type from the global. Rewrite
337 // the global to match the initializer. (We have to do this
338 // because some types, like unions, can't be completely represented
339 // in the LLVM type system.)
Chandler Carruth84537952012-03-30 19:44:53 +0000340 if (GV->getType()->getElementType() != Init->getType()) {
341 llvm::GlobalVariable *OldGV = GV;
342
343 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
344 OldGV->isConstant(),
345 OldGV->getLinkage(), Init, "",
346 /*InsertBefore*/ OldGV,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +0000347 OldGV->getThreadLocalMode(),
Chandler Carruth84537952012-03-30 19:44:53 +0000348 CGM.getContext().getTargetAddressSpace(D.getType()));
349 GV->setVisibility(OldGV->getVisibility());
Rafael Espindola699f5d62018-02-07 22:15:33 +0000350 GV->setDSOLocal(OldGV->isDSOLocal());
Reid Klecknereab97d32015-07-20 20:35:30 +0000351 GV->setComdat(OldGV->getComdat());
Eric Christopher31ab1302011-08-23 22:38:00 +0000352
Chris Lattnere99c1102009-12-05 08:22:11 +0000353 // Steal the name of the old global
Chandler Carruth84537952012-03-30 19:44:53 +0000354 GV->takeName(OldGV);
Eric Christopher31ab1302011-08-23 22:38:00 +0000355
Chris Lattnere99c1102009-12-05 08:22:11 +0000356 // Replace all uses of the old global with the new global
Chandler Carruth84537952012-03-30 19:44:53 +0000357 llvm::Constant *NewPtrForOldDecl =
358 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
359 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eric Christopher31ab1302011-08-23 22:38:00 +0000360
Chris Lattnere99c1102009-12-05 08:22:11 +0000361 // Erase the old global, since it is no longer used.
Chandler Carruth84537952012-03-30 19:44:53 +0000362 OldGV->eraseFromParent();
Chris Lattnere99c1102009-12-05 08:22:11 +0000363 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000364
Chandler Carruth84537952012-03-30 19:44:53 +0000365 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
366 GV->setInitializer(Init);
Richard Smith6331c402012-02-13 22:16:19 +0000367
John McCallde0fe072017-08-15 21:42:52 +0000368 emitter.finalize(GV);
369
Matthias Braun44bfe032017-01-10 17:43:01 +0000370 if (hasNontrivialDestruction(D.getType()) && HaveInsertPoint()) {
Richard Smith6331c402012-02-13 22:16:19 +0000371 // We have a constant initializer, but a nontrivial destructor. We still
372 // need to perform a guarded "initialization" in order to register the
Richard Smithe070fd22012-02-17 06:48:11 +0000373 // destructor.
Chandler Carruth84537952012-03-30 19:44:53 +0000374 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
Richard Smith6331c402012-02-13 22:16:19 +0000375 }
376
Chandler Carruth84537952012-03-30 19:44:53 +0000377 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000378}
379
John McCall1c9c3fd2010-10-15 04:57:14 +0000380void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000381 llvm::GlobalValue::LinkageTypes Linkage) {
John McCallb88a5662012-03-30 21:00:39 +0000382 // Check to see if we already have a global variable for this
383 // declaration. This can happen when double-emitting function
384 // bodies, e.g. with complete and base constructors.
Reid Kleckner453e0562014-10-08 01:07:54 +0000385 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
John McCall7f416cc2015-09-08 08:05:57 +0000386 CharUnits alignment = getContext().getDeclAlign(&D);
Daniel Dunbara374e602009-02-25 19:45:19 +0000387
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000388 // Store into LocalDeclMap before generating initializer to handle
389 // circular references.
John McCall7f416cc2015-09-08 08:05:57 +0000390 setAddrOfLocalVar(&D, Address(addr, alignment));
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000391
John McCall4a39ab82010-05-04 20:45:42 +0000392 // We can't have a VLA here, but we can have a pointer to a VLA,
393 // even though that doesn't really make any sense.
Eli Friedmanbc633be2009-04-20 03:54:15 +0000394 // Make sure to evaluate VLA bounds now so that we have them for later.
395 if (D.getType()->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000396 EmitVariablyModifiedType(D.getType());
Eric Christopher31ab1302011-08-23 22:38:00 +0000397
John McCallb88a5662012-03-30 21:00:39 +0000398 // Save the type in case adding the initializer forces a type change.
399 llvm::Type *expectedType = addr->getType();
Eli Friedmanbc633be2009-04-20 03:54:15 +0000400
Eli Benderskycb399432014-03-24 22:05:38 +0000401 llvm::GlobalVariable *var =
402 cast<llvm::GlobalVariable>(addr->stripPointerCasts());
Artem Belevich4d430ba2016-05-09 22:09:56 +0000403
404 // CUDA's local and local static __shared__ variables should not
405 // have any non-empty initializers. This is ensured by Sema.
406 // Whatever initializer such variable may have when it gets here is
407 // a no-op and should not be emitted.
408 bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
409 D.hasAttr<CUDASharedAttr>();
Chris Lattnere99c1102009-12-05 08:22:11 +0000410 // If this value has an initializer, emit it.
Artem Belevich4d430ba2016-05-09 22:09:56 +0000411 if (D.getInit() && !isCudaSharedVar)
John McCallb88a5662012-03-30 21:00:39 +0000412 var = AddInitializerToStaticVarDecl(D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000413
John McCall7f416cc2015-09-08 08:05:57 +0000414 var->setAlignment(alignment.getQuantity());
Chris Lattner4d941092010-03-10 23:59:59 +0000415
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000416 if (D.hasAttr<AnnotateAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000417 CGM.AddGlobalAnnotations(&D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000418
Javed Absar2a67c9e2017-06-05 10:11:57 +0000419 if (auto *SA = D.getAttr<PragmaClangBSSSectionAttr>())
420 var->addAttribute("bss-section", SA->getName());
421 if (auto *SA = D.getAttr<PragmaClangDataSectionAttr>())
422 var->addAttribute("data-section", SA->getName());
423 if (auto *SA = D.getAttr<PragmaClangRodataSectionAttr>())
424 var->addAttribute("rodata-section", SA->getName());
425
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000426 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000427 var->setSection(SA->getName());
Mike Stump11289f42009-09-09 15:08:12 +0000428
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000429 if (D.hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +0000430 CGM.addUsedGlobal(var);
Daniel Dunbar128a1382009-02-13 22:08:43 +0000431
Chandler Carruth84537952012-03-30 19:44:53 +0000432 // We may have to cast the constant because of the initializer
433 // mismatch above.
434 //
435 // FIXME: It is really dangerous to store this in the map; if anyone
436 // RAUW's the GV uses of this constant will be invalid.
Eli Benderskycb399432014-03-24 22:05:38 +0000437 llvm::Constant *castedAddr =
438 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
John McCall7f416cc2015-09-08 08:05:57 +0000439 if (var != castedAddr)
440 LocalDeclMap.find(&D)->second = Address(castedAddr, alignment);
John McCallb88a5662012-03-30 21:00:39 +0000441 CGM.setStaticLocalDeclAddress(&D, castedAddr);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000442
Alexey Samsonov4b8de112014-08-01 21:35:28 +0000443 CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000444
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000445 // Emit global variable debug descriptor for static vars.
Anders Carlsson63784f42009-02-13 08:11:52 +0000446 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov74a38682012-05-04 07:39:27 +0000447 if (DI &&
Benjamin Kramer8c305922016-02-02 11:06:51 +0000448 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
Daniel Dunbarb9fd9022008-10-17 16:15:48 +0000449 DI->setLocation(D.getLocation());
John McCallb88a5662012-03-30 21:00:39 +0000450 DI->EmitGlobalVariable(var, &D);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000451 }
Anders Carlssonf94cd1f2007-10-17 00:52:43 +0000452}
Mike Stump11289f42009-09-09 15:08:12 +0000453
John McCall2b7fc382010-07-13 20:32:21 +0000454namespace {
David Blaikie7e70d682015-08-18 22:40:54 +0000455 struct DestroyObject final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000456 DestroyObject(Address addr, QualType type,
John McCall178360e2011-07-11 08:38:19 +0000457 CodeGenFunction::Destroyer *destroyer,
458 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +0000459 : addr(addr), type(type), destroyer(destroyer),
John McCall178360e2011-07-11 08:38:19 +0000460 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall2b7fc382010-07-13 20:32:21 +0000461
John McCall7f416cc2015-09-08 08:05:57 +0000462 Address addr;
John McCall82fe67b2011-07-09 01:37:26 +0000463 QualType type;
Peter Collingbourne1425b452012-01-26 03:33:36 +0000464 CodeGenFunction::Destroyer *destroyer;
John McCall178360e2011-07-11 08:38:19 +0000465 bool useEHCleanupForArray;
John McCall2b7fc382010-07-13 20:32:21 +0000466
Craig Topper4f12f102014-03-12 06:41:41 +0000467 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +0000468 // Don't use an EH cleanup recursively from an EH cleanup.
John McCall30317fd2011-07-12 20:27:29 +0000469 bool useEHCleanupForArray =
470 flags.isForNormalCleanup() && this->useEHCleanupForArray;
John McCall178360e2011-07-11 08:38:19 +0000471
472 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
John McCall2b7fc382010-07-13 20:32:21 +0000473 }
474 };
475
Akira Hatanaka673af7a2018-03-29 17:56:24 +0000476 template <class Derived>
477 struct DestroyNRVOVariable : EHScopeStack::Cleanup {
478 DestroyNRVOVariable(Address addr, llvm::Value *NRVOFlag)
479 : NRVOFlag(NRVOFlag), Loc(addr) {}
John McCall2b7fc382010-07-13 20:32:21 +0000480
John McCall2b7fc382010-07-13 20:32:21 +0000481 llvm::Value *NRVOFlag;
John McCall7f416cc2015-09-08 08:05:57 +0000482 Address Loc;
John McCall2b7fc382010-07-13 20:32:21 +0000483
Craig Topper4f12f102014-03-12 06:41:41 +0000484 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall2b7fc382010-07-13 20:32:21 +0000485 // Along the exceptions path we always execute the dtor.
John McCall30317fd2011-07-12 20:27:29 +0000486 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
John McCall2b7fc382010-07-13 20:32:21 +0000487
Craig Topper8a13c412014-05-21 05:09:00 +0000488 llvm::BasicBlock *SkipDtorBB = nullptr;
John McCall2b7fc382010-07-13 20:32:21 +0000489 if (NRVO) {
490 // If we exited via NRVO, we skip the destructor call.
491 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
492 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
John McCall7f416cc2015-09-08 08:05:57 +0000493 llvm::Value *DidNRVO =
494 CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
John McCall2b7fc382010-07-13 20:32:21 +0000495 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
496 CGF.EmitBlock(RunDtorBB);
497 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000498
Akira Hatanaka673af7a2018-03-29 17:56:24 +0000499 static_cast<Derived *>(this)->emitDestructorCall(CGF);
John McCall2b7fc382010-07-13 20:32:21 +0000500
501 if (NRVO) CGF.EmitBlock(SkipDtorBB);
502 }
Akira Hatanaka673af7a2018-03-29 17:56:24 +0000503
504 virtual ~DestroyNRVOVariable() = default;
505 };
506
507 struct DestroyNRVOVariableCXX final
508 : DestroyNRVOVariable<DestroyNRVOVariableCXX> {
509 DestroyNRVOVariableCXX(Address addr, const CXXDestructorDecl *Dtor,
510 llvm::Value *NRVOFlag)
511 : DestroyNRVOVariable<DestroyNRVOVariableCXX>(addr, NRVOFlag),
512 Dtor(Dtor) {}
513
514 const CXXDestructorDecl *Dtor;
515
516 void emitDestructorCall(CodeGenFunction &CGF) {
517 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
518 /*ForVirtualBase=*/false,
519 /*Delegating=*/false, Loc);
520 }
521 };
522
523 struct DestroyNRVOVariableC final
524 : DestroyNRVOVariable<DestroyNRVOVariableC> {
525 DestroyNRVOVariableC(Address addr, llvm::Value *NRVOFlag, QualType Ty)
526 : DestroyNRVOVariable<DestroyNRVOVariableC>(addr, NRVOFlag), Ty(Ty) {}
527
528 QualType Ty;
529
530 void emitDestructorCall(CodeGenFunction &CGF) {
531 CGF.destroyNonTrivialCStruct(CGF, Loc, Ty);
532 }
John McCall2b7fc382010-07-13 20:32:21 +0000533 };
John McCall2b7fc382010-07-13 20:32:21 +0000534
David Blaikie7e70d682015-08-18 22:40:54 +0000535 struct CallStackRestore final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000536 Address Stack;
537 CallStackRestore(Address Stack) : Stack(Stack) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000538 void Emit(CodeGenFunction &CGF, Flags flags) override {
Benjamin Kramer76399eb2011-09-27 21:06:10 +0000539 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
John McCalla464ff92010-07-21 06:13:08 +0000540 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
541 CGF.Builder.CreateCall(F, V);
542 }
543 };
544
David Blaikie7e70d682015-08-18 22:40:54 +0000545 struct ExtendGCLifetime final : EHScopeStack::Cleanup {
John McCall1bd25562011-06-24 23:21:27 +0000546 const VarDecl &Var;
547 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
548
Craig Topper4f12f102014-03-12 06:41:41 +0000549 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1bd25562011-06-24 23:21:27 +0000550 // Compute the address of the local variable, in case it's a
551 // byref or something.
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000552 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
John McCall113bee02012-03-10 09:33:50 +0000553 Var.getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +0000554 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
555 SourceLocation());
John McCall1bd25562011-06-24 23:21:27 +0000556 CGF.EmitExtendGCLifetime(value);
557 }
558 };
559
David Blaikie7e70d682015-08-18 22:40:54 +0000560 struct CallCleanupFunction final : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000561 llvm::Constant *CleanupFn;
562 const CGFunctionInfo &FnInfo;
John McCalla464ff92010-07-21 06:13:08 +0000563 const VarDecl &Var;
Eric Christopher31ab1302011-08-23 22:38:00 +0000564
John McCalla464ff92010-07-21 06:13:08 +0000565 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCallc533cb72011-02-22 06:44:22 +0000566 const VarDecl *Var)
567 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalla464ff92010-07-21 06:13:08 +0000568
Craig Topper4f12f102014-03-12 06:41:41 +0000569 void Emit(CodeGenFunction &CGF, Flags flags) override {
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000570 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
John McCall113bee02012-03-10 09:33:50 +0000571 Var.getType(), VK_LValue, SourceLocation());
John McCallc533cb72011-02-22 06:44:22 +0000572 // Compute the address of the local variable, in case it's a byref
573 // or something.
John McCall7f416cc2015-09-08 08:05:57 +0000574 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer();
John McCallc533cb72011-02-22 06:44:22 +0000575
John McCalla464ff92010-07-21 06:13:08 +0000576 // In some cases, the type of the function argument will be different from
577 // the type of the pointer. An example of this is
578 // void f(void* arg);
579 // __attribute__((cleanup(f))) void *g;
580 //
581 // To fix this we insert a bitcast here.
582 QualType ArgTy = FnInfo.arg_begin()->type;
583 llvm::Value *Arg =
584 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
585
586 CallArgList Args;
Eli Friedman43dca6a2011-05-02 17:57:46 +0000587 Args.add(RValue::get(Arg),
588 CGF.getContext().getPointerType(Var.getType()));
John McCallb92ab1a2016-10-26 23:46:34 +0000589 auto Callee = CGCallee::forDirect(CleanupFn);
590 CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
John McCalla464ff92010-07-21 06:13:08 +0000591 }
592 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000593} // end anonymous namespace
John McCalla464ff92010-07-21 06:13:08 +0000594
John McCall31168b02011-06-15 23:02:42 +0000595/// EmitAutoVarWithLifetime - Does the setup required for an automatic
596/// variable with lifetime.
597static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
John McCall7f416cc2015-09-08 08:05:57 +0000598 Address addr,
John McCall31168b02011-06-15 23:02:42 +0000599 Qualifiers::ObjCLifetime lifetime) {
600 switch (lifetime) {
601 case Qualifiers::OCL_None:
602 llvm_unreachable("present but none");
603
604 case Qualifiers::OCL_ExplicitNone:
605 // nothing to do
606 break;
607
608 case Qualifiers::OCL_Strong: {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000609 CodeGenFunction::Destroyer *destroyer =
John McCall4bd0fb12011-07-12 16:41:08 +0000610 (var.hasAttr<ObjCPreciseLifetimeAttr>()
611 ? CodeGenFunction::destroyARCStrongPrecise
612 : CodeGenFunction::destroyARCStrongImprecise);
613
614 CleanupKind cleanupKind = CGF.getARCCleanupKind();
615 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
616 cleanupKind & EHCleanup);
John McCall31168b02011-06-15 23:02:42 +0000617 break;
618 }
619 case Qualifiers::OCL_Autoreleasing:
620 // nothing to do
621 break;
Eric Christopher31ab1302011-08-23 22:38:00 +0000622
John McCall31168b02011-06-15 23:02:42 +0000623 case Qualifiers::OCL_Weak:
624 // __weak objects always get EH cleanups; otherwise, exceptions
625 // could cause really nasty crashes instead of mere leaks.
John McCall4bd0fb12011-07-12 16:41:08 +0000626 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
627 CodeGenFunction::destroyARCWeak,
628 /*useEHCleanup*/ true);
John McCall31168b02011-06-15 23:02:42 +0000629 break;
630 }
631}
632
633static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
634 if (const Expr *e = dyn_cast<Expr>(s)) {
635 // Skip the most common kinds of expressions that make
636 // hierarchy-walking expensive.
637 s = e = e->IgnoreParenCasts();
638
639 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
640 return (ref->getDecl() == &var);
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000641 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
642 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +0000643 for (const auto &I : block->captures()) {
644 if (I.getVariable() == &var)
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000645 return true;
646 }
647 }
John McCall31168b02011-06-15 23:02:42 +0000648 }
649
Benjamin Kramer642f1732015-07-02 21:03:14 +0000650 for (const Stmt *SubStmt : s->children())
651 // SubStmt might be null; as in missing decl or conditional of an if-stmt.
652 if (SubStmt && isAccessedBy(var, SubStmt))
John McCall31168b02011-06-15 23:02:42 +0000653 return true;
654
655 return false;
656}
657
658static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
659 if (!decl) return false;
660 if (!isa<VarDecl>(decl)) return false;
661 const VarDecl *var = cast<VarDecl>(decl);
662 return isAccessedBy(*var, e);
663}
664
John McCallf8a9b662015-10-21 18:06:31 +0000665static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
666 const LValue &destLV, const Expr *init) {
John McCall0204e342015-11-16 22:11:41 +0000667 bool needsCast = false;
668
John McCallf8a9b662015-10-21 18:06:31 +0000669 while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
670 switch (castExpr->getCastKind()) {
671 // Look through casts that don't require representation changes.
672 case CK_NoOp:
673 case CK_BitCast:
674 case CK_BlockPointerToObjCPointerCast:
John McCall0204e342015-11-16 22:11:41 +0000675 needsCast = true;
John McCallf8a9b662015-10-21 18:06:31 +0000676 break;
677
678 // If we find an l-value to r-value cast from a __weak variable,
679 // emit this operation as a copy or move.
680 case CK_LValueToRValue: {
681 const Expr *srcExpr = castExpr->getSubExpr();
682 if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
683 return false;
684
685 // Emit the source l-value.
686 LValue srcLV = CGF.EmitLValue(srcExpr);
687
John McCall0204e342015-11-16 22:11:41 +0000688 // Handle a formal type change to avoid asserting.
689 auto srcAddr = srcLV.getAddress();
690 if (needsCast) {
691 srcAddr = CGF.Builder.CreateElementBitCast(srcAddr,
692 destLV.getAddress().getElementType());
693 }
694
John McCallf8a9b662015-10-21 18:06:31 +0000695 // If it was an l-value, use objc_copyWeak.
696 if (srcExpr->getValueKind() == VK_LValue) {
John McCall0204e342015-11-16 22:11:41 +0000697 CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr);
John McCallf8a9b662015-10-21 18:06:31 +0000698 } else {
699 assert(srcExpr->getValueKind() == VK_XValue);
John McCall0204e342015-11-16 22:11:41 +0000700 CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr);
John McCallf8a9b662015-10-21 18:06:31 +0000701 }
702 return true;
703 }
704
705 // Stop at anything else.
706 default:
707 return false;
708 }
709
710 init = castExpr->getSubExpr();
John McCallf8a9b662015-10-21 18:06:31 +0000711 }
712 return false;
713}
714
John McCall1553b192011-06-16 04:16:24 +0000715static void drillIntoBlockVariable(CodeGenFunction &CGF,
716 LValue &lvalue,
717 const VarDecl *var) {
John McCall7f416cc2015-09-08 08:05:57 +0000718 lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var));
John McCall1553b192011-06-16 04:16:24 +0000719}
720
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000721void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS,
722 SourceLocation Loc) {
723 if (!SanOpts.has(SanitizerKind::NullabilityAssign))
724 return;
725
726 auto Nullability = LHS.getType()->getNullability(getContext());
727 if (!Nullability || *Nullability != NullabilityKind::NonNull)
728 return;
729
730 // Check if the right hand side of the assignment is nonnull, if the left
731 // hand side must be nonnull.
732 SanitizerScope SanScope(this);
733 llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS);
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000734 llvm::Constant *StaticData[] = {
735 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(LHS.getType()),
Simon Pilgrim2df19982017-03-14 21:43:52 +0000736 llvm::ConstantInt::get(Int8Ty, 0), // The LogAlignment info is unused.
Vedant Kumar2b9f48a2017-03-14 16:48:29 +0000737 llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)};
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000738 EmitCheck({{IsNotNull, SanitizerKind::NullabilityAssign}},
739 SanitizerHandler::TypeMismatch, StaticData, RHS);
740}
741
David Blaikie73ca5692014-12-09 00:32:22 +0000742void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +0000743 LValue lvalue, bool capturedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000744 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +0000745 if (!lifetime) {
746 llvm::Value *value = EmitScalarExpr(init);
John McCall1553b192011-06-16 04:16:24 +0000747 if (capturedByInit)
748 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000749 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
David Blaikie66e41972015-01-14 07:38:27 +0000750 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
John McCall31168b02011-06-15 23:02:42 +0000751 return;
752 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000753
Fariborz Jahaniana5a469e2014-03-14 15:40:54 +0000754 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
755 init = DIE->getExpr();
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000756
John McCall31168b02011-06-15 23:02:42 +0000757 // If we're emitting a value with lifetime, we have to do the
758 // initialization *before* we leave the cleanup scopes.
Bill Wendling7c44da22018-10-31 03:48:47 +0000759 if (const FullExpr *fe = dyn_cast<FullExpr>(init)) {
760 enterFullExpression(fe);
761 init = fe->getSubExpr();
John McCall08ef4662011-11-10 08:15:53 +0000762 }
763 CodeGenFunction::RunCleanupsScope Scope(*this);
John McCall31168b02011-06-15 23:02:42 +0000764
765 // We have to maintain the illusion that the variable is
766 // zero-initialized. If the variable might be accessed in its
767 // initializer, zero-initialize before running the initializer, then
768 // actually perform the initialization with an assign.
769 bool accessedByInit = false;
770 if (lifetime != Qualifiers::OCL_ExplicitNone)
John McCallb726a552011-07-28 07:23:35 +0000771 accessedByInit = (capturedByInit || isAccessedBy(D, init));
John McCall31168b02011-06-15 23:02:42 +0000772 if (accessedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000773 LValue tempLV = lvalue;
John McCall31168b02011-06-15 23:02:42 +0000774 // Drill down to the __block object if necessary.
John McCall31168b02011-06-15 23:02:42 +0000775 if (capturedByInit) {
776 // We can use a simple GEP for this because it can't have been
777 // moved yet.
John McCall7f416cc2015-09-08 08:05:57 +0000778 tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(),
779 cast<VarDecl>(D),
780 /*follow*/ false));
John McCall31168b02011-06-15 23:02:42 +0000781 }
782
John McCall7f416cc2015-09-08 08:05:57 +0000783 auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType());
Yaxun Liu402804b2016-12-15 08:09:08 +0000784 llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());
Eric Christopher31ab1302011-08-23 22:38:00 +0000785
John McCall31168b02011-06-15 23:02:42 +0000786 // If __weak, we want to use a barrier under certain conditions.
787 if (lifetime == Qualifiers::OCL_Weak)
John McCall1553b192011-06-16 04:16:24 +0000788 EmitARCInitWeak(tempLV.getAddress(), zero);
John McCall31168b02011-06-15 23:02:42 +0000789
790 // Otherwise just do a simple store.
791 else
David Chisnallfa35df62012-01-16 17:27:18 +0000792 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000793 }
794
795 // Emit the initializer.
Craig Topper8a13c412014-05-21 05:09:00 +0000796 llvm::Value *value = nullptr;
John McCall31168b02011-06-15 23:02:42 +0000797
798 switch (lifetime) {
799 case Qualifiers::OCL_None:
800 llvm_unreachable("present but none");
801
Erik Pilkington1e368822019-01-04 18:33:06 +0000802 case Qualifiers::OCL_Strong: {
803 if (!D || !isa<VarDecl>(D) || !cast<VarDecl>(D)->isARCPseudoStrong()) {
804 value = EmitARCRetainScalarExpr(init);
805 break;
806 }
807 // If D is pseudo-strong, treat it like __unsafe_unretained here. This means
808 // that we omit the retain, and causes non-autoreleased return values to be
809 // immediately released.
810 LLVM_FALLTHROUGH;
811 }
812
John McCall31168b02011-06-15 23:02:42 +0000813 case Qualifiers::OCL_ExplicitNone:
John McCalle399e5b2016-01-27 18:32:30 +0000814 value = EmitARCUnsafeUnretainedScalarExpr(init);
John McCall31168b02011-06-15 23:02:42 +0000815 break;
816
John McCall31168b02011-06-15 23:02:42 +0000817 case Qualifiers::OCL_Weak: {
John McCallf8a9b662015-10-21 18:06:31 +0000818 // If it's not accessed by the initializer, try to emit the
819 // initialization with a copy or move.
820 if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
821 return;
822 }
823
John McCall31168b02011-06-15 23:02:42 +0000824 // No way to optimize a producing initializer into this. It's not
825 // worth optimizing for, because the value will immediately
826 // disappear in the common case.
827 value = EmitScalarExpr(init);
828
John McCall1553b192011-06-16 04:16:24 +0000829 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000830 if (accessedByInit)
John McCall1553b192011-06-16 04:16:24 +0000831 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +0000832 else
John McCall1553b192011-06-16 04:16:24 +0000833 EmitARCInitWeak(lvalue.getAddress(), value);
John McCall31168b02011-06-15 23:02:42 +0000834 return;
835 }
836
837 case Qualifiers::OCL_Autoreleasing:
838 value = EmitARCRetainAutoreleaseScalarExpr(init);
839 break;
840 }
841
John McCall1553b192011-06-16 04:16:24 +0000842 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000843
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000844 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
845
John McCall31168b02011-06-15 23:02:42 +0000846 // If the variable might have been accessed by its initializer, we
847 // might have to initialize with a barrier. We have to do this for
848 // both __weak and __strong, but __weak got filtered out above.
849 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000850 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
David Chisnallfa35df62012-01-16 17:27:18 +0000851 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCallcdda29c2013-03-13 03:10:54 +0000852 EmitARCRelease(oldValue, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +0000853 return;
854 }
855
David Chisnallfa35df62012-01-16 17:27:18 +0000856 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000857}
Chris Lattnerb85025f2010-12-01 02:05:19 +0000858
JF Bastiened92f602018-07-20 23:37:12 +0000859/// Decide whether we can emit the non-zero parts of the specified initializer
860/// with equal or fewer than NumStores scalar stores.
861static bool canEmitInitWithFewStoresAfterBZero(llvm::Constant *Init,
862 unsigned &NumStores) {
Chris Lattnere6af8862010-12-02 01:58:41 +0000863 // Zero and Undef never requires any extra stores.
864 if (isa<llvm::ConstantAggregateZero>(Init) ||
865 isa<llvm::ConstantPointerNull>(Init) ||
866 isa<llvm::UndefValue>(Init))
867 return true;
868 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
869 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
870 isa<llvm::ConstantExpr>(Init))
871 return Init->isNullValue() || NumStores--;
872
873 // See if we can emit each element.
874 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
875 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
876 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
JF Bastiened92f602018-07-20 23:37:12 +0000877 if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
Chris Lattnere6af8862010-12-02 01:58:41 +0000878 return false;
879 }
880 return true;
881 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000882
Chris Lattner236b3572012-01-31 04:36:19 +0000883 if (llvm::ConstantDataSequential *CDS =
884 dyn_cast<llvm::ConstantDataSequential>(Init)) {
885 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
886 llvm::Constant *Elt = CDS->getElementAsConstant(i);
JF Bastiened92f602018-07-20 23:37:12 +0000887 if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
Chris Lattner236b3572012-01-31 04:36:19 +0000888 return false;
889 }
890 return true;
891 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000892
Chris Lattnerb85025f2010-12-01 02:05:19 +0000893 // Anything else is hard and scary.
894 return false;
895}
896
JF Bastiened92f602018-07-20 23:37:12 +0000897/// For inits that canEmitInitWithFewStoresAfterBZero returned true for, emit
898/// the scalar stores that would be required.
899static void emitStoresForInitAfterBZero(CodeGenModule &CGM,
900 llvm::Constant *Init, Address Loc,
901 bool isVolatile, CGBuilderTy &Builder) {
Benjamin Kramer29f9a002012-08-27 22:07:02 +0000902 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
JF Bastiened92f602018-07-20 23:37:12 +0000903 "called emitStoresForInitAfterBZero for zero or undef value.");
Eric Christopher31ab1302011-08-23 22:38:00 +0000904
Chris Lattnere6af8862010-12-02 01:58:41 +0000905 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
906 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
907 isa<llvm::ConstantExpr>(Init)) {
JF Bastien9aab85a2018-07-13 20:33:23 +0000908 Builder.CreateStore(Init, Loc, isVolatile);
Chris Lattner236b3572012-01-31 04:36:19 +0000909 return;
910 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000911
912 if (llvm::ConstantDataSequential *CDS =
913 dyn_cast<llvm::ConstantDataSequential>(Init)) {
Chris Lattner236b3572012-01-31 04:36:19 +0000914 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
915 llvm::Constant *Elt = CDS->getElementAsConstant(i);
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000916
917 // If necessary, get a pointer to the element and emit it.
918 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
JF Bastiened92f602018-07-20 23:37:12 +0000919 emitStoresForInitAfterBZero(
JF Bastien9aab85a2018-07-13 20:33:23 +0000920 CGM, Elt,
921 Builder.CreateConstInBoundsGEP2_32(Loc, 0, i, CGM.getDataLayout()),
David Blaikie17ea2662015-04-04 21:07:17 +0000922 isVolatile, Builder);
Chris Lattner236b3572012-01-31 04:36:19 +0000923 }
Chris Lattnere6af8862010-12-02 01:58:41 +0000924 return;
925 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000926
Chris Lattnere6af8862010-12-02 01:58:41 +0000927 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
928 "Unknown value type!");
Eric Christopher31ab1302011-08-23 22:38:00 +0000929
Chris Lattnere6af8862010-12-02 01:58:41 +0000930 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
931 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000932
933 // If necessary, get a pointer to the element and emit it.
934 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
JF Bastiened92f602018-07-20 23:37:12 +0000935 emitStoresForInitAfterBZero(
JF Bastien9aab85a2018-07-13 20:33:23 +0000936 CGM, Elt,
937 Builder.CreateConstInBoundsGEP2_32(Loc, 0, i, CGM.getDataLayout()),
David Blaikie17ea2662015-04-04 21:07:17 +0000938 isVolatile, Builder);
Chris Lattnere6af8862010-12-02 01:58:41 +0000939 }
Chris Lattnerb85025f2010-12-01 02:05:19 +0000940}
941
JF Bastiened92f602018-07-20 23:37:12 +0000942/// Decide whether we should use bzero plus some stores to initialize a local
943/// variable instead of using a memcpy from a constant global. It is beneficial
944/// to use bzero if the global is all zeros, or mostly zeros and large.
945static bool shouldUseBZeroPlusStoresToInitialize(llvm::Constant *Init,
946 uint64_t GlobalSize) {
947 // If a global is all zeros, always use a bzero.
Chris Lattnerb85025f2010-12-01 02:05:19 +0000948 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
949
Chris Lattnerb85025f2010-12-01 02:05:19 +0000950 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
951 // do it if it will require 6 or fewer scalar stores.
952 // TODO: Should budget depends on the size? Avoiding a large global warrants
953 // plopping in more stores.
954 unsigned StoreBudget = 6;
955 uint64_t SizeLimit = 32;
Eric Christopher31ab1302011-08-23 22:38:00 +0000956
957 return GlobalSize > SizeLimit &&
JF Bastiened92f602018-07-20 23:37:12 +0000958 canEmitInitWithFewStoresAfterBZero(Init, StoreBudget);
Chris Lattnerb85025f2010-12-01 02:05:19 +0000959}
960
JF Bastien65089292018-07-25 04:29:03 +0000961/// Decide whether we should use memset to initialize a local variable instead
962/// of using a memcpy from a constant global. Assumes we've already decided to
963/// not user bzero.
964/// FIXME We could be more clever, as we are for bzero above, and generate
965/// memset followed by stores. It's unclear that's worth the effort.
JF Bastien2f0582f2018-09-21 13:54:09 +0000966static llvm::Value *shouldUseMemSetToInitialize(llvm::Constant *Init,
967 uint64_t GlobalSize) {
JF Bastien65089292018-07-25 04:29:03 +0000968 uint64_t SizeLimit = 32;
969 if (GlobalSize <= SizeLimit)
JF Bastien2f0582f2018-09-21 13:54:09 +0000970 return nullptr;
971 return llvm::isBytewiseValue(Init);
JF Bastien65089292018-07-25 04:29:03 +0000972}
973
JF Bastien14daa202018-12-18 05:12:21 +0000974static llvm::Constant *patternFor(CodeGenModule &CGM, llvm::Type *Ty) {
975 // The following value is a guaranteed unmappable pointer value and has a
976 // repeated byte-pattern which makes it easier to synthesize. We use it for
977 // pointers as well as integers so that aggregates are likely to be
978 // initialized with this repeated value.
979 constexpr uint64_t LargeValue = 0xAAAAAAAAAAAAAAAAull;
980 // For 32-bit platforms it's a bit trickier because, across systems, only the
981 // zero page can reasonably be expected to be unmapped, and even then we need
982 // a very low address. We use a smaller value, and that value sadly doesn't
983 // have a repeated byte-pattern. We don't use it for integers.
984 constexpr uint32_t SmallValue = 0x000000AA;
985 // Floating-point values are initialized as NaNs because they propagate. Using
986 // a repeated byte pattern means that it will be easier to initialize
987 // all-floating-point aggregates and arrays with memset. Further, aggregates
988 // which mix integral and a few floats might also initialize with memset
989 // followed by a handful of stores for the floats. Using fairly unique NaNs
990 // also means they'll be easier to distinguish in a crash.
991 constexpr bool NegativeNaN = true;
992 constexpr uint64_t NaNPayload = 0xFFFFFFFFFFFFFFFFull;
993 if (Ty->isIntOrIntVectorTy()) {
994 unsigned BitWidth = cast<llvm::IntegerType>(
995 Ty->isVectorTy() ? Ty->getVectorElementType() : Ty)
996 ->getBitWidth();
997 if (BitWidth <= 64)
998 return llvm::ConstantInt::get(Ty, LargeValue);
999 return llvm::ConstantInt::get(
1000 Ty, llvm::APInt::getSplat(BitWidth, llvm::APInt(64, LargeValue)));
1001 }
1002 if (Ty->isPtrOrPtrVectorTy()) {
1003 auto *PtrTy = cast<llvm::PointerType>(
1004 Ty->isVectorTy() ? Ty->getVectorElementType() : Ty);
1005 unsigned PtrWidth = CGM.getContext().getTargetInfo().getPointerWidth(
1006 PtrTy->getAddressSpace());
1007 llvm::Type *IntTy = llvm::IntegerType::get(CGM.getLLVMContext(), PtrWidth);
1008 uint64_t IntValue;
1009 switch (PtrWidth) {
1010 default:
1011 llvm_unreachable("pattern initialization of unsupported pointer width");
1012 case 64:
1013 IntValue = LargeValue;
1014 break;
1015 case 32:
1016 IntValue = SmallValue;
1017 break;
1018 }
1019 auto *Int = llvm::ConstantInt::get(IntTy, IntValue);
1020 return llvm::ConstantExpr::getIntToPtr(Int, PtrTy);
1021 }
1022 if (Ty->isFPOrFPVectorTy()) {
1023 unsigned BitWidth = llvm::APFloat::semanticsSizeInBits(
1024 (Ty->isVectorTy() ? Ty->getVectorElementType() : Ty)
1025 ->getFltSemantics());
1026 llvm::APInt Payload(64, NaNPayload);
1027 if (BitWidth >= 64)
1028 Payload = llvm::APInt::getSplat(BitWidth, Payload);
1029 return llvm::ConstantFP::getQNaN(Ty, NegativeNaN, &Payload);
1030 }
1031 if (Ty->isArrayTy()) {
1032 // Note: this doesn't touch tail padding (at the end of an object, before
1033 // the next array object). It is instead handled by replaceUndef.
1034 auto *ArrTy = cast<llvm::ArrayType>(Ty);
1035 llvm::SmallVector<llvm::Constant *, 8> Element(
1036 ArrTy->getNumElements(), patternFor(CGM, ArrTy->getElementType()));
1037 return llvm::ConstantArray::get(ArrTy, Element);
1038 }
1039
1040 // Note: this doesn't touch struct padding. It will initialize as much union
1041 // padding as is required for the largest type in the union. Padding is
1042 // instead handled by replaceUndef. Stores to structs with volatile members
1043 // don't have a volatile qualifier when initialized according to C++. This is
1044 // fine because stack-based volatiles don't really have volatile semantics
1045 // anyways, and the initialization shouldn't be observable.
1046 auto *StructTy = cast<llvm::StructType>(Ty);
1047 llvm::SmallVector<llvm::Constant *, 8> Struct(StructTy->getNumElements());
1048 for (unsigned El = 0; El != Struct.size(); ++El)
1049 Struct[El] = patternFor(CGM, StructTy->getElementType(El));
1050 return llvm::ConstantStruct::get(StructTy, Struct);
1051}
1052
JF Bastien3a881e62018-11-15 00:19:18 +00001053static Address createUnnamedGlobalFrom(CodeGenModule &CGM, const VarDecl &D,
1054 CGBuilderTy &Builder,
1055 llvm::Constant *Constant,
1056 CharUnits Align) {
1057 auto FunctionName = [&](const DeclContext *DC) -> std::string {
1058 if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
1059 if (const auto *CC = dyn_cast<CXXConstructorDecl>(FD))
1060 return CC->getNameAsString();
1061 if (const auto *CD = dyn_cast<CXXDestructorDecl>(FD))
1062 return CD->getNameAsString();
1063 return CGM.getMangledName(FD);
1064 } else if (const auto *OM = dyn_cast<ObjCMethodDecl>(DC)) {
1065 return OM->getNameAsString();
Mikael Holmenee846762018-11-15 13:01:54 +00001066 } else if (isa<BlockDecl>(DC)) {
JF Bastien3a881e62018-11-15 00:19:18 +00001067 return "<block>";
Mikael Holmenee846762018-11-15 13:01:54 +00001068 } else if (isa<CapturedDecl>(DC)) {
JF Bastien3a881e62018-11-15 00:19:18 +00001069 return "<captured>";
1070 } else {
1071 llvm::llvm_unreachable_internal("expected a function or method");
1072 }
1073 };
1074
1075 auto *Ty = Constant->getType();
1076 bool isConstant = true;
1077 llvm::GlobalVariable *InsertBefore = nullptr;
1078 unsigned AS = CGM.getContext().getTargetAddressSpace(
1079 CGM.getStringLiteralAddressSpace());
1080 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1081 CGM.getModule(), Ty, isConstant, llvm::GlobalValue::PrivateLinkage,
1082 Constant,
1083 "__const." + FunctionName(D.getParentFunctionOrMethod()) + "." +
1084 D.getName(),
1085 InsertBefore, llvm::GlobalValue::NotThreadLocal, AS);
1086 GV->setAlignment(Align.getQuantity());
1087 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1088
1089 Address SrcPtr = Address(GV, Align);
1090 llvm::Type *BP = llvm::PointerType::getInt8PtrTy(CGM.getLLVMContext(), AS);
1091 if (SrcPtr.getType() != BP)
1092 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
1093 return SrcPtr;
1094}
1095
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001096static void emitStoresForConstant(CodeGenModule &CGM, const VarDecl &D,
1097 Address Loc, bool isVolatile,
1098 CGBuilderTy &Builder,
1099 llvm::Constant *constant) {
JF Bastien14daa202018-12-18 05:12:21 +00001100 auto *Ty = constant->getType();
1101 bool isScalar = Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy() ||
1102 Ty->isFPOrFPVectorTy();
1103 if (isScalar) {
1104 Builder.CreateStore(constant, Loc, isVolatile);
1105 return;
1106 }
1107
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001108 auto *Int8Ty = llvm::IntegerType::getInt8Ty(CGM.getLLVMContext());
1109 auto *IntPtrTy = CGM.getDataLayout().getIntPtrType(CGM.getLLVMContext());
1110
1111 // If the initializer is all or mostly the same, codegen with bzero / memset
1112 // then do a few stores afterward.
JF Bastien14daa202018-12-18 05:12:21 +00001113 uint64_t ConstantSize = CGM.getDataLayout().getTypeAllocSize(Ty);
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001114 auto *SizeVal = llvm::ConstantInt::get(IntPtrTy, ConstantSize);
1115 if (shouldUseBZeroPlusStoresToInitialize(constant, ConstantSize)) {
1116 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1117 isVolatile);
1118
1119 bool valueAlreadyCorrect =
1120 constant->isNullValue() || isa<llvm::UndefValue>(constant);
1121 if (!valueAlreadyCorrect) {
JF Bastien14daa202018-12-18 05:12:21 +00001122 Loc = Builder.CreateBitCast(Loc, Ty->getPointerTo(Loc.getAddressSpace()));
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001123 emitStoresForInitAfterBZero(CGM, constant, Loc, isVolatile, Builder);
1124 }
1125 return;
1126 }
1127
JF Bastien2f0582f2018-09-21 13:54:09 +00001128 llvm::Value *Pattern = shouldUseMemSetToInitialize(constant, ConstantSize);
1129 if (Pattern) {
1130 uint64_t Value = 0x00;
1131 if (!isa<llvm::UndefValue>(Pattern)) {
1132 const llvm::APInt &AP = cast<llvm::ConstantInt>(Pattern)->getValue();
1133 assert(AP.getBitWidth() <= 8);
1134 Value = AP.getLimitedValue();
1135 }
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001136 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, Value), SizeVal,
1137 isVolatile);
1138 return;
1139 }
1140
JF Bastien3a881e62018-11-15 00:19:18 +00001141 Builder.CreateMemCpy(
1142 Loc,
1143 createUnnamedGlobalFrom(CGM, D, Builder, constant, Loc.getAlignment()),
1144 SizeVal, isVolatile);
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001145}
1146
JF Bastien14daa202018-12-18 05:12:21 +00001147static void emitStoresForZeroInit(CodeGenModule &CGM, const VarDecl &D,
1148 Address Loc, bool isVolatile,
1149 CGBuilderTy &Builder) {
1150 llvm::Type *ElTy = Loc.getElementType();
1151 llvm::Constant *constant = llvm::Constant::getNullValue(ElTy);
1152 emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant);
1153}
1154
1155static void emitStoresForPatternInit(CodeGenModule &CGM, const VarDecl &D,
1156 Address Loc, bool isVolatile,
1157 CGBuilderTy &Builder) {
1158 llvm::Type *ElTy = Loc.getElementType();
1159 llvm::Constant *constant = patternFor(CGM, ElTy);
1160 assert(!isa<llvm::UndefValue>(constant));
1161 emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant);
1162}
1163
1164static bool containsUndef(llvm::Constant *constant) {
1165 auto *Ty = constant->getType();
1166 if (isa<llvm::UndefValue>(constant))
1167 return true;
1168 if (Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy())
1169 for (llvm::Use &Op : constant->operands())
1170 if (containsUndef(cast<llvm::Constant>(Op)))
1171 return true;
1172 return false;
1173}
1174
1175static llvm::Constant *replaceUndef(llvm::Constant *constant) {
1176 // FIXME: when doing pattern initialization, replace undef with 0xAA instead.
1177 // FIXME: also replace padding between values by creating a new struct type
1178 // which has no padding.
1179 auto *Ty = constant->getType();
1180 if (isa<llvm::UndefValue>(constant))
1181 return llvm::Constant::getNullValue(Ty);
1182 if (!(Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()))
1183 return constant;
1184 if (!containsUndef(constant))
1185 return constant;
1186 llvm::SmallVector<llvm::Constant *, 8> Values(constant->getNumOperands());
1187 for (unsigned Op = 0, NumOp = constant->getNumOperands(); Op != NumOp; ++Op) {
1188 auto *OpValue = cast<llvm::Constant>(constant->getOperand(Op));
1189 Values[Op] = replaceUndef(OpValue);
1190 }
1191 if (Ty->isStructTy())
1192 return llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Values);
1193 if (Ty->isArrayTy())
1194 return llvm::ConstantArray::get(cast<llvm::ArrayType>(Ty), Values);
1195 assert(Ty->isVectorTy());
1196 return llvm::ConstantVector::get(Values);
1197}
1198
Nick Lewycky8a7d90b2010-12-30 20:21:55 +00001199/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Chris Lattner03df1222007-06-02 04:53:11 +00001200/// variable declaration with auto, register, or no storage class specifier.
Chris Lattnerb781dc792008-05-08 05:58:21 +00001201/// These turn into simple stack objects, or GlobalValues depending on target.
John McCallc533cb72011-02-22 06:44:22 +00001202void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
1203 AutoVarEmission emission = EmitAutoVarAlloca(D);
1204 EmitAutoVarInit(emission);
1205 EmitAutoVarCleanups(emission);
1206}
Chris Lattner03df1222007-06-02 04:53:11 +00001207
David Majnemerdc012fa2015-04-22 21:38:15 +00001208/// Emit a lifetime.begin marker if some criteria are satisfied.
1209/// \return a pointer to the temporary size Value if a marker was emitted, null
1210/// otherwise
1211llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
1212 llvm::Value *Addr) {
Vitaly Buka1c943322016-10-26 01:59:57 +00001213 if (!ShouldEmitLifetimeMarkers)
Reid Kleckner1ef49212015-04-23 18:07:13 +00001214 return nullptr;
1215
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001216 assert(Addr->getType()->getPointerAddressSpace() ==
1217 CGM.getDataLayout().getAllocaAddrSpace() &&
1218 "Pointer should be in alloca address space");
David Majnemerdc012fa2015-04-22 21:38:15 +00001219 llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
Yaxun Liu7f7f3232017-04-17 20:03:11 +00001220 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
Alexey Samsonovd918ff62015-06-12 22:31:32 +00001221 llvm::CallInst *C =
1222 Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +00001223 C->setDoesNotThrow();
1224 return SizeV;
1225}
1226
1227void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001228 assert(Addr->getType()->getPointerAddressSpace() ==
1229 CGM.getDataLayout().getAllocaAddrSpace() &&
1230 "Pointer should be in alloca address space");
Yaxun Liu7f7f3232017-04-17 20:03:11 +00001231 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
Alexey Samsonovd918ff62015-06-12 22:31:32 +00001232 llvm::CallInst *C =
1233 Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +00001234 C->setDoesNotThrow();
1235}
1236
Sander de Smalen891af03a2018-02-03 13:55:59 +00001237void CodeGenFunction::EmitAndRegisterVariableArrayDimensions(
1238 CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo) {
1239 // For each dimension stores its QualType and corresponding
1240 // size-expression Value.
1241 SmallVector<CodeGenFunction::VlaSizePair, 4> Dimensions;
Adrian Prantla40cce82018-11-09 19:17:56 +00001242 SmallVector<IdentifierInfo *, 4> VLAExprNames;
Sander de Smalen891af03a2018-02-03 13:55:59 +00001243
1244 // Break down the array into individual dimensions.
1245 QualType Type1D = D.getType();
1246 while (getContext().getAsVariableArrayType(Type1D)) {
1247 auto VlaSize = getVLAElements1D(Type1D);
1248 if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1249 Dimensions.emplace_back(C, Type1D.getUnqualifiedType());
1250 else {
Adrian Prantla40cce82018-11-09 19:17:56 +00001251 // Generate a locally unique name for the size expression.
1252 Twine Name = Twine("__vla_expr") + Twine(VLAExprCounter++);
1253 SmallString<12> Buffer;
1254 StringRef NameRef = Name.toStringRef(Buffer);
1255 auto &Ident = getContext().Idents.getOwn(NameRef);
1256 VLAExprNames.push_back(&Ident);
1257 auto SizeExprAddr =
1258 CreateDefaultAlignTempAlloca(VlaSize.NumElts->getType(), NameRef);
Sander de Smalen891af03a2018-02-03 13:55:59 +00001259 Builder.CreateStore(VlaSize.NumElts, SizeExprAddr);
1260 Dimensions.emplace_back(SizeExprAddr.getPointer(),
1261 Type1D.getUnqualifiedType());
1262 }
1263 Type1D = VlaSize.Type;
1264 }
1265
1266 if (!EmitDebugInfo)
1267 return;
1268
1269 // Register each dimension's size-expression with a DILocalVariable,
1270 // so that it can be used by CGDebugInfo when instantiating a DISubrange
1271 // to describe this array.
Adrian Prantla40cce82018-11-09 19:17:56 +00001272 unsigned NameIdx = 0;
Sander de Smalen891af03a2018-02-03 13:55:59 +00001273 for (auto &VlaSize : Dimensions) {
1274 llvm::Metadata *MD;
1275 if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1276 MD = llvm::ConstantAsMetadata::get(C);
1277 else {
1278 // Create an artificial VarDecl to generate debug info for.
Adrian Prantla40cce82018-11-09 19:17:56 +00001279 IdentifierInfo *NameIdent = VLAExprNames[NameIdx++];
Sander de Smalen891af03a2018-02-03 13:55:59 +00001280 auto VlaExprTy = VlaSize.NumElts->getType()->getPointerElementType();
1281 auto QT = getContext().getIntTypeForBitwidth(
1282 VlaExprTy->getScalarSizeInBits(), false);
1283 auto *ArtificialDecl = VarDecl::Create(
1284 getContext(), const_cast<DeclContext *>(D.getDeclContext()),
Adrian Prantla40cce82018-11-09 19:17:56 +00001285 D.getLocation(), D.getLocation(), NameIdent, QT,
Sander de Smalen891af03a2018-02-03 13:55:59 +00001286 getContext().CreateTypeSourceInfo(QT), SC_Auto);
Sander de Smalen9084a3b2018-02-13 07:49:34 +00001287 ArtificialDecl->setImplicit();
Sander de Smalen891af03a2018-02-03 13:55:59 +00001288
1289 MD = DI->EmitDeclareOfAutoVariable(ArtificialDecl, VlaSize.NumElts,
1290 Builder);
1291 }
1292 assert(MD && "No Size expression debug node created");
1293 DI->registerVLASizeExpression(VlaSize.Type, MD);
1294 }
1295}
1296
John McCallc533cb72011-02-22 06:44:22 +00001297/// EmitAutoVarAlloca - Emit the alloca and debug information for a
Alp Tokerf6a24ce2013-12-05 16:25:25 +00001298/// local variable. Does not emit initialization or destruction.
John McCallc533cb72011-02-22 06:44:22 +00001299CodeGenFunction::AutoVarEmission
1300CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
1301 QualType Ty = D.getType();
Yaxun Liub7318e02017-10-13 03:37:48 +00001302 assert(
1303 Ty.getAddressSpace() == LangAS::Default ||
1304 (Ty.getAddressSpace() == LangAS::opencl_private && getLangOpts().OpenCL));
John McCallc533cb72011-02-22 06:44:22 +00001305
1306 AutoVarEmission emission(D);
1307
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001308 bool isEscapingByRef = D.isEscapingByref();
1309 emission.IsEscapingByRef = isEscapingByRef;
John McCallc533cb72011-02-22 06:44:22 +00001310
1311 CharUnits alignment = getContext().getDeclAlign(&D);
John McCallc533cb72011-02-22 06:44:22 +00001312
John McCall23c29fe2011-06-24 21:55:10 +00001313 // If the type is variably-modified, emit all the VLA sizes for it.
1314 if (Ty->isVariablyModifiedType())
1315 EmitVariablyModifiedType(Ty);
1316
Sander de Smalen891af03a2018-02-03 13:55:59 +00001317 auto *DI = getDebugInfo();
1318 bool EmitDebugInfo = DI && CGM.getCodeGenOpts().getDebugInfo() >=
1319 codegenoptions::LimitedDebugInfo;
1320
John McCall7f416cc2015-09-08 08:05:57 +00001321 Address address = Address::invalid();
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001322 Address AllocaAddr = Address::invalid();
Eli Friedmana682d392008-02-15 12:20:59 +00001323 if (Ty->isConstantSizeType()) {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001324 bool NRVO = getLangOpts().ElideConstructors &&
1325 D.isNRVOVariable();
John McCallc533cb72011-02-22 06:44:22 +00001326
Richard Smith2bcde3a2013-06-02 00:09:52 +00001327 // If this value is an array or struct with a statically determinable
1328 // constant initializer, there are optimizations we can do.
Rafael Espindola609f5d92013-03-26 18:41:47 +00001329 //
1330 // TODO: We should constant-evaluate the initializer of any variable,
1331 // as long as it is initialized by a constant expression. Currently,
1332 // isConstantInitializer produces wrong answers for structs with
1333 // reference or bitfield members, and a few other cases, and checking
1334 // for POD-ness protects us from some of these.
Richard Smith2bcde3a2013-06-02 00:09:52 +00001335 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
1336 (D.isConstexpr() ||
1337 ((Ty.isPODType(getContext()) ||
1338 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
1339 D.getInit()->isConstantInitializer(getContext(), false)))) {
John McCallc533cb72011-02-22 06:44:22 +00001340
Rafael Espindola609f5d92013-03-26 18:41:47 +00001341 // If the variable's a const type, and it's neither an NRVO
1342 // candidate nor a __block variable and has no mutable members,
1343 // emit it as a global instead.
Anastasia Stulovae4a1c382016-11-29 17:01:19 +00001344 // Exception is if a variable is located in non-constant address space
1345 // in OpenCL.
1346 if ((!getLangOpts().OpenCL ||
1347 Ty.getAddressSpace() == LangAS::opencl_constant) &&
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001348 (CGM.getCodeGenOpts().MergeAllConstants && !NRVO &&
1349 !isEscapingByRef && CGM.isTypeConstant(Ty, true))) {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001350 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCallc533cb72011-02-22 06:44:22 +00001351
John McCall7f416cc2015-09-08 08:05:57 +00001352 // Signal this condition to later callbacks.
1353 emission.Addr = Address::invalid();
Rafael Espindola609f5d92013-03-26 18:41:47 +00001354 assert(emission.wasEmittedAsGlobal());
1355 return emission;
Tanya Lattnerf9d41df2009-11-04 01:18:09 +00001356 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001357
Rafael Espindola609f5d92013-03-26 18:41:47 +00001358 // Otherwise, tell the initialization code that we're in this case.
1359 emission.IsConstantAggregate = true;
1360 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001361
Rafael Espindola609f5d92013-03-26 18:41:47 +00001362 // A normal fixed sized variable becomes an alloca in the entry block,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001363 // unless:
1364 // - it's an NRVO variable.
1365 // - we are compiling OpenMP and it's an OpenMP local variable.
Eric Christopher31ab1302011-08-23 22:38:00 +00001366
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001367 Address OpenMPLocalAddr =
1368 getLangOpts().OpenMP
1369 ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
1370 : Address::invalid();
1371 if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
1372 address = OpenMPLocalAddr;
1373 } else if (NRVO) {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001374 // The named return value optimization: allocate this variable in the
1375 // return slot, so that we can elide the copy when returning this
1376 // variable (C++0x [class.copy]p34).
John McCall7f416cc2015-09-08 08:05:57 +00001377 address = ReturnValue;
Eric Christopher31ab1302011-08-23 22:38:00 +00001378
Rafael Espindola609f5d92013-03-26 18:41:47 +00001379 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
Akira Hatanaka673af7a2018-03-29 17:56:24 +00001380 const auto *RD = RecordTy->getDecl();
1381 const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1382 if ((CXXRD && !CXXRD->hasTrivialDestructor()) ||
1383 RD->isNonTrivialToPrimitiveDestroy()) {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001384 // Create a flag that is used to indicate when the NRVO was applied
1385 // to this variable. Set it to zero to indicate that NRVO was not
1386 // applied.
1387 llvm::Value *Zero = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +00001388 Address NRVOFlag =
1389 CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
Rafael Espindola609f5d92013-03-26 18:41:47 +00001390 EnsureInsertPoint();
1391 Builder.CreateStore(Zero, NRVOFlag);
Eric Christopher31ab1302011-08-23 22:38:00 +00001392
Rafael Espindola609f5d92013-03-26 18:41:47 +00001393 // Record the NRVO flag for this variable.
John McCall7f416cc2015-09-08 08:05:57 +00001394 NRVOFlags[&D] = NRVOFlag.getPointer();
1395 emission.NRVOFlag = NRVOFlag.getPointer();
Nadav Rotem1da30942013-03-23 06:43:35 +00001396 }
Douglas Gregor290c93e2010-05-15 06:46:45 +00001397 }
Chris Lattnerb781dc792008-05-08 05:58:21 +00001398 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001399 CharUnits allocaAlignment;
1400 llvm::Type *allocaTy;
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001401 if (isEscapingByRef) {
John McCall7f416cc2015-09-08 08:05:57 +00001402 auto &byrefInfo = getBlockByrefInfo(&D);
1403 allocaTy = byrefInfo.Type;
1404 allocaAlignment = byrefInfo.ByrefAlignment;
1405 } else {
1406 allocaTy = ConvertTypeForMem(Ty);
1407 allocaAlignment = alignment;
1408 }
Rafael Espindola609f5d92013-03-26 18:41:47 +00001409
John McCall999110f2015-09-08 09:18:30 +00001410 // Create the alloca. Note that we set the name separately from
1411 // building the instruction so that it's there even in no-asserts
1412 // builds.
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001413 address = CreateTempAlloca(allocaTy, allocaAlignment, D.getName(),
1414 /*ArraySize=*/nullptr, &AllocaAddr);
Rafael Espindola609f5d92013-03-26 18:41:47 +00001415
Reid Kleckner1f88e932015-10-07 21:03:41 +00001416 // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1417 // the catch parameter starts in the catchpad instruction, and we can't
1418 // insert code in those basic blocks.
1419 bool IsMSCatchParam =
1420 D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1421
Vitaly Buka64c80b42016-10-26 05:42:30 +00001422 // Emit a lifetime intrinsic if meaningful. There's no point in doing this
1423 // if we don't have a valid insertion point (?).
Reid Kleckner1f88e932015-10-07 21:03:41 +00001424 if (HaveInsertPoint() && !IsMSCatchParam) {
Akira Hatanakafdcd18b2017-01-25 22:55:13 +00001425 // If there's a jump into the lifetime of this variable, its lifetime
1426 // gets broken up into several regions in IR, which requires more work
1427 // to handle correctly. For now, just omit the intrinsics; this is a
1428 // rare case, and it's better to just be conservatively correct.
1429 // PR28267.
1430 //
1431 // We have to do this in all language modes if there's a jump past the
1432 // declaration. We also have to do it in C if there's a jump to an
1433 // earlier point in the current block because non-VLA lifetimes begin as
1434 // soon as the containing block is entered, not when its variables
1435 // actually come into scope; suppressing the lifetime annotations
1436 // completely in this case is unnecessarily pessimistic, but again, this
1437 // is rare.
1438 if (!Bypasses.IsBypassed(&D) &&
1439 !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
Vitaly Buka64c80b42016-10-26 05:42:30 +00001440 uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
1441 emission.SizeForLifetimeMarkers =
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001442 EmitLifetimeStart(size, AllocaAddr.getPointer());
Vitaly Buka64c80b42016-10-26 05:42:30 +00001443 }
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +00001444 } else {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001445 assert(!emission.useLifetimeMarkers());
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +00001446 }
Chris Lattnerb781dc792008-05-08 05:58:21 +00001447 }
Chris Lattner03df1222007-06-02 04:53:11 +00001448 } else {
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001449 EnsureInsertPoint();
1450
Anders Carlsson15949b32009-02-09 20:41:50 +00001451 if (!DidCallStackSave) {
Anders Carlsson30032882008-12-12 07:38:43 +00001452 // Save the stack.
John McCall7f416cc2015-09-08 08:05:57 +00001453 Address Stack =
1454 CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
Mike Stump11289f42009-09-09 15:08:12 +00001455
Anders Carlsson30032882008-12-12 07:38:43 +00001456 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
David Blaikie4ba525b2015-07-14 17:27:39 +00001457 llvm::Value *V = Builder.CreateCall(F);
Anders Carlsson30032882008-12-12 07:38:43 +00001458 Builder.CreateStore(V, Stack);
Anders Carlsson15949b32009-02-09 20:41:50 +00001459
1460 DidCallStackSave = true;
Mike Stump11289f42009-09-09 15:08:12 +00001461
John McCalla464ff92010-07-21 06:13:08 +00001462 // Push a cleanup block and restore the stack there.
John McCalle4df6c82011-01-28 08:37:24 +00001463 // FIXME: in general circumstances, this should be an EH cleanup.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001464 pushStackRestore(NormalCleanup, Stack);
Anders Carlsson30032882008-12-12 07:38:43 +00001465 }
Mike Stump11289f42009-09-09 15:08:12 +00001466
Sander de Smalen891af03a2018-02-03 13:55:59 +00001467 auto VlaSize = getVLASize(Ty);
1468 llvm::Type *llvmTy = ConvertTypeForMem(VlaSize.Type);
Anders Carlsson30032882008-12-12 07:38:43 +00001469
1470 // Allocate memory for the array.
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001471 address = CreateTempAlloca(llvmTy, alignment, "vla", VlaSize.NumElts,
1472 &AllocaAddr);
Sander de Smalen891af03a2018-02-03 13:55:59 +00001473
1474 // If we have debug info enabled, properly describe the VLA dimensions for
1475 // this type by registering the vla size expression for each of the
1476 // dimensions.
1477 EmitAndRegisterVariableArrayDimensions(DI, D, EmitDebugInfo);
Chris Lattner03df1222007-06-02 04:53:11 +00001478 }
Eli Friedmanf4084702008-12-20 23:11:59 +00001479
John McCall7f416cc2015-09-08 08:05:57 +00001480 setAddrOfLocalVar(&D, address);
1481 emission.Addr = address;
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001482 emission.AllocaAddr = AllocaAddr;
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001483
1484 // Emit debug info for local var declaration.
Sander de Smalen891af03a2018-02-03 13:55:59 +00001485 if (EmitDebugInfo && HaveInsertPoint()) {
1486 DI->setLocation(D.getLocation());
1487 (void)DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
1488 }
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001489
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001490 if (D.hasAttr<AnnotateAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00001491 EmitVarAnnotations(&D, address.getPointer());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001492
Kuba Mracek5e5e4e72017-04-14 16:53:25 +00001493 // Make sure we call @llvm.lifetime.end.
1494 if (emission.useLifetimeMarkers())
1495 EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001496 emission.getOriginalAllocatedAddress(),
Kuba Mracek5e5e4e72017-04-14 16:53:25 +00001497 emission.getSizeForLifetimeMarkers());
1498
John McCallc533cb72011-02-22 06:44:22 +00001499 return emission;
1500}
1501
JF Bastien6b239722018-05-19 04:21:26 +00001502static bool isCapturedBy(const VarDecl &, const Expr *);
1503
1504/// Determines whether the given __block variable is potentially
1505/// captured by the given statement.
1506static bool isCapturedBy(const VarDecl &Var, const Stmt *S) {
1507 if (const Expr *E = dyn_cast<Expr>(S))
1508 return isCapturedBy(Var, E);
1509 for (const Stmt *SubStmt : S->children())
1510 if (isCapturedBy(Var, SubStmt))
1511 return true;
1512 return false;
1513}
1514
John McCallc533cb72011-02-22 06:44:22 +00001515/// Determines whether the given __block variable is potentially
1516/// captured by the given expression.
JF Bastien6b239722018-05-19 04:21:26 +00001517static bool isCapturedBy(const VarDecl &Var, const Expr *E) {
John McCallc533cb72011-02-22 06:44:22 +00001518 // Skip the most common kinds of expressions that make
1519 // hierarchy-walking expensive.
JF Bastien6b239722018-05-19 04:21:26 +00001520 E = E->IgnoreParenCasts();
John McCallc533cb72011-02-22 06:44:22 +00001521
JF Bastien6b239722018-05-19 04:21:26 +00001522 if (const BlockExpr *BE = dyn_cast<BlockExpr>(E)) {
1523 const BlockDecl *Block = BE->getBlockDecl();
1524 for (const auto &I : Block->captures()) {
1525 if (I.getVariable() == &Var)
John McCallc533cb72011-02-22 06:44:22 +00001526 return true;
1527 }
1528
1529 // No need to walk into the subexpressions.
1530 return false;
1531 }
1532
JF Bastien6b239722018-05-19 04:21:26 +00001533 if (const StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001534 const CompoundStmt *CS = SE->getSubStmt();
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001535 for (const auto *BI : CS->body())
JF Bastien6b239722018-05-19 04:21:26 +00001536 if (const auto *BIE = dyn_cast<Expr>(BI)) {
1537 if (isCapturedBy(Var, BIE))
1538 return true;
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001539 }
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001540 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001541 // special case declarations
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001542 for (const auto *I : DS->decls()) {
1543 if (const auto *VD = dyn_cast<VarDecl>((I))) {
1544 const Expr *Init = VD->getInit();
JF Bastien6b239722018-05-19 04:21:26 +00001545 if (Init && isCapturedBy(Var, Init))
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001546 return true;
1547 }
1548 }
1549 }
1550 else
1551 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1552 // Later, provide code to poke into statements for capture analysis.
1553 return true;
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001554 return false;
1555 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001556
JF Bastien6b239722018-05-19 04:21:26 +00001557 for (const Stmt *SubStmt : E->children())
1558 if (isCapturedBy(Var, SubStmt))
John McCallc533cb72011-02-22 06:44:22 +00001559 return true;
1560
1561 return false;
1562}
1563
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001564/// Determine whether the given initializer is trivial in the sense
Douglas Gregor82e1af22011-07-01 21:08:19 +00001565/// that it requires no code to be generated.
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001566bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
Douglas Gregor82e1af22011-07-01 21:08:19 +00001567 if (!Init)
1568 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001569
Douglas Gregor82e1af22011-07-01 21:08:19 +00001570 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1571 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1572 if (Constructor->isTrivial() &&
1573 Constructor->isDefaultConstructor() &&
1574 !Construct->requiresZeroInitialization())
1575 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001576
Douglas Gregor82e1af22011-07-01 21:08:19 +00001577 return false;
1578}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001579
John McCallc533cb72011-02-22 06:44:22 +00001580void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001581 assert(emission.Variable && "emission was not valid!");
1582
John McCallc533cb72011-02-22 06:44:22 +00001583 // If this was emitted as a global constant, we're done.
1584 if (emission.wasEmittedAsGlobal()) return;
1585
John McCall9e2e22f2011-02-22 07:16:58 +00001586 const VarDecl &D = *emission.Variable;
Adrian Prantl95b24e92015-02-03 20:00:54 +00001587 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
John McCallc533cb72011-02-22 06:44:22 +00001588 QualType type = D.getType();
1589
JF Bastien14daa202018-12-18 05:12:21 +00001590 bool isVolatile = type.isVolatileQualified();
1591
Chris Lattner07eb7332007-07-12 00:39:48 +00001592 // If this local has an initializer, emit it now.
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001593 const Expr *Init = D.getInit();
1594
1595 // If we are at an unreachable point, we don't need to emit the initializer
1596 // unless it contains a label.
1597 if (!HaveInsertPoint()) {
John McCallc533cb72011-02-22 06:44:22 +00001598 if (!Init || !ContainsLabel(Init)) return;
1599 EnsureInsertPoint();
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001600 }
1601
John McCall73064872011-03-31 01:59:53 +00001602 // Initialize the structure of a __block variable.
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001603 if (emission.IsEscapingByRef)
John McCall73064872011-03-31 01:59:53 +00001604 emitByrefStructureInit(emission);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001605
Akira Hatanaka7275da02018-02-28 07:15:55 +00001606 // Initialize the variable here if it doesn't have a initializer and it is a
1607 // C struct that is non-trivial to initialize or an array containing such a
1608 // struct.
1609 if (!Init &&
1610 type.isNonTrivialToPrimitiveDefaultInitialize() ==
1611 QualType::PDIK_Struct) {
1612 LValue Dst = MakeAddrLValue(emission.getAllocatedAddress(), type);
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001613 if (emission.IsEscapingByRef)
Akira Hatanaka7275da02018-02-28 07:15:55 +00001614 drillIntoBlockVariable(*this, Dst, &D);
1615 defaultInitNonTrivialCStructVar(Dst);
1616 return;
1617 }
1618
John McCallc533cb72011-02-22 06:44:22 +00001619 // Check whether this is a byref variable that's potentially
1620 // captured and moved by its own initializer. If so, we'll need to
1621 // emit the initializer first, then copy into the variable.
JF Bastien14daa202018-12-18 05:12:21 +00001622 bool capturedByInit =
1623 Init && emission.IsEscapingByRef && isCapturedBy(D, Init);
John McCallc533cb72011-02-22 06:44:22 +00001624
John McCall7f416cc2015-09-08 08:05:57 +00001625 Address Loc =
JF Bastien14daa202018-12-18 05:12:21 +00001626 capturedByInit ? emission.Addr : emission.getObjectAddress(*this);
1627
1628 // Note: constexpr already initializes everything correctly.
1629 LangOptions::TrivialAutoVarInitKind trivialAutoVarInit =
1630 (D.isConstexpr()
1631 ? LangOptions::TrivialAutoVarInitKind::Uninitialized
1632 : (D.getAttr<UninitializedAttr>()
1633 ? LangOptions::TrivialAutoVarInitKind::Uninitialized
1634 : getContext().getLangOpts().getTrivialAutoVarInit()));
1635
1636 auto initializeWhatIsTechnicallyUninitialized = [&]() {
1637 if (trivialAutoVarInit ==
1638 LangOptions::TrivialAutoVarInitKind::Uninitialized)
1639 return;
1640
1641 CharUnits Size = getContext().getTypeSizeInChars(type);
1642 if (!Size.isZero()) {
1643 switch (trivialAutoVarInit) {
1644 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
1645 llvm_unreachable("Uninitialized handled above");
1646 case LangOptions::TrivialAutoVarInitKind::Zero:
1647 emitStoresForZeroInit(CGM, D, Loc, isVolatile, Builder);
1648 break;
1649 case LangOptions::TrivialAutoVarInitKind::Pattern:
1650 emitStoresForPatternInit(CGM, D, Loc, isVolatile, Builder);
1651 break;
1652 }
1653 return;
1654 }
1655
1656 // VLAs look zero-sized to getTypeInfo. We can't emit constant stores to
1657 // them, so emit a memcpy with the VLA size to initialize each element.
1658 // Technically zero-sized or negative-sized VLAs are undefined, and UBSan
1659 // will catch that code, but there exists code which generates zero-sized
1660 // VLAs. Be nice and initialize whatever they requested.
1661 const VariableArrayType *VlaType =
1662 dyn_cast_or_null<VariableArrayType>(getContext().getAsArrayType(type));
1663 if (!VlaType)
1664 return;
1665 auto VlaSize = getVLASize(VlaType);
1666 auto SizeVal = VlaSize.NumElts;
1667 CharUnits EltSize = getContext().getTypeSizeInChars(VlaSize.Type);
1668 switch (trivialAutoVarInit) {
1669 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
1670 llvm_unreachable("Uninitialized handled above");
1671
1672 case LangOptions::TrivialAutoVarInitKind::Zero:
1673 if (!EltSize.isOne())
1674 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
1675 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1676 isVolatile);
1677 break;
1678
1679 case LangOptions::TrivialAutoVarInitKind::Pattern: {
1680 llvm::Type *ElTy = Loc.getElementType();
1681 llvm::Constant *Constant = patternFor(CGM, ElTy);
1682 CharUnits ConstantAlign = getContext().getTypeAlignInChars(VlaSize.Type);
1683 llvm::BasicBlock *SetupBB = createBasicBlock("vla-setup.loop");
1684 llvm::BasicBlock *LoopBB = createBasicBlock("vla-init.loop");
1685 llvm::BasicBlock *ContBB = createBasicBlock("vla-init.cont");
1686 llvm::Value *IsZeroSizedVLA = Builder.CreateICmpEQ(
1687 SizeVal, llvm::ConstantInt::get(SizeVal->getType(), 0),
1688 "vla.iszerosized");
1689 Builder.CreateCondBr(IsZeroSizedVLA, ContBB, SetupBB);
1690 EmitBlock(SetupBB);
1691 if (!EltSize.isOne())
1692 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
1693 llvm::Value *BaseSizeInChars =
1694 llvm::ConstantInt::get(IntPtrTy, EltSize.getQuantity());
1695 Address Begin = Builder.CreateElementBitCast(Loc, Int8Ty, "vla.begin");
1696 llvm::Value *End =
1697 Builder.CreateInBoundsGEP(Begin.getPointer(), SizeVal, "vla.end");
1698 llvm::BasicBlock *OriginBB = Builder.GetInsertBlock();
1699 EmitBlock(LoopBB);
1700 llvm::PHINode *Cur = Builder.CreatePHI(Begin.getType(), 2, "vla.cur");
1701 Cur->addIncoming(Begin.getPointer(), OriginBB);
1702 CharUnits CurAlign = Loc.getAlignment().alignmentOfArrayElement(EltSize);
1703 Builder.CreateMemCpy(
1704 Address(Cur, CurAlign),
1705 createUnnamedGlobalFrom(CGM, D, Builder, Constant, ConstantAlign),
1706 BaseSizeInChars, isVolatile);
1707 llvm::Value *Next =
1708 Builder.CreateInBoundsGEP(Int8Ty, Cur, BaseSizeInChars, "vla.next");
1709 llvm::Value *Done = Builder.CreateICmpEQ(Next, End, "vla-init.isdone");
1710 Builder.CreateCondBr(Done, ContBB, LoopBB);
1711 Cur->addIncoming(Next, LoopBB);
1712 EmitBlock(ContBB);
1713 } break;
1714 }
1715 };
1716
1717 if (isTrivialInitializer(Init)) {
1718 initializeWhatIsTechnicallyUninitialized();
1719 return;
1720 }
John McCallc533cb72011-02-22 06:44:22 +00001721
Craig Topper8a13c412014-05-21 05:09:00 +00001722 llvm::Constant *constant = nullptr;
Richard Smith2bcde3a2013-06-02 00:09:52 +00001723 if (emission.IsConstantAggregate || D.isConstexpr()) {
Richard Smithfddd3842011-12-30 21:15:51 +00001724 assert(!capturedByInit && "constant init contains a capturing block?");
John McCallde0fe072017-08-15 21:42:52 +00001725 constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(D);
JF Bastien14daa202018-12-18 05:12:21 +00001726 if (constant && trivialAutoVarInit !=
1727 LangOptions::TrivialAutoVarInitKind::Uninitialized)
1728 constant = replaceUndef(constant);
Richard Smithfddd3842011-12-30 21:15:51 +00001729 }
1730
1731 if (!constant) {
JF Bastien14daa202018-12-18 05:12:21 +00001732 initializeWhatIsTechnicallyUninitialized();
John McCall7f416cc2015-09-08 08:05:57 +00001733 LValue lv = MakeAddrLValue(Loc, type);
John McCall1553b192011-06-16 04:16:24 +00001734 lv.setNonGC(true);
David Blaikie66e41972015-01-14 07:38:27 +00001735 return EmitExprAsInit(Init, &D, lv, capturedByInit);
John McCall1553b192011-06-16 04:16:24 +00001736 }
John McCall91ca10f2011-03-08 09:11:50 +00001737
Richard Smith2bcde3a2013-06-02 00:09:52 +00001738 if (!emission.IsConstantAggregate) {
1739 // For simple scalar/complex initialization, store the value directly.
John McCall7f416cc2015-09-08 08:05:57 +00001740 LValue lv = MakeAddrLValue(Loc, type);
Richard Smith2bcde3a2013-06-02 00:09:52 +00001741 lv.setNonGC(true);
1742 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1743 }
1744
Yaxun Liudaceb1e2018-05-14 19:20:12 +00001745 llvm::Type *BP = CGM.Int8Ty->getPointerTo(Loc.getAddressSpace());
John McCall7f416cc2015-09-08 08:05:57 +00001746 if (Loc.getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001747 Loc = Builder.CreateBitCast(Loc, BP);
Mon P Wangcc2ab0c2010-04-04 03:10:52 +00001748
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001749 emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant);
John McCall91ca10f2011-03-08 09:11:50 +00001750}
1751
Richard Smithe78fac52018-04-05 20:52:58 +00001752/// Emit an expression as an initializer for an object (variable, field, etc.)
1753/// at the given location. The expression is not necessarily the normal
1754/// initializer for the object, and the address is not necessarily
John McCall91ca10f2011-03-08 09:11:50 +00001755/// its normal location.
1756///
1757/// \param init the initializing expression
Richard Smithe78fac52018-04-05 20:52:58 +00001758/// \param D the object to act as if we're initializing
John McCall91ca10f2011-03-08 09:11:50 +00001759/// \param loc the address to initialize; its type is a pointer
Richard Smithe78fac52018-04-05 20:52:58 +00001760/// to the LLVM mapping of the object's type
John McCall91ca10f2011-03-08 09:11:50 +00001761/// \param alignment the alignment of the address
Richard Smithe78fac52018-04-05 20:52:58 +00001762/// \param capturedByInit true if \p D is a __block variable
John McCall91ca10f2011-03-08 09:11:50 +00001763/// whose address is potentially changed by the initializer
David Blaikie73ca5692014-12-09 00:32:22 +00001764void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +00001765 LValue lvalue, bool capturedByInit) {
John McCall31168b02011-06-15 23:02:42 +00001766 QualType type = D->getType();
John McCall91ca10f2011-03-08 09:11:50 +00001767
1768 if (type->isReferenceType()) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +00001769 RValue rvalue = EmitReferenceBindingToExpr(init);
Eric Christopher31ab1302011-08-23 22:38:00 +00001770 if (capturedByInit)
John McCall1553b192011-06-16 04:16:24 +00001771 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001772 EmitStoreThroughLValue(rvalue, lvalue, true);
John McCall47fb9502013-03-07 21:37:08 +00001773 return;
1774 }
1775 switch (getEvaluationKind(type)) {
1776 case TEK_Scalar:
David Blaikie66e41972015-01-14 07:38:27 +00001777 EmitScalarInit(init, D, lvalue, capturedByInit);
John McCall47fb9502013-03-07 21:37:08 +00001778 return;
1779 case TEK_Complex: {
John McCall91ca10f2011-03-08 09:11:50 +00001780 ComplexPairTy complex = EmitComplexExpr(init);
John McCall1553b192011-06-16 04:16:24 +00001781 if (capturedByInit)
1782 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001783 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
John McCall47fb9502013-03-07 21:37:08 +00001784 return;
1785 }
1786 case TEK_Aggregate:
John McCalla8ec7eb2013-03-07 21:37:17 +00001787 if (type->isAtomicType()) {
1788 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1789 } else {
Richard Smithe78fac52018-04-05 20:52:58 +00001790 AggValueSlot::Overlap_t Overlap = AggValueSlot::MayOverlap;
1791 if (isa<VarDecl>(D))
1792 Overlap = AggValueSlot::DoesNotOverlap;
1793 else if (auto *FD = dyn_cast<FieldDecl>(D))
1794 Overlap = overlapForFieldInit(FD);
John McCalla8ec7eb2013-03-07 21:37:17 +00001795 // TODO: how can we delay here if D is captured by its initializer?
1796 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001797 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001798 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00001799 AggValueSlot::IsNotAliased,
1800 Overlap));
John McCalla8ec7eb2013-03-07 21:37:17 +00001801 }
John McCall47fb9502013-03-07 21:37:08 +00001802 return;
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001803 }
John McCall47fb9502013-03-07 21:37:08 +00001804 llvm_unreachable("bad evaluation kind");
John McCallc533cb72011-02-22 06:44:22 +00001805}
John McCallbd309292010-07-06 01:34:17 +00001806
John McCall82fe67b2011-07-09 01:37:26 +00001807/// Enter a destroy cleanup for the given local variable.
1808void CodeGenFunction::emitAutoVarTypeCleanup(
1809 const CodeGenFunction::AutoVarEmission &emission,
1810 QualType::DestructionKind dtorKind) {
1811 assert(dtorKind != QualType::DK_none);
1812
1813 // Note that for __block variables, we want to destroy the
1814 // original stack object, not the possibly forwarded object.
John McCall7f416cc2015-09-08 08:05:57 +00001815 Address addr = emission.getObjectAddress(*this);
John McCall82fe67b2011-07-09 01:37:26 +00001816
1817 const VarDecl *var = emission.Variable;
1818 QualType type = var->getType();
1819
1820 CleanupKind cleanupKind = NormalAndEHCleanup;
Craig Topper8a13c412014-05-21 05:09:00 +00001821 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall82fe67b2011-07-09 01:37:26 +00001822
1823 switch (dtorKind) {
1824 case QualType::DK_none:
1825 llvm_unreachable("no cleanup for trivially-destructible variable");
1826
1827 case QualType::DK_cxx_destructor:
1828 // If there's an NRVO flag on the emission, we need a different
1829 // cleanup.
1830 if (emission.NRVOFlag) {
1831 assert(!type->isArrayType());
1832 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
Akira Hatanaka673af7a2018-03-29 17:56:24 +00001833 EHStack.pushCleanup<DestroyNRVOVariableCXX>(cleanupKind, addr, dtor,
1834 emission.NRVOFlag);
John McCall82fe67b2011-07-09 01:37:26 +00001835 return;
1836 }
1837 break;
1838
1839 case QualType::DK_objc_strong_lifetime:
1840 // Suppress cleanups for pseudo-strong variables.
1841 if (var->isARCPseudoStrong()) return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001842
John McCall82fe67b2011-07-09 01:37:26 +00001843 // Otherwise, consider whether to use an EH cleanup or not.
1844 cleanupKind = getARCCleanupKind();
1845
1846 // Use the imprecise destroyer by default.
1847 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1848 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1849 break;
1850
1851 case QualType::DK_objc_weak_lifetime:
1852 break;
Akira Hatanaka7275da02018-02-28 07:15:55 +00001853
1854 case QualType::DK_nontrivial_c_struct:
1855 destroyer = CodeGenFunction::destroyNonTrivialCStruct;
Akira Hatanaka673af7a2018-03-29 17:56:24 +00001856 if (emission.NRVOFlag) {
1857 assert(!type->isArrayType());
1858 EHStack.pushCleanup<DestroyNRVOVariableC>(cleanupKind, addr,
1859 emission.NRVOFlag, type);
1860 return;
1861 }
Akira Hatanaka7275da02018-02-28 07:15:55 +00001862 break;
John McCall82fe67b2011-07-09 01:37:26 +00001863 }
1864
1865 // If we haven't chosen a more specific destroyer, use the default.
Peter Collingbourne1425b452012-01-26 03:33:36 +00001866 if (!destroyer) destroyer = getDestroyer(dtorKind);
John McCall178360e2011-07-11 08:38:19 +00001867
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001868 // Use an EH cleanup in array destructors iff the destructor itself
John McCall178360e2011-07-11 08:38:19 +00001869 // is being pushed as an EH cleanup.
1870 bool useEHCleanup = (cleanupKind & EHCleanup);
1871 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1872 useEHCleanup);
John McCall82fe67b2011-07-09 01:37:26 +00001873}
1874
John McCallc533cb72011-02-22 06:44:22 +00001875void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001876 assert(emission.Variable && "emission was not valid!");
1877
John McCallc533cb72011-02-22 06:44:22 +00001878 // If this was emitted as a global constant, we're done.
1879 if (emission.wasEmittedAsGlobal()) return;
1880
John McCall8c38d352012-04-13 18:44:05 +00001881 // If we don't have an insertion point, we're done. Sema prevents
1882 // us from jumping into any of these scopes anyway.
1883 if (!HaveInsertPoint()) return;
1884
John McCall9e2e22f2011-02-22 07:16:58 +00001885 const VarDecl &D = *emission.Variable;
John McCallc533cb72011-02-22 06:44:22 +00001886
John McCall82fe67b2011-07-09 01:37:26 +00001887 // Check the type for a cleanup.
1888 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1889 emitAutoVarTypeCleanup(emission, dtorKind);
John McCall31168b02011-06-15 23:02:42 +00001890
John McCall1bd25562011-06-24 23:21:27 +00001891 // In GC mode, honor objc_precise_lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001892 if (getLangOpts().getGC() != LangOptions::NonGC &&
John McCall1bd25562011-06-24 23:21:27 +00001893 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1894 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1895 }
1896
John McCallc533cb72011-02-22 06:44:22 +00001897 // Handle the cleanup attribute.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001898 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001899 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001900
John McCallc533cb72011-02-22 06:44:22 +00001901 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001902 assert(F && "Could not find function!");
Mike Stump11289f42009-09-09 15:08:12 +00001903
John McCalla729c622012-02-17 03:33:10 +00001904 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
John McCallc533cb72011-02-22 06:44:22 +00001905 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001906 }
Mike Stump626aecc2009-03-05 01:23:13 +00001907
John McCallc533cb72011-02-22 06:44:22 +00001908 // If this is a block variable, call _Block_object_destroy
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001909 // (on the unforwarded address). Don't enter this cleanup if we're in pure-GC
1910 // mode.
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001911 if (emission.IsEscapingByRef &&
1912 CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001913 BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
1914 if (emission.Variable->getType().isObjCGCWeak())
1915 Flags |= BLOCK_FIELD_IS_WEAK;
1916 enterByrefCleanup(NormalAndEHCleanup, emission.Addr, Flags,
Akira Hatanaka9978da32018-08-10 15:09:24 +00001917 /*LoadBlockVarAddr*/ false,
1918 cxxDestructorCanThrow(emission.Variable->getType()));
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001919 }
Chris Lattner03df1222007-06-02 04:53:11 +00001920}
Chris Lattner53621a52007-06-13 20:44:40 +00001921
Peter Collingbourne1425b452012-01-26 03:33:36 +00001922CodeGenFunction::Destroyer *
John McCall82fe67b2011-07-09 01:37:26 +00001923CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1924 switch (kind) {
1925 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
John McCallc2f00012011-07-09 09:09:00 +00001926 case QualType::DK_cxx_destructor:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001927 return destroyCXXObject;
John McCallc2f00012011-07-09 09:09:00 +00001928 case QualType::DK_objc_strong_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001929 return destroyARCStrongPrecise;
John McCallc2f00012011-07-09 09:09:00 +00001930 case QualType::DK_objc_weak_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001931 return destroyARCWeak;
Akira Hatanaka7275da02018-02-28 07:15:55 +00001932 case QualType::DK_nontrivial_c_struct:
1933 return destroyNonTrivialCStruct;
John McCall82fe67b2011-07-09 01:37:26 +00001934 }
Matt Beaumont-Gay934bbf52012-01-27 00:46:27 +00001935 llvm_unreachable("Unknown DestructionKind");
John McCall82fe67b2011-07-09 01:37:26 +00001936}
1937
John McCall12cc42a2013-02-01 05:11:40 +00001938/// pushEHDestroy - Push the standard destructor for the given type as
1939/// an EH-only cleanup.
1940void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00001941 Address addr, QualType type) {
John McCall12cc42a2013-02-01 05:11:40 +00001942 assert(dtorKind && "cannot push destructor for trivial type");
1943 assert(needsEHCleanup(dtorKind));
1944
1945 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1946}
1947
1948/// pushDestroy - Push the standard destructor for the given type as
1949/// at least a normal cleanup.
John McCall4bd0fb12011-07-12 16:41:08 +00001950void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00001951 Address addr, QualType type) {
John McCall4bd0fb12011-07-12 16:41:08 +00001952 assert(dtorKind && "cannot push destructor for trivial type");
1953
1954 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1955 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1956 cleanupKind & EHCleanup);
1957}
1958
John McCall7f416cc2015-09-08 08:05:57 +00001959void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001960 QualType type, Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001961 bool useEHCleanupForArray) {
John McCall4bd0fb12011-07-12 16:41:08 +00001962 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1963 destroyer, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001964}
1965
John McCall7f416cc2015-09-08 08:05:57 +00001966void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001967 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
1968}
1969
Richard Smith736a9472013-06-12 20:42:33 +00001970void CodeGenFunction::pushLifetimeExtendedDestroy(
John McCall7f416cc2015-09-08 08:05:57 +00001971 CleanupKind cleanupKind, Address addr, QualType type,
Richard Smith736a9472013-06-12 20:42:33 +00001972 Destroyer *destroyer, bool useEHCleanupForArray) {
Richard Smith736a9472013-06-12 20:42:33 +00001973 // Push an EH-only cleanup for the object now.
1974 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1975 // around in case a temporary's destructor throws an exception.
1976 if (cleanupKind & EHCleanup)
1977 EHStack.pushCleanup<DestroyObject>(
1978 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1979 destroyer, useEHCleanupForArray);
1980
1981 // Remember that we need to push a full cleanup for the object at the
1982 // end of the full-expression.
1983 pushCleanupAfterFullExpr<DestroyObject>(
1984 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1985}
1986
John McCall178360e2011-07-11 08:38:19 +00001987/// emitDestroy - Immediately perform the destruction of the given
1988/// object.
1989///
1990/// \param addr - the address of the object; a type*
1991/// \param type - the type of the object; if an array type, all
1992/// objects are destroyed in reverse order
1993/// \param destroyer - the function to call to destroy individual
1994/// elements
1995/// \param useEHCleanupForArray - whether an EH cleanup should be
1996/// used when destroying array elements, in case one of the
1997/// destructions throws an exception
John McCall7f416cc2015-09-08 08:05:57 +00001998void CodeGenFunction::emitDestroy(Address addr, QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001999 Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00002000 bool useEHCleanupForArray) {
John McCall82fe67b2011-07-09 01:37:26 +00002001 const ArrayType *arrayType = getContext().getAsArrayType(type);
2002 if (!arrayType)
2003 return destroyer(*this, addr, type);
2004
John McCall7f416cc2015-09-08 08:05:57 +00002005 llvm::Value *length = emitArrayLength(arrayType, type, addr);
2006
2007 CharUnits elementAlign =
2008 addr.getAlignment()
2009 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
John McCall97eab0a2011-07-13 08:09:46 +00002010
2011 // Normally we have to check whether the array is zero-length.
2012 bool checkZeroLength = true;
2013
2014 // But if the array length is constant, we can suppress that.
2015 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
2016 // ...and if it's constant zero, we can just skip the entire thing.
2017 if (constLength->isZero()) return;
2018 checkZeroLength = false;
2019 }
2020
John McCall7f416cc2015-09-08 08:05:57 +00002021 llvm::Value *begin = addr.getPointer();
John McCall82fe67b2011-07-09 01:37:26 +00002022 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
John McCall7f416cc2015-09-08 08:05:57 +00002023 emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00002024 checkZeroLength, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00002025}
2026
John McCall178360e2011-07-11 08:38:19 +00002027/// emitArrayDestroy - Destroys all the elements of the given array,
2028/// beginning from last to first. The array cannot be zero-length.
2029///
2030/// \param begin - a type* denoting the first element of the array
2031/// \param end - a type* denoting one past the end of the array
NAKAMURA Takumiff7a9252015-09-08 09:42:41 +00002032/// \param elementType - the element type of the array
John McCall178360e2011-07-11 08:38:19 +00002033/// \param destroyer - the function to call to destroy elements
2034/// \param useEHCleanup - whether to push an EH cleanup to destroy
2035/// the remaining elements in case the destruction of a single
2036/// element throws
John McCall82fe67b2011-07-09 01:37:26 +00002037void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
2038 llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00002039 QualType elementType,
2040 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00002041 Destroyer *destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00002042 bool checkZeroLength,
John McCall178360e2011-07-11 08:38:19 +00002043 bool useEHCleanup) {
John McCall7f416cc2015-09-08 08:05:57 +00002044 assert(!elementType->isArrayType());
John McCall82fe67b2011-07-09 01:37:26 +00002045
2046 // The basic structure here is a do-while loop, because we don't
2047 // need to check for the zero-element case.
2048 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
2049 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
2050
John McCall97eab0a2011-07-13 08:09:46 +00002051 if (checkZeroLength) {
2052 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
2053 "arraydestroy.isempty");
2054 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
2055 }
2056
John McCall82fe67b2011-07-09 01:37:26 +00002057 // Enter the loop body, making that address the current address.
2058 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
2059 EmitBlock(bodyBB);
2060 llvm::PHINode *elementPast =
2061 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
2062 elementPast->addIncoming(end, entryBB);
2063
2064 // Shift the address back by one element.
2065 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
2066 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
2067 "arraydestroy.element");
2068
John McCall178360e2011-07-11 08:38:19 +00002069 if (useEHCleanup)
John McCall7f416cc2015-09-08 08:05:57 +00002070 pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
2071 destroyer);
John McCall178360e2011-07-11 08:38:19 +00002072
John McCall82fe67b2011-07-09 01:37:26 +00002073 // Perform the actual destruction there.
John McCall7f416cc2015-09-08 08:05:57 +00002074 destroyer(*this, Address(element, elementAlign), elementType);
John McCall82fe67b2011-07-09 01:37:26 +00002075
John McCall178360e2011-07-11 08:38:19 +00002076 if (useEHCleanup)
2077 PopCleanupBlock();
2078
John McCall82fe67b2011-07-09 01:37:26 +00002079 // Check whether we've reached the end.
2080 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
2081 Builder.CreateCondBr(done, doneBB, bodyBB);
2082 elementPast->addIncoming(element, Builder.GetInsertBlock());
2083
2084 // Done.
2085 EmitBlock(doneBB);
2086}
2087
John McCall178360e2011-07-11 08:38:19 +00002088/// Perform partial array destruction as if in an EH cleanup. Unlike
2089/// emitArrayDestroy, the element type here may still be an array type.
John McCall178360e2011-07-11 08:38:19 +00002090static void emitPartialArrayDestroy(CodeGenFunction &CGF,
2091 llvm::Value *begin, llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00002092 QualType type, CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00002093 CodeGenFunction::Destroyer *destroyer) {
John McCall178360e2011-07-11 08:38:19 +00002094 // If the element type is itself an array, drill down.
John McCall97eab0a2011-07-13 08:09:46 +00002095 unsigned arrayDepth = 0;
John McCall178360e2011-07-11 08:38:19 +00002096 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
2097 // VLAs don't require a GEP index to walk into.
2098 if (!isa<VariableArrayType>(arrayType))
John McCall97eab0a2011-07-13 08:09:46 +00002099 arrayDepth++;
John McCall178360e2011-07-11 08:38:19 +00002100 type = arrayType->getElementType();
2101 }
John McCall97eab0a2011-07-13 08:09:46 +00002102
2103 if (arrayDepth) {
John McCallf0f0b7a2015-09-14 18:57:08 +00002104 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
John McCall97eab0a2011-07-13 08:09:46 +00002105
John McCallf0f0b7a2015-09-14 18:57:08 +00002106 SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
Jay Foad040dd822011-07-22 08:16:57 +00002107 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
2108 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
John McCall178360e2011-07-11 08:38:19 +00002109 }
2110
John McCall97eab0a2011-07-13 08:09:46 +00002111 // Destroy the array. We don't ever need an EH cleanup because we
2112 // assume that we're in an EH cleanup ourselves, so a throwing
2113 // destructor causes an immediate terminate.
John McCall7f416cc2015-09-08 08:05:57 +00002114 CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00002115 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
John McCall178360e2011-07-11 08:38:19 +00002116}
2117
John McCall82fe67b2011-07-09 01:37:26 +00002118namespace {
John McCall178360e2011-07-11 08:38:19 +00002119 /// RegularPartialArrayDestroy - a cleanup which performs a partial
2120 /// array destroy where the end pointer is regularly determined and
2121 /// does not need to be loaded from a local.
David Blaikie7e70d682015-08-18 22:40:54 +00002122 class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall178360e2011-07-11 08:38:19 +00002123 llvm::Value *ArrayBegin;
2124 llvm::Value *ArrayEnd;
2125 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00002126 CodeGenFunction::Destroyer *Destroyer;
John McCall7f416cc2015-09-08 08:05:57 +00002127 CharUnits ElementAlign;
John McCall178360e2011-07-11 08:38:19 +00002128 public:
2129 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00002130 QualType elementType, CharUnits elementAlign,
John McCall178360e2011-07-11 08:38:19 +00002131 CodeGenFunction::Destroyer *destroyer)
2132 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
John McCall7f416cc2015-09-08 08:05:57 +00002133 ElementType(elementType), Destroyer(destroyer),
2134 ElementAlign(elementAlign) {}
John McCall178360e2011-07-11 08:38:19 +00002135
Craig Topper4f12f102014-03-12 06:41:41 +00002136 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +00002137 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00002138 ElementType, ElementAlign, Destroyer);
John McCall178360e2011-07-11 08:38:19 +00002139 }
2140 };
2141
2142 /// IrregularPartialArrayDestroy - a cleanup which performs a
2143 /// partial array destroy where the end pointer is irregularly
2144 /// determined and must be loaded from a local.
David Blaikie7e70d682015-08-18 22:40:54 +00002145 class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall82fe67b2011-07-09 01:37:26 +00002146 llvm::Value *ArrayBegin;
John McCall7f416cc2015-09-08 08:05:57 +00002147 Address ArrayEndPointer;
John McCall82fe67b2011-07-09 01:37:26 +00002148 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00002149 CodeGenFunction::Destroyer *Destroyer;
John McCall7f416cc2015-09-08 08:05:57 +00002150 CharUnits ElementAlign;
John McCall82fe67b2011-07-09 01:37:26 +00002151 public:
John McCall178360e2011-07-11 08:38:19 +00002152 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00002153 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00002154 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00002155 CharUnits elementAlign,
John McCall178360e2011-07-11 08:38:19 +00002156 CodeGenFunction::Destroyer *destroyer)
John McCall82fe67b2011-07-09 01:37:26 +00002157 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
John McCall7f416cc2015-09-08 08:05:57 +00002158 ElementType(elementType), Destroyer(destroyer),
2159 ElementAlign(elementAlign) {}
John McCall82fe67b2011-07-09 01:37:26 +00002160
Craig Topper4f12f102014-03-12 06:41:41 +00002161 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall82fe67b2011-07-09 01:37:26 +00002162 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
John McCall178360e2011-07-11 08:38:19 +00002163 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00002164 ElementType, ElementAlign, Destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00002165 }
2166 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002167} // end anonymous namespace
John McCall82fe67b2011-07-09 01:37:26 +00002168
John McCall178360e2011-07-11 08:38:19 +00002169/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
John McCall82fe67b2011-07-09 01:37:26 +00002170/// already-constructed elements of the given array. The cleanup
John McCall178360e2011-07-11 08:38:19 +00002171/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00002172///
John McCall82fe67b2011-07-09 01:37:26 +00002173/// \param elementType - the immediate element type of the array;
2174/// possibly still an array type
John McCall4bd0fb12011-07-12 16:41:08 +00002175void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00002176 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00002177 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00002178 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00002179 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00002180 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
2181 arrayBegin, arrayEndPointer,
John McCall7f416cc2015-09-08 08:05:57 +00002182 elementType, elementAlign,
2183 destroyer);
John McCall178360e2011-07-11 08:38:19 +00002184}
2185
2186/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
2187/// already-constructed elements of the given array. The cleanup
2188/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00002189///
John McCall178360e2011-07-11 08:38:19 +00002190/// \param elementType - the immediate element type of the array;
2191/// possibly still an array type
John McCall178360e2011-07-11 08:38:19 +00002192void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
2193 llvm::Value *arrayEnd,
2194 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00002195 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00002196 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00002197 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
John McCall178360e2011-07-11 08:38:19 +00002198 arrayBegin, arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00002199 elementType, elementAlign,
2200 destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00002201}
2202
Nadav Rotem1da30942013-03-23 06:43:35 +00002203/// Lazily declare the @llvm.lifetime.start intrinsic.
2204llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
Matt Arsenaultd9729492017-04-10 20:18:45 +00002205 if (LifetimeStartFn)
2206 return LifetimeStartFn;
Nadav Rotem1da30942013-03-23 06:43:35 +00002207 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
Yaxun Liu7f7f3232017-04-17 20:03:11 +00002208 llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);
Nadav Rotem1da30942013-03-23 06:43:35 +00002209 return LifetimeStartFn;
2210}
2211
2212/// Lazily declare the @llvm.lifetime.end intrinsic.
2213llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
Matt Arsenaultd9729492017-04-10 20:18:45 +00002214 if (LifetimeEndFn)
2215 return LifetimeEndFn;
Nadav Rotem1da30942013-03-23 06:43:35 +00002216 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
Yaxun Liu7f7f3232017-04-17 20:03:11 +00002217 llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);
Nadav Rotem1da30942013-03-23 06:43:35 +00002218 return LifetimeEndFn;
2219}
2220
John McCall31168b02011-06-15 23:02:42 +00002221namespace {
2222 /// A cleanup to perform a release of an object at the end of a
2223 /// function. This is used to balance out the incoming +1 of a
2224 /// ns_consumed argument when we can't reasonably do that just by
2225 /// not doing the initial retain for a __block argument.
David Blaikie7e70d682015-08-18 22:40:54 +00002226 struct ConsumeARCParameter final : EHScopeStack::Cleanup {
John McCallcdda29c2013-03-13 03:10:54 +00002227 ConsumeARCParameter(llvm::Value *param,
2228 ARCPreciseLifetime_t precise)
2229 : Param(param), Precise(precise) {}
John McCall31168b02011-06-15 23:02:42 +00002230
2231 llvm::Value *Param;
John McCallcdda29c2013-03-13 03:10:54 +00002232 ARCPreciseLifetime_t Precise;
John McCall31168b02011-06-15 23:02:42 +00002233
Craig Topper4f12f102014-03-12 06:41:41 +00002234 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00002235 CGF.EmitARCRelease(Param, Precise);
John McCall31168b02011-06-15 23:02:42 +00002236 }
2237 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002238} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00002239
Mike Stump11289f42009-09-09 15:08:12 +00002240/// Emit an alloca (or GlobalValue depending on target)
Chris Lattnerb781dc792008-05-08 05:58:21 +00002241/// for the specified parameter and set up LocalDeclMap.
John McCall7f416cc2015-09-08 08:05:57 +00002242void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
2243 unsigned ArgNo) {
Daniel Dunbara94ecd22008-08-16 03:19:19 +00002244 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Guptad7959242008-10-31 09:52:39 +00002245 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbara94ecd22008-08-16 03:19:19 +00002246 "Invalid argument to EmitParmDecl");
John McCall147d0212011-02-22 22:38:33 +00002247
John McCall7f416cc2015-09-08 08:05:57 +00002248 Arg.getAnyValue()->setName(D.getName());
John McCall147d0212011-02-22 22:38:33 +00002249
Adrian Prantl51936dd2013-03-14 17:53:33 +00002250 QualType Ty = D.getType();
2251
John McCall147d0212011-02-22 22:38:33 +00002252 // Use better IR generation for certain implicit parameters.
John McCall7f416cc2015-09-08 08:05:57 +00002253 if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
John McCall147d0212011-02-22 22:38:33 +00002254 // The only implicit argument a block has is its literal.
Saleem Abdulrasoolc1b46382018-02-21 21:47:51 +00002255 // This may be passed as an inalloca'ed value on Windows x86.
John McCall147d0212011-02-22 22:38:33 +00002256 if (BlockInfo) {
Saleem Abdulrasoolc1b46382018-02-21 21:47:51 +00002257 llvm::Value *V = Arg.isIndirect()
2258 ? Builder.CreateLoad(Arg.getIndirectAddress())
2259 : Arg.getDirectValue();
2260 setBlockContextParameter(IPD, ArgNo, V);
John McCall147d0212011-02-22 22:38:33 +00002261 return;
2262 }
2263 }
2264
John McCall7f416cc2015-09-08 08:05:57 +00002265 Address DeclPtr = Address::invalid();
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002266 bool DoStore = false;
2267 bool IsScalar = hasScalarEvaluationKind(Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002268 // If we already have a pointer to the argument, reuse the input pointer.
John McCall7f416cc2015-09-08 08:05:57 +00002269 if (Arg.isIndirect()) {
2270 DeclPtr = Arg.getIndirectAddress();
Reid Kleckner5e8edba2014-04-02 00:16:53 +00002271 // If we have a prettier pointer type at this point, bitcast to that.
John McCall7f416cc2015-09-08 08:05:57 +00002272 unsigned AS = DeclPtr.getType()->getAddressSpace();
Reid Kleckner5e8edba2014-04-02 00:16:53 +00002273 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
John McCall7f416cc2015-09-08 08:05:57 +00002274 if (DeclPtr.getType() != IRTy)
2275 DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
Yaxun Liu5b330e82018-03-15 15:25:19 +00002276 // Indirect argument is in alloca address space, which may be different
2277 // from the default address space.
2278 auto AllocaAS = CGM.getASTAllocaAddressSpace();
2279 auto *V = DeclPtr.getPointer();
2280 auto SrcLangAS = getLangOpts().OpenCL ? LangAS::opencl_private : AllocaAS;
2281 auto DestLangAS =
2282 getLangOpts().OpenCL ? LangAS::opencl_private : LangAS::Default;
2283 if (SrcLangAS != DestLangAS) {
2284 assert(getContext().getTargetAddressSpace(SrcLangAS) ==
2285 CGM.getDataLayout().getAllocaAddrSpace());
2286 auto DestAS = getContext().getTargetAddressSpace(DestLangAS);
2287 auto *T = V->getType()->getPointerElementType()->getPointerTo(DestAS);
2288 DeclPtr = Address(getTargetHooks().performAddrSpaceCast(
2289 *this, V, SrcLangAS, DestLangAS, T, true),
2290 DeclPtr.getAlignment());
2291 }
John McCall7f416cc2015-09-08 08:05:57 +00002292
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002293 // Push a destructor cleanup for this parameter if the ABI requires it.
Reid Kleckner19819442014-07-25 21:39:46 +00002294 // Don't push a cleanup in a thunk for a method that will also emit a
2295 // cleanup.
Akira Hatanaka85282972018-05-15 21:00:30 +00002296 if (hasAggregateEvaluationKind(Ty) && !CurFuncIsThunk &&
2297 Ty->getAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
Akira Hatanaka7275da02018-02-28 07:15:55 +00002298 if (QualType::DestructionKind DtorKind = Ty.isDestructedType()) {
2299 assert((DtorKind == QualType::DK_cxx_destructor ||
2300 DtorKind == QualType::DK_nontrivial_c_struct) &&
2301 "unexpected destructor type");
2302 pushDestroy(DtorKind, DeclPtr, Ty);
Akira Hatanakaccda3d22018-04-27 06:57:00 +00002303 CalleeDestructedParamCleanups[cast<ParmVarDecl>(&D)] =
2304 EHStack.stable_begin();
Akira Hatanaka7275da02018-02-28 07:15:55 +00002305 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002306 }
Chris Lattner53621a52007-06-13 20:44:40 +00002307 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002308 // Check if the parameter address is controlled by OpenMP runtime.
2309 Address OpenMPLocalAddr =
2310 getLangOpts().OpenMP
2311 ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
2312 : Address::invalid();
2313 if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
2314 DeclPtr = OpenMPLocalAddr;
2315 } else {
2316 // Otherwise, create a temporary to hold the value.
2317 DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
2318 D.getName() + ".addr");
2319 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002320 DoStore = true;
2321 }
Mike Stump11289f42009-09-09 15:08:12 +00002322
John McCall7f416cc2015-09-08 08:05:57 +00002323 llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
2324
2325 LValue lv = MakeAddrLValue(DeclPtr, Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002326 if (IsScalar) {
John McCall31168b02011-06-15 23:02:42 +00002327 Qualifiers qs = Ty.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00002328 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
2329 // We honor __attribute__((ns_consumed)) for types with lifetime.
2330 // For __strong, it's handled by just skipping the initial retain;
2331 // otherwise we have to balance out the initial +1 with an extra
2332 // cleanup to do the release at the end of the function.
2333 bool isConsumed = D.hasAttr<NSConsumedAttr>();
2334
Erik Pilkington1e368822019-01-04 18:33:06 +00002335 // If a parameter is pseudo-strong then we can omit the implicit retain.
John McCalld4631322011-06-17 06:42:21 +00002336 if (D.isARCPseudoStrong()) {
Erik Pilkington1e368822019-01-04 18:33:06 +00002337 assert(lt == Qualifiers::OCL_Strong &&
2338 "pseudo-strong variable isn't strong?");
2339 assert(qs.hasConst() && "pseudo-strong variable should be const!");
John McCall31168b02011-06-15 23:02:42 +00002340 lt = Qualifiers::OCL_ExplicitNone;
2341 }
2342
Saleem Abdulrasoolda6784e2017-06-27 18:37:51 +00002343 // Load objects passed indirectly.
2344 if (Arg.isIndirect() && !ArgVal)
2345 ArgVal = Builder.CreateLoad(DeclPtr);
2346
John McCall31168b02011-06-15 23:02:42 +00002347 if (lt == Qualifiers::OCL_Strong) {
Fariborz Jahanian134cec62013-02-21 00:40:10 +00002348 if (!isConsumed) {
2349 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2350 // use objc_storeStrong(&dest, value) for retaining the
2351 // object. But first, store a null into 'dest' because
2352 // objc_storeStrong attempts to release its old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002353 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
Fariborz Jahanian134cec62013-02-21 00:40:10 +00002354 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
John McCall7f416cc2015-09-08 08:05:57 +00002355 EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002356 DoStore = false;
Fariborz Jahanian134cec62013-02-21 00:40:10 +00002357 }
2358 else
John McCall31168b02011-06-15 23:02:42 +00002359 // Don't use objc_retainBlock for block pointers, because we
2360 // don't want to Block_copy something just because we got it
2361 // as a parameter.
John McCall7f416cc2015-09-08 08:05:57 +00002362 ArgVal = EmitARCRetainNonBlock(ArgVal);
Fariborz Jahanian134cec62013-02-21 00:40:10 +00002363 }
John McCall31168b02011-06-15 23:02:42 +00002364 } else {
2365 // Push the cleanup for a consumed parameter.
John McCallcdda29c2013-03-13 03:10:54 +00002366 if (isConsumed) {
2367 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
2368 ? ARCPreciseLifetime : ARCImpreciseLifetime);
John McCall7f416cc2015-09-08 08:05:57 +00002369 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
John McCallcdda29c2013-03-13 03:10:54 +00002370 precise);
2371 }
John McCall31168b02011-06-15 23:02:42 +00002372
2373 if (lt == Qualifiers::OCL_Weak) {
John McCall7f416cc2015-09-08 08:05:57 +00002374 EmitARCInitWeak(DeclPtr, ArgVal);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002375 DoStore = false; // The weak init is a store, no need to do two.
John McCall31168b02011-06-15 23:02:42 +00002376 }
2377 }
2378
2379 // Enter the cleanup scope.
2380 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
2381 }
Chris Lattner53621a52007-06-13 20:44:40 +00002382 }
2383
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002384 // Store the initial value into the alloca.
2385 if (DoStore)
John McCall7f416cc2015-09-08 08:05:57 +00002386 EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002387
John McCall7f416cc2015-09-08 08:05:57 +00002388 setAddrOfLocalVar(&D, DeclPtr);
Sanjiv Gupta18de6242008-05-30 10:30:31 +00002389
2390 // Emit debug info for param declaration.
Alexey Samsonov74a38682012-05-04 07:39:27 +00002391 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00002392 if (CGM.getCodeGenOpts().getDebugInfo() >=
2393 codegenoptions::LimitedDebugInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00002394 DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00002395 }
2396 }
Julien Lerouge5a6b6982011-09-09 22:41:49 +00002397
2398 if (D.hasAttr<AnnotateAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00002399 EmitVarAnnotations(&D, DeclPtr.getPointer());
Vedant Kumar42c17ec2017-03-14 01:56:34 +00002400
2401 // We can only check return value nullability if all arguments to the
2402 // function satisfy their nullability preconditions. This makes it necessary
2403 // to emit null checks for args in the function body itself.
2404 if (requiresReturnValueNullabilityCheck()) {
2405 auto Nullability = Ty->getNullability(getContext());
2406 if (Nullability && *Nullability == NullabilityKind::NonNull) {
2407 SanitizerScope SanScope(this);
2408 RetValNullabilityPrecondition =
2409 Builder.CreateAnd(RetValNullabilityPrecondition,
2410 Builder.CreateIsNotNull(Arg.getAnyValue()));
2411 }
2412 }
Chris Lattner53621a52007-06-13 20:44:40 +00002413}
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002414
Alexey Bataevc5b1d322016-03-04 09:22:22 +00002415void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
2416 CodeGenFunction *CGF) {
2417 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
2418 return;
2419 getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
2420}
Kelvin Li1408f912018-09-26 04:28:39 +00002421
Michael Kruse251e1482019-02-01 20:25:04 +00002422void CodeGenModule::EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D,
2423 CodeGenFunction *CGF) {
2424 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
2425 return;
2426 // FIXME: need to implement mapper code generation
2427}
2428
Kelvin Li1408f912018-09-26 04:28:39 +00002429void CodeGenModule::EmitOMPRequiresDecl(const OMPRequiresDecl *D) {
Patrick Lyster8f7f5862018-11-19 15:09:33 +00002430 getOpenMPRuntime().checkArchForUnifiedAddressing(*this, D);
Kelvin Li1408f912018-09-26 04:28:39 +00002431}