[AMDGPU][AsmParser][NFC] Get rid of custom default operand handlers.
[llvm-project.git] / clang / lib / CodeGen / CGDecl.cpp
blob4c5d14e1e7028d423aa3a609590859a63268c0e4
1 //===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
2 //
3 // 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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This contains code to emit Decl nodes as LLVM code.
11 //===----------------------------------------------------------------------===//
13 #include "CGBlocks.h"
14 #include "CGCXXABI.h"
15 #include "CGCleanup.h"
16 #include "CGDebugInfo.h"
17 #include "CGOpenCLRuntime.h"
18 #include "CGOpenMPRuntime.h"
19 #include "CodeGenFunction.h"
20 #include "CodeGenModule.h"
21 #include "ConstantEmitter.h"
22 #include "PatternInit.h"
23 #include "TargetInfo.h"
24 #include "clang/AST/ASTContext.h"
25 #include "clang/AST/Attr.h"
26 #include "clang/AST/CharUnits.h"
27 #include "clang/AST/Decl.h"
28 #include "clang/AST/DeclObjC.h"
29 #include "clang/AST/DeclOpenMP.h"
30 #include "clang/Basic/CodeGenOptions.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "clang/Basic/TargetInfo.h"
33 #include "clang/CodeGen/CGFunctionInfo.h"
34 #include "clang/Sema/Sema.h"
35 #include "llvm/Analysis/ValueTracking.h"
36 #include "llvm/IR/DataLayout.h"
37 #include "llvm/IR/GlobalVariable.h"
38 #include "llvm/IR/Intrinsics.h"
39 #include "llvm/IR/Type.h"
40 #include <optional>
42 using namespace clang;
43 using namespace CodeGen;
45 static_assert(clang::Sema::MaximumAlignment <= llvm::Value::MaximumAlignment,
46 "Clang max alignment greater than what LLVM supports?");
48 void CodeGenFunction::EmitDecl(const Decl &D) {
49 switch (D.getKind()) {
50 case Decl::BuiltinTemplate:
51 case Decl::TranslationUnit:
52 case Decl::ExternCContext:
53 case Decl::Namespace:
54 case Decl::UnresolvedUsingTypename:
55 case Decl::ClassTemplateSpecialization:
56 case Decl::ClassTemplatePartialSpecialization:
57 case Decl::VarTemplateSpecialization:
58 case Decl::VarTemplatePartialSpecialization:
59 case Decl::TemplateTypeParm:
60 case Decl::UnresolvedUsingValue:
61 case Decl::NonTypeTemplateParm:
62 case Decl::CXXDeductionGuide:
63 case Decl::CXXMethod:
64 case Decl::CXXConstructor:
65 case Decl::CXXDestructor:
66 case Decl::CXXConversion:
67 case Decl::Field:
68 case Decl::MSProperty:
69 case Decl::IndirectField:
70 case Decl::ObjCIvar:
71 case Decl::ObjCAtDefsField:
72 case Decl::ParmVar:
73 case Decl::ImplicitParam:
74 case Decl::ClassTemplate:
75 case Decl::VarTemplate:
76 case Decl::FunctionTemplate:
77 case Decl::TypeAliasTemplate:
78 case Decl::TemplateTemplateParm:
79 case Decl::ObjCMethod:
80 case Decl::ObjCCategory:
81 case Decl::ObjCProtocol:
82 case Decl::ObjCInterface:
83 case Decl::ObjCCategoryImpl:
84 case Decl::ObjCImplementation:
85 case Decl::ObjCProperty:
86 case Decl::ObjCCompatibleAlias:
87 case Decl::PragmaComment:
88 case Decl::PragmaDetectMismatch:
89 case Decl::AccessSpec:
90 case Decl::LinkageSpec:
91 case Decl::Export:
92 case Decl::ObjCPropertyImpl:
93 case Decl::FileScopeAsm:
94 case Decl::TopLevelStmt:
95 case Decl::Friend:
96 case Decl::FriendTemplate:
97 case Decl::Block:
98 case Decl::Captured:
99 case Decl::ClassScopeFunctionSpecialization:
100 case Decl::UsingShadow:
101 case Decl::ConstructorUsingShadow:
102 case Decl::ObjCTypeParam:
103 case Decl::Binding:
104 case Decl::UnresolvedUsingIfExists:
105 case Decl::HLSLBuffer:
106 llvm_unreachable("Declaration should not be in declstmts!");
107 case Decl::Record: // struct/union/class X;
108 case Decl::CXXRecord: // struct/union/class X; [C++]
109 if (CGDebugInfo *DI = getDebugInfo())
110 if (cast<RecordDecl>(D).getDefinition())
111 DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(&D)));
112 return;
113 case Decl::Enum: // enum X;
114 if (CGDebugInfo *DI = getDebugInfo())
115 if (cast<EnumDecl>(D).getDefinition())
116 DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(&D)));
117 return;
118 case Decl::Function: // void X();
119 case Decl::EnumConstant: // enum ? { X = ? }
120 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
121 case Decl::Label: // __label__ x;
122 case Decl::Import:
123 case Decl::MSGuid: // __declspec(uuid("..."))
124 case Decl::UnnamedGlobalConstant:
125 case Decl::TemplateParamObject:
126 case Decl::OMPThreadPrivate:
127 case Decl::OMPAllocate:
128 case Decl::OMPCapturedExpr:
129 case Decl::OMPRequires:
130 case Decl::Empty:
131 case Decl::Concept:
132 case Decl::ImplicitConceptSpecialization:
133 case Decl::LifetimeExtendedTemporary:
134 case Decl::RequiresExprBody:
135 // None of these decls require codegen support.
136 return;
138 case Decl::NamespaceAlias:
139 if (CGDebugInfo *DI = getDebugInfo())
140 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
141 return;
142 case Decl::Using: // using X; [C++]
143 if (CGDebugInfo *DI = getDebugInfo())
144 DI->EmitUsingDecl(cast<UsingDecl>(D));
145 return;
146 case Decl::UsingEnum: // using enum X; [C++]
147 if (CGDebugInfo *DI = getDebugInfo())
148 DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(D));
149 return;
150 case Decl::UsingPack:
151 for (auto *Using : cast<UsingPackDecl>(D).expansions())
152 EmitDecl(*Using);
153 return;
154 case Decl::UsingDirective: // using namespace X; [C++]
155 if (CGDebugInfo *DI = getDebugInfo())
156 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
157 return;
158 case Decl::Var:
159 case Decl::Decomposition: {
160 const VarDecl &VD = cast<VarDecl>(D);
161 assert(VD.isLocalVarDecl() &&
162 "Should not see file-scope variables inside a function!");
163 EmitVarDecl(VD);
164 if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
165 for (auto *B : DD->bindings())
166 if (auto *HD = B->getHoldingVar())
167 EmitVarDecl(*HD);
168 return;
171 case Decl::OMPDeclareReduction:
172 return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
174 case Decl::OMPDeclareMapper:
175 return CGM.EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(&D), this);
177 case Decl::Typedef: // typedef int X;
178 case Decl::TypeAlias: { // using X = int; [C++0x]
179 QualType Ty = cast<TypedefNameDecl>(D).getUnderlyingType();
180 if (CGDebugInfo *DI = getDebugInfo())
181 DI->EmitAndRetainType(Ty);
182 if (Ty->isVariablyModifiedType())
183 EmitVariablyModifiedType(Ty);
184 return;
189 /// EmitVarDecl - This method handles emission of any variable declaration
190 /// inside a function, including static vars etc.
191 void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
192 if (D.hasExternalStorage())
193 // Don't emit it now, allow it to be emitted lazily on its first use.
194 return;
196 // Some function-scope variable does not have static storage but still
197 // needs to be emitted like a static variable, e.g. a function-scope
198 // variable in constant address space in OpenCL.
199 if (D.getStorageDuration() != SD_Automatic) {
200 // Static sampler variables translated to function calls.
201 if (D.getType()->isSamplerT())
202 return;
204 llvm::GlobalValue::LinkageTypes Linkage =
205 CGM.getLLVMLinkageVarDefinition(&D, /*IsConstant=*/false);
207 // FIXME: We need to force the emission/use of a guard variable for
208 // some variables even if we can constant-evaluate them because
209 // we can't guarantee every translation unit will constant-evaluate them.
211 return EmitStaticVarDecl(D, Linkage);
214 if (D.getType().getAddressSpace() == LangAS::opencl_local)
215 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
217 assert(D.hasLocalStorage());
218 return EmitAutoVarDecl(D);
221 static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
222 if (CGM.getLangOpts().CPlusPlus)
223 return CGM.getMangledName(&D).str();
225 // If this isn't C++, we don't need a mangled name, just a pretty one.
226 assert(!D.isExternallyVisible() && "name shouldn't matter");
227 std::string ContextName;
228 const DeclContext *DC = D.getDeclContext();
229 if (auto *CD = dyn_cast<CapturedDecl>(DC))
230 DC = cast<DeclContext>(CD->getNonClosureContext());
231 if (const auto *FD = dyn_cast<FunctionDecl>(DC))
232 ContextName = std::string(CGM.getMangledName(FD));
233 else if (const auto *BD = dyn_cast<BlockDecl>(DC))
234 ContextName = std::string(CGM.getBlockMangledName(GlobalDecl(), BD));
235 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
236 ContextName = OMD->getSelector().getAsString();
237 else
238 llvm_unreachable("Unknown context for static var decl");
240 ContextName += "." + D.getNameAsString();
241 return ContextName;
244 llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
245 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
246 // In general, we don't always emit static var decls once before we reference
247 // them. It is possible to reference them before emitting the function that
248 // contains them, and it is possible to emit the containing function multiple
249 // times.
250 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
251 return ExistingGV;
253 QualType Ty = D.getType();
254 assert(Ty->isConstantSizeType() && "VLAs can't be static");
256 // Use the label if the variable is renamed with the asm-label extension.
257 std::string Name;
258 if (D.hasAttr<AsmLabelAttr>())
259 Name = std::string(getMangledName(&D));
260 else
261 Name = getStaticDeclName(*this, D);
263 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
264 LangAS AS = GetGlobalVarAddressSpace(&D);
265 unsigned TargetAS = getContext().getTargetAddressSpace(AS);
267 // OpenCL variables in local address space and CUDA shared
268 // variables cannot have an initializer.
269 llvm::Constant *Init = nullptr;
270 if (Ty.getAddressSpace() == LangAS::opencl_local ||
271 D.hasAttr<CUDASharedAttr>() || D.hasAttr<LoaderUninitializedAttr>())
272 Init = llvm::UndefValue::get(LTy);
273 else
274 Init = EmitNullConstant(Ty);
276 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
277 getModule(), LTy, Ty.isConstant(getContext()), Linkage, Init, Name,
278 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
279 GV->setAlignment(getContext().getDeclAlign(&D).getAsAlign());
281 if (supportsCOMDAT() && GV->isWeakForLinker())
282 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
284 if (D.getTLSKind())
285 setTLSMode(GV, D);
287 setGVProperties(GV, &D);
289 // Make sure the result is of the correct type.
290 LangAS ExpectedAS = Ty.getAddressSpace();
291 llvm::Constant *Addr = GV;
292 if (AS != ExpectedAS) {
293 Addr = getTargetCodeGenInfo().performAddrSpaceCast(
294 *this, GV, AS, ExpectedAS,
295 LTy->getPointerTo(getContext().getTargetAddressSpace(ExpectedAS)));
298 setStaticLocalDeclAddress(&D, Addr);
300 // Ensure that the static local gets initialized by making sure the parent
301 // function gets emitted eventually.
302 const Decl *DC = cast<Decl>(D.getDeclContext());
304 // We can't name blocks or captured statements directly, so try to emit their
305 // parents.
306 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
307 DC = DC->getNonClosureContext();
308 // FIXME: Ensure that global blocks get emitted.
309 if (!DC)
310 return Addr;
313 GlobalDecl GD;
314 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
315 GD = GlobalDecl(CD, Ctor_Base);
316 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
317 GD = GlobalDecl(DD, Dtor_Base);
318 else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
319 GD = GlobalDecl(FD);
320 else {
321 // Don't do anything for Obj-C method decls or global closures. We should
322 // never defer them.
323 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
325 if (GD.getDecl()) {
326 // Disable emission of the parent function for the OpenMP device codegen.
327 CGOpenMPRuntime::DisableAutoDeclareTargetRAII NoDeclTarget(*this);
328 (void)GetAddrOfGlobal(GD);
331 return Addr;
334 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
335 /// global variable that has already been created for it. If the initializer
336 /// has a different type than GV does, this may free GV and return a different
337 /// one. Otherwise it just returns GV.
338 llvm::GlobalVariable *
339 CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
340 llvm::GlobalVariable *GV) {
341 ConstantEmitter emitter(*this);
342 llvm::Constant *Init = emitter.tryEmitForInitializer(D);
344 // If constant emission failed, then this should be a C++ static
345 // initializer.
346 if (!Init) {
347 if (!getLangOpts().CPlusPlus)
348 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
349 else if (D.hasFlexibleArrayInit(getContext()))
350 CGM.ErrorUnsupported(D.getInit(), "flexible array initializer");
351 else if (HaveInsertPoint()) {
352 // Since we have a static initializer, this global variable can't
353 // be constant.
354 GV->setConstant(false);
356 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
358 return GV;
361 #ifndef NDEBUG
362 CharUnits VarSize = CGM.getContext().getTypeSizeInChars(D.getType()) +
363 D.getFlexibleArrayInitChars(getContext());
364 CharUnits CstSize = CharUnits::fromQuantity(
365 CGM.getDataLayout().getTypeAllocSize(Init->getType()));
366 assert(VarSize == CstSize && "Emitted constant has unexpected size");
367 #endif
369 // The initializer may differ in type from the global. Rewrite
370 // the global to match the initializer. (We have to do this
371 // because some types, like unions, can't be completely represented
372 // in the LLVM type system.)
373 if (GV->getValueType() != Init->getType()) {
374 llvm::GlobalVariable *OldGV = GV;
376 GV = new llvm::GlobalVariable(
377 CGM.getModule(), Init->getType(), OldGV->isConstant(),
378 OldGV->getLinkage(), Init, "",
379 /*InsertBefore*/ OldGV, OldGV->getThreadLocalMode(),
380 OldGV->getType()->getPointerAddressSpace());
381 GV->setVisibility(OldGV->getVisibility());
382 GV->setDSOLocal(OldGV->isDSOLocal());
383 GV->setComdat(OldGV->getComdat());
385 // Steal the name of the old global
386 GV->takeName(OldGV);
388 // Replace all uses of the old global with the new global
389 llvm::Constant *NewPtrForOldDecl =
390 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
391 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
393 // Erase the old global, since it is no longer used.
394 OldGV->eraseFromParent();
397 bool NeedsDtor =
398 D.needsDestruction(getContext()) == QualType::DK_cxx_destructor;
400 GV->setConstant(CGM.isTypeConstant(D.getType(), true, !NeedsDtor));
401 GV->setInitializer(Init);
403 emitter.finalize(GV);
405 if (NeedsDtor && HaveInsertPoint()) {
406 // We have a constant initializer, but a nontrivial destructor. We still
407 // need to perform a guarded "initialization" in order to register the
408 // destructor.
409 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
412 return GV;
415 void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
416 llvm::GlobalValue::LinkageTypes Linkage) {
417 // Check to see if we already have a global variable for this
418 // declaration. This can happen when double-emitting function
419 // bodies, e.g. with complete and base constructors.
420 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
421 CharUnits alignment = getContext().getDeclAlign(&D);
423 // Store into LocalDeclMap before generating initializer to handle
424 // circular references.
425 llvm::Type *elemTy = ConvertTypeForMem(D.getType());
426 setAddrOfLocalVar(&D, Address(addr, elemTy, alignment));
428 // We can't have a VLA here, but we can have a pointer to a VLA,
429 // even though that doesn't really make any sense.
430 // Make sure to evaluate VLA bounds now so that we have them for later.
431 if (D.getType()->isVariablyModifiedType())
432 EmitVariablyModifiedType(D.getType());
434 // Save the type in case adding the initializer forces a type change.
435 llvm::Type *expectedType = addr->getType();
437 llvm::GlobalVariable *var =
438 cast<llvm::GlobalVariable>(addr->stripPointerCasts());
440 // CUDA's local and local static __shared__ variables should not
441 // have any non-empty initializers. This is ensured by Sema.
442 // Whatever initializer such variable may have when it gets here is
443 // a no-op and should not be emitted.
444 bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
445 D.hasAttr<CUDASharedAttr>();
446 // If this value has an initializer, emit it.
447 if (D.getInit() && !isCudaSharedVar)
448 var = AddInitializerToStaticVarDecl(D, var);
450 var->setAlignment(alignment.getAsAlign());
452 if (D.hasAttr<AnnotateAttr>())
453 CGM.AddGlobalAnnotations(&D, var);
455 if (auto *SA = D.getAttr<PragmaClangBSSSectionAttr>())
456 var->addAttribute("bss-section", SA->getName());
457 if (auto *SA = D.getAttr<PragmaClangDataSectionAttr>())
458 var->addAttribute("data-section", SA->getName());
459 if (auto *SA = D.getAttr<PragmaClangRodataSectionAttr>())
460 var->addAttribute("rodata-section", SA->getName());
461 if (auto *SA = D.getAttr<PragmaClangRelroSectionAttr>())
462 var->addAttribute("relro-section", SA->getName());
464 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
465 var->setSection(SA->getName());
467 if (D.hasAttr<RetainAttr>())
468 CGM.addUsedGlobal(var);
469 else if (D.hasAttr<UsedAttr>())
470 CGM.addUsedOrCompilerUsedGlobal(var);
472 // We may have to cast the constant because of the initializer
473 // mismatch above.
475 // FIXME: It is really dangerous to store this in the map; if anyone
476 // RAUW's the GV uses of this constant will be invalid.
477 llvm::Constant *castedAddr =
478 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
479 LocalDeclMap.find(&D)->second = Address(castedAddr, elemTy, alignment);
480 CGM.setStaticLocalDeclAddress(&D, castedAddr);
482 CGM.getSanitizerMetadata()->reportGlobal(var, D);
484 // Emit global variable debug descriptor for static vars.
485 CGDebugInfo *DI = getDebugInfo();
486 if (DI && CGM.getCodeGenOpts().hasReducedDebugInfo()) {
487 DI->setLocation(D.getLocation());
488 DI->EmitGlobalVariable(var, &D);
492 namespace {
493 struct DestroyObject final : EHScopeStack::Cleanup {
494 DestroyObject(Address addr, QualType type,
495 CodeGenFunction::Destroyer *destroyer,
496 bool useEHCleanupForArray)
497 : addr(addr), type(type), destroyer(destroyer),
498 useEHCleanupForArray(useEHCleanupForArray) {}
500 Address addr;
501 QualType type;
502 CodeGenFunction::Destroyer *destroyer;
503 bool useEHCleanupForArray;
505 void Emit(CodeGenFunction &CGF, Flags flags) override {
506 // Don't use an EH cleanup recursively from an EH cleanup.
507 bool useEHCleanupForArray =
508 flags.isForNormalCleanup() && this->useEHCleanupForArray;
510 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
514 template <class Derived>
515 struct DestroyNRVOVariable : EHScopeStack::Cleanup {
516 DestroyNRVOVariable(Address addr, QualType type, llvm::Value *NRVOFlag)
517 : NRVOFlag(NRVOFlag), Loc(addr), Ty(type) {}
519 llvm::Value *NRVOFlag;
520 Address Loc;
521 QualType Ty;
523 void Emit(CodeGenFunction &CGF, Flags flags) override {
524 // Along the exceptions path we always execute the dtor.
525 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
527 llvm::BasicBlock *SkipDtorBB = nullptr;
528 if (NRVO) {
529 // If we exited via NRVO, we skip the destructor call.
530 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
531 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
532 llvm::Value *DidNRVO =
533 CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
534 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
535 CGF.EmitBlock(RunDtorBB);
538 static_cast<Derived *>(this)->emitDestructorCall(CGF);
540 if (NRVO) CGF.EmitBlock(SkipDtorBB);
543 virtual ~DestroyNRVOVariable() = default;
546 struct DestroyNRVOVariableCXX final
547 : DestroyNRVOVariable<DestroyNRVOVariableCXX> {
548 DestroyNRVOVariableCXX(Address addr, QualType type,
549 const CXXDestructorDecl *Dtor, llvm::Value *NRVOFlag)
550 : DestroyNRVOVariable<DestroyNRVOVariableCXX>(addr, type, NRVOFlag),
551 Dtor(Dtor) {}
553 const CXXDestructorDecl *Dtor;
555 void emitDestructorCall(CodeGenFunction &CGF) {
556 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
557 /*ForVirtualBase=*/false,
558 /*Delegating=*/false, Loc, Ty);
562 struct DestroyNRVOVariableC final
563 : DestroyNRVOVariable<DestroyNRVOVariableC> {
564 DestroyNRVOVariableC(Address addr, llvm::Value *NRVOFlag, QualType Ty)
565 : DestroyNRVOVariable<DestroyNRVOVariableC>(addr, Ty, NRVOFlag) {}
567 void emitDestructorCall(CodeGenFunction &CGF) {
568 CGF.destroyNonTrivialCStruct(CGF, Loc, Ty);
572 struct CallStackRestore final : EHScopeStack::Cleanup {
573 Address Stack;
574 CallStackRestore(Address Stack) : Stack(Stack) {}
575 bool isRedundantBeforeReturn() override { return true; }
576 void Emit(CodeGenFunction &CGF, Flags flags) override {
577 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
578 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
579 CGF.Builder.CreateCall(F, V);
583 struct ExtendGCLifetime final : EHScopeStack::Cleanup {
584 const VarDecl &Var;
585 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
587 void Emit(CodeGenFunction &CGF, Flags flags) override {
588 // Compute the address of the local variable, in case it's a
589 // byref or something.
590 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
591 Var.getType(), VK_LValue, SourceLocation());
592 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
593 SourceLocation());
594 CGF.EmitExtendGCLifetime(value);
598 struct CallCleanupFunction final : EHScopeStack::Cleanup {
599 llvm::Constant *CleanupFn;
600 const CGFunctionInfo &FnInfo;
601 const VarDecl &Var;
603 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
604 const VarDecl *Var)
605 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
607 void Emit(CodeGenFunction &CGF, Flags flags) override {
608 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
609 Var.getType(), VK_LValue, SourceLocation());
610 // Compute the address of the local variable, in case it's a byref
611 // or something.
612 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer(CGF);
614 // In some cases, the type of the function argument will be different from
615 // the type of the pointer. An example of this is
616 // void f(void* arg);
617 // __attribute__((cleanup(f))) void *g;
619 // To fix this we insert a bitcast here.
620 QualType ArgTy = FnInfo.arg_begin()->type;
621 llvm::Value *Arg =
622 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
624 CallArgList Args;
625 Args.add(RValue::get(Arg),
626 CGF.getContext().getPointerType(Var.getType()));
627 auto Callee = CGCallee::forDirect(CleanupFn);
628 CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
631 } // end anonymous namespace
633 /// EmitAutoVarWithLifetime - Does the setup required for an automatic
634 /// variable with lifetime.
635 static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
636 Address addr,
637 Qualifiers::ObjCLifetime lifetime) {
638 switch (lifetime) {
639 case Qualifiers::OCL_None:
640 llvm_unreachable("present but none");
642 case Qualifiers::OCL_ExplicitNone:
643 // nothing to do
644 break;
646 case Qualifiers::OCL_Strong: {
647 CodeGenFunction::Destroyer *destroyer =
648 (var.hasAttr<ObjCPreciseLifetimeAttr>()
649 ? CodeGenFunction::destroyARCStrongPrecise
650 : CodeGenFunction::destroyARCStrongImprecise);
652 CleanupKind cleanupKind = CGF.getARCCleanupKind();
653 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
654 cleanupKind & EHCleanup);
655 break;
657 case Qualifiers::OCL_Autoreleasing:
658 // nothing to do
659 break;
661 case Qualifiers::OCL_Weak:
662 // __weak objects always get EH cleanups; otherwise, exceptions
663 // could cause really nasty crashes instead of mere leaks.
664 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
665 CodeGenFunction::destroyARCWeak,
666 /*useEHCleanup*/ true);
667 break;
671 static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
672 if (const Expr *e = dyn_cast<Expr>(s)) {
673 // Skip the most common kinds of expressions that make
674 // hierarchy-walking expensive.
675 s = e = e->IgnoreParenCasts();
677 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
678 return (ref->getDecl() == &var);
679 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
680 const BlockDecl *block = be->getBlockDecl();
681 for (const auto &I : block->captures()) {
682 if (I.getVariable() == &var)
683 return true;
688 for (const Stmt *SubStmt : s->children())
689 // SubStmt might be null; as in missing decl or conditional of an if-stmt.
690 if (SubStmt && isAccessedBy(var, SubStmt))
691 return true;
693 return false;
696 static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
697 if (!decl) return false;
698 if (!isa<VarDecl>(decl)) return false;
699 const VarDecl *var = cast<VarDecl>(decl);
700 return isAccessedBy(*var, e);
703 static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
704 const LValue &destLV, const Expr *init) {
705 bool needsCast = false;
707 while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
708 switch (castExpr->getCastKind()) {
709 // Look through casts that don't require representation changes.
710 case CK_NoOp:
711 case CK_BitCast:
712 case CK_BlockPointerToObjCPointerCast:
713 needsCast = true;
714 break;
716 // If we find an l-value to r-value cast from a __weak variable,
717 // emit this operation as a copy or move.
718 case CK_LValueToRValue: {
719 const Expr *srcExpr = castExpr->getSubExpr();
720 if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
721 return false;
723 // Emit the source l-value.
724 LValue srcLV = CGF.EmitLValue(srcExpr);
726 // Handle a formal type change to avoid asserting.
727 auto srcAddr = srcLV.getAddress(CGF);
728 if (needsCast) {
729 srcAddr = CGF.Builder.CreateElementBitCast(
730 srcAddr, destLV.getAddress(CGF).getElementType());
733 // If it was an l-value, use objc_copyWeak.
734 if (srcExpr->isLValue()) {
735 CGF.EmitARCCopyWeak(destLV.getAddress(CGF), srcAddr);
736 } else {
737 assert(srcExpr->isXValue());
738 CGF.EmitARCMoveWeak(destLV.getAddress(CGF), srcAddr);
740 return true;
743 // Stop at anything else.
744 default:
745 return false;
748 init = castExpr->getSubExpr();
750 return false;
753 static void drillIntoBlockVariable(CodeGenFunction &CGF,
754 LValue &lvalue,
755 const VarDecl *var) {
756 lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(CGF), var));
759 void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS,
760 SourceLocation Loc) {
761 if (!SanOpts.has(SanitizerKind::NullabilityAssign))
762 return;
764 auto Nullability = LHS.getType()->getNullability();
765 if (!Nullability || *Nullability != NullabilityKind::NonNull)
766 return;
768 // Check if the right hand side of the assignment is nonnull, if the left
769 // hand side must be nonnull.
770 SanitizerScope SanScope(this);
771 llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS);
772 llvm::Constant *StaticData[] = {
773 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(LHS.getType()),
774 llvm::ConstantInt::get(Int8Ty, 0), // The LogAlignment info is unused.
775 llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)};
776 EmitCheck({{IsNotNull, SanitizerKind::NullabilityAssign}},
777 SanitizerHandler::TypeMismatch, StaticData, RHS);
780 void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
781 LValue lvalue, bool capturedByInit) {
782 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
783 if (!lifetime) {
784 llvm::Value *value = EmitScalarExpr(init);
785 if (capturedByInit)
786 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
787 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
788 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
789 return;
792 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
793 init = DIE->getExpr();
795 // If we're emitting a value with lifetime, we have to do the
796 // initialization *before* we leave the cleanup scopes.
797 if (auto *EWC = dyn_cast<ExprWithCleanups>(init)) {
798 CodeGenFunction::RunCleanupsScope Scope(*this);
799 return EmitScalarInit(EWC->getSubExpr(), D, lvalue, capturedByInit);
802 // We have to maintain the illusion that the variable is
803 // zero-initialized. If the variable might be accessed in its
804 // initializer, zero-initialize before running the initializer, then
805 // actually perform the initialization with an assign.
806 bool accessedByInit = false;
807 if (lifetime != Qualifiers::OCL_ExplicitNone)
808 accessedByInit = (capturedByInit || isAccessedBy(D, init));
809 if (accessedByInit) {
810 LValue tempLV = lvalue;
811 // Drill down to the __block object if necessary.
812 if (capturedByInit) {
813 // We can use a simple GEP for this because it can't have been
814 // moved yet.
815 tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(*this),
816 cast<VarDecl>(D),
817 /*follow*/ false));
820 auto ty =
821 cast<llvm::PointerType>(tempLV.getAddress(*this).getElementType());
822 llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());
824 // If __weak, we want to use a barrier under certain conditions.
825 if (lifetime == Qualifiers::OCL_Weak)
826 EmitARCInitWeak(tempLV.getAddress(*this), zero);
828 // Otherwise just do a simple store.
829 else
830 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
833 // Emit the initializer.
834 llvm::Value *value = nullptr;
836 switch (lifetime) {
837 case Qualifiers::OCL_None:
838 llvm_unreachable("present but none");
840 case Qualifiers::OCL_Strong: {
841 if (!D || !isa<VarDecl>(D) || !cast<VarDecl>(D)->isARCPseudoStrong()) {
842 value = EmitARCRetainScalarExpr(init);
843 break;
845 // If D is pseudo-strong, treat it like __unsafe_unretained here. This means
846 // that we omit the retain, and causes non-autoreleased return values to be
847 // immediately released.
848 [[fallthrough]];
851 case Qualifiers::OCL_ExplicitNone:
852 value = EmitARCUnsafeUnretainedScalarExpr(init);
853 break;
855 case Qualifiers::OCL_Weak: {
856 // If it's not accessed by the initializer, try to emit the
857 // initialization with a copy or move.
858 if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
859 return;
862 // No way to optimize a producing initializer into this. It's not
863 // worth optimizing for, because the value will immediately
864 // disappear in the common case.
865 value = EmitScalarExpr(init);
867 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
868 if (accessedByInit)
869 EmitARCStoreWeak(lvalue.getAddress(*this), value, /*ignored*/ true);
870 else
871 EmitARCInitWeak(lvalue.getAddress(*this), value);
872 return;
875 case Qualifiers::OCL_Autoreleasing:
876 value = EmitARCRetainAutoreleaseScalarExpr(init);
877 break;
880 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
882 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
884 // If the variable might have been accessed by its initializer, we
885 // might have to initialize with a barrier. We have to do this for
886 // both __weak and __strong, but __weak got filtered out above.
887 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
888 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
889 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
890 EmitARCRelease(oldValue, ARCImpreciseLifetime);
891 return;
894 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
897 /// Decide whether we can emit the non-zero parts of the specified initializer
898 /// with equal or fewer than NumStores scalar stores.
899 static bool canEmitInitWithFewStoresAfterBZero(llvm::Constant *Init,
900 unsigned &NumStores) {
901 // Zero and Undef never requires any extra stores.
902 if (isa<llvm::ConstantAggregateZero>(Init) ||
903 isa<llvm::ConstantPointerNull>(Init) ||
904 isa<llvm::UndefValue>(Init))
905 return true;
906 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
907 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
908 isa<llvm::ConstantExpr>(Init))
909 return Init->isNullValue() || NumStores--;
911 // See if we can emit each element.
912 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
913 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
914 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
915 if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
916 return false;
918 return true;
921 if (llvm::ConstantDataSequential *CDS =
922 dyn_cast<llvm::ConstantDataSequential>(Init)) {
923 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
924 llvm::Constant *Elt = CDS->getElementAsConstant(i);
925 if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
926 return false;
928 return true;
931 // Anything else is hard and scary.
932 return false;
935 /// For inits that canEmitInitWithFewStoresAfterBZero returned true for, emit
936 /// the scalar stores that would be required.
937 static void emitStoresForInitAfterBZero(CodeGenModule &CGM,
938 llvm::Constant *Init, Address Loc,
939 bool isVolatile, CGBuilderTy &Builder,
940 bool IsAutoInit) {
941 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
942 "called emitStoresForInitAfterBZero for zero or undef value.");
944 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
945 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
946 isa<llvm::ConstantExpr>(Init)) {
947 auto *I = Builder.CreateStore(Init, Loc, isVolatile);
948 if (IsAutoInit)
949 I->addAnnotationMetadata("auto-init");
950 return;
953 if (llvm::ConstantDataSequential *CDS =
954 dyn_cast<llvm::ConstantDataSequential>(Init)) {
955 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
956 llvm::Constant *Elt = CDS->getElementAsConstant(i);
958 // If necessary, get a pointer to the element and emit it.
959 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
960 emitStoresForInitAfterBZero(
961 CGM, Elt, Builder.CreateConstInBoundsGEP2_32(Loc, 0, i), isVolatile,
962 Builder, IsAutoInit);
964 return;
967 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
968 "Unknown value type!");
970 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
971 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
973 // If necessary, get a pointer to the element and emit it.
974 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
975 emitStoresForInitAfterBZero(CGM, Elt,
976 Builder.CreateConstInBoundsGEP2_32(Loc, 0, i),
977 isVolatile, Builder, IsAutoInit);
981 /// Decide whether we should use bzero plus some stores to initialize a local
982 /// variable instead of using a memcpy from a constant global. It is beneficial
983 /// to use bzero if the global is all zeros, or mostly zeros and large.
984 static bool shouldUseBZeroPlusStoresToInitialize(llvm::Constant *Init,
985 uint64_t GlobalSize) {
986 // If a global is all zeros, always use a bzero.
987 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
989 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
990 // do it if it will require 6 or fewer scalar stores.
991 // TODO: Should budget depends on the size? Avoiding a large global warrants
992 // plopping in more stores.
993 unsigned StoreBudget = 6;
994 uint64_t SizeLimit = 32;
996 return GlobalSize > SizeLimit &&
997 canEmitInitWithFewStoresAfterBZero(Init, StoreBudget);
1000 /// Decide whether we should use memset to initialize a local variable instead
1001 /// of using a memcpy from a constant global. Assumes we've already decided to
1002 /// not user bzero.
1003 /// FIXME We could be more clever, as we are for bzero above, and generate
1004 /// memset followed by stores. It's unclear that's worth the effort.
1005 static llvm::Value *shouldUseMemSetToInitialize(llvm::Constant *Init,
1006 uint64_t GlobalSize,
1007 const llvm::DataLayout &DL) {
1008 uint64_t SizeLimit = 32;
1009 if (GlobalSize <= SizeLimit)
1010 return nullptr;
1011 return llvm::isBytewiseValue(Init, DL);
1014 /// Decide whether we want to split a constant structure or array store into a
1015 /// sequence of its fields' stores. This may cost us code size and compilation
1016 /// speed, but plays better with store optimizations.
1017 static bool shouldSplitConstantStore(CodeGenModule &CGM,
1018 uint64_t GlobalByteSize) {
1019 // Don't break things that occupy more than one cacheline.
1020 uint64_t ByteSizeLimit = 64;
1021 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
1022 return false;
1023 if (GlobalByteSize <= ByteSizeLimit)
1024 return true;
1025 return false;
1028 enum class IsPattern { No, Yes };
1030 /// Generate a constant filled with either a pattern or zeroes.
1031 static llvm::Constant *patternOrZeroFor(CodeGenModule &CGM, IsPattern isPattern,
1032 llvm::Type *Ty) {
1033 if (isPattern == IsPattern::Yes)
1034 return initializationPatternFor(CGM, Ty);
1035 else
1036 return llvm::Constant::getNullValue(Ty);
1039 static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
1040 llvm::Constant *constant);
1042 /// Helper function for constWithPadding() to deal with padding in structures.
1043 static llvm::Constant *constStructWithPadding(CodeGenModule &CGM,
1044 IsPattern isPattern,
1045 llvm::StructType *STy,
1046 llvm::Constant *constant) {
1047 const llvm::DataLayout &DL = CGM.getDataLayout();
1048 const llvm::StructLayout *Layout = DL.getStructLayout(STy);
1049 llvm::Type *Int8Ty = llvm::IntegerType::getInt8Ty(CGM.getLLVMContext());
1050 unsigned SizeSoFar = 0;
1051 SmallVector<llvm::Constant *, 8> Values;
1052 bool NestedIntact = true;
1053 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1054 unsigned CurOff = Layout->getElementOffset(i);
1055 if (SizeSoFar < CurOff) {
1056 assert(!STy->isPacked());
1057 auto *PadTy = llvm::ArrayType::get(Int8Ty, CurOff - SizeSoFar);
1058 Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy));
1060 llvm::Constant *CurOp;
1061 if (constant->isZeroValue())
1062 CurOp = llvm::Constant::getNullValue(STy->getElementType(i));
1063 else
1064 CurOp = cast<llvm::Constant>(constant->getAggregateElement(i));
1065 auto *NewOp = constWithPadding(CGM, isPattern, CurOp);
1066 if (CurOp != NewOp)
1067 NestedIntact = false;
1068 Values.push_back(NewOp);
1069 SizeSoFar = CurOff + DL.getTypeAllocSize(CurOp->getType());
1071 unsigned TotalSize = Layout->getSizeInBytes();
1072 if (SizeSoFar < TotalSize) {
1073 auto *PadTy = llvm::ArrayType::get(Int8Ty, TotalSize - SizeSoFar);
1074 Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy));
1076 if (NestedIntact && Values.size() == STy->getNumElements())
1077 return constant;
1078 return llvm::ConstantStruct::getAnon(Values, STy->isPacked());
1081 /// Replace all padding bytes in a given constant with either a pattern byte or
1082 /// 0x00.
1083 static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
1084 llvm::Constant *constant) {
1085 llvm::Type *OrigTy = constant->getType();
1086 if (const auto STy = dyn_cast<llvm::StructType>(OrigTy))
1087 return constStructWithPadding(CGM, isPattern, STy, constant);
1088 if (auto *ArrayTy = dyn_cast<llvm::ArrayType>(OrigTy)) {
1089 llvm::SmallVector<llvm::Constant *, 8> Values;
1090 uint64_t Size = ArrayTy->getNumElements();
1091 if (!Size)
1092 return constant;
1093 llvm::Type *ElemTy = ArrayTy->getElementType();
1094 bool ZeroInitializer = constant->isNullValue();
1095 llvm::Constant *OpValue, *PaddedOp;
1096 if (ZeroInitializer) {
1097 OpValue = llvm::Constant::getNullValue(ElemTy);
1098 PaddedOp = constWithPadding(CGM, isPattern, OpValue);
1100 for (unsigned Op = 0; Op != Size; ++Op) {
1101 if (!ZeroInitializer) {
1102 OpValue = constant->getAggregateElement(Op);
1103 PaddedOp = constWithPadding(CGM, isPattern, OpValue);
1105 Values.push_back(PaddedOp);
1107 auto *NewElemTy = Values[0]->getType();
1108 if (NewElemTy == ElemTy)
1109 return constant;
1110 auto *NewArrayTy = llvm::ArrayType::get(NewElemTy, Size);
1111 return llvm::ConstantArray::get(NewArrayTy, Values);
1113 // FIXME: Add handling for tail padding in vectors. Vectors don't
1114 // have padding between or inside elements, but the total amount of
1115 // data can be less than the allocated size.
1116 return constant;
1119 Address CodeGenModule::createUnnamedGlobalFrom(const VarDecl &D,
1120 llvm::Constant *Constant,
1121 CharUnits Align) {
1122 auto FunctionName = [&](const DeclContext *DC) -> std::string {
1123 if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
1124 if (const auto *CC = dyn_cast<CXXConstructorDecl>(FD))
1125 return CC->getNameAsString();
1126 if (const auto *CD = dyn_cast<CXXDestructorDecl>(FD))
1127 return CD->getNameAsString();
1128 return std::string(getMangledName(FD));
1129 } else if (const auto *OM = dyn_cast<ObjCMethodDecl>(DC)) {
1130 return OM->getNameAsString();
1131 } else if (isa<BlockDecl>(DC)) {
1132 return "<block>";
1133 } else if (isa<CapturedDecl>(DC)) {
1134 return "<captured>";
1135 } else {
1136 llvm_unreachable("expected a function or method");
1140 // Form a simple per-variable cache of these values in case we find we
1141 // want to reuse them.
1142 llvm::GlobalVariable *&CacheEntry = InitializerConstants[&D];
1143 if (!CacheEntry || CacheEntry->getInitializer() != Constant) {
1144 auto *Ty = Constant->getType();
1145 bool isConstant = true;
1146 llvm::GlobalVariable *InsertBefore = nullptr;
1147 unsigned AS =
1148 getContext().getTargetAddressSpace(GetGlobalConstantAddressSpace());
1149 std::string Name;
1150 if (D.hasGlobalStorage())
1151 Name = getMangledName(&D).str() + ".const";
1152 else if (const DeclContext *DC = D.getParentFunctionOrMethod())
1153 Name = ("__const." + FunctionName(DC) + "." + D.getName()).str();
1154 else
1155 llvm_unreachable("local variable has no parent function or method");
1156 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1157 getModule(), Ty, isConstant, llvm::GlobalValue::PrivateLinkage,
1158 Constant, Name, InsertBefore, llvm::GlobalValue::NotThreadLocal, AS);
1159 GV->setAlignment(Align.getAsAlign());
1160 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1161 CacheEntry = GV;
1162 } else if (CacheEntry->getAlignment() < uint64_t(Align.getQuantity())) {
1163 CacheEntry->setAlignment(Align.getAsAlign());
1166 return Address(CacheEntry, CacheEntry->getValueType(), Align);
1169 static Address createUnnamedGlobalForMemcpyFrom(CodeGenModule &CGM,
1170 const VarDecl &D,
1171 CGBuilderTy &Builder,
1172 llvm::Constant *Constant,
1173 CharUnits Align) {
1174 Address SrcPtr = CGM.createUnnamedGlobalFrom(D, Constant, Align);
1175 return Builder.CreateElementBitCast(SrcPtr, CGM.Int8Ty);
1178 static void emitStoresForConstant(CodeGenModule &CGM, const VarDecl &D,
1179 Address Loc, bool isVolatile,
1180 CGBuilderTy &Builder,
1181 llvm::Constant *constant, bool IsAutoInit) {
1182 auto *Ty = constant->getType();
1183 uint64_t ConstantSize = CGM.getDataLayout().getTypeAllocSize(Ty);
1184 if (!ConstantSize)
1185 return;
1187 bool canDoSingleStore = Ty->isIntOrIntVectorTy() ||
1188 Ty->isPtrOrPtrVectorTy() || Ty->isFPOrFPVectorTy();
1189 if (canDoSingleStore) {
1190 auto *I = Builder.CreateStore(constant, Loc, isVolatile);
1191 if (IsAutoInit)
1192 I->addAnnotationMetadata("auto-init");
1193 return;
1196 auto *SizeVal = llvm::ConstantInt::get(CGM.IntPtrTy, ConstantSize);
1198 // If the initializer is all or mostly the same, codegen with bzero / memset
1199 // then do a few stores afterward.
1200 if (shouldUseBZeroPlusStoresToInitialize(constant, ConstantSize)) {
1201 auto *I = Builder.CreateMemSet(Loc, llvm::ConstantInt::get(CGM.Int8Ty, 0),
1202 SizeVal, isVolatile);
1203 if (IsAutoInit)
1204 I->addAnnotationMetadata("auto-init");
1206 bool valueAlreadyCorrect =
1207 constant->isNullValue() || isa<llvm::UndefValue>(constant);
1208 if (!valueAlreadyCorrect) {
1209 Loc = Builder.CreateElementBitCast(Loc, Ty);
1210 emitStoresForInitAfterBZero(CGM, constant, Loc, isVolatile, Builder,
1211 IsAutoInit);
1213 return;
1216 // If the initializer is a repeated byte pattern, use memset.
1217 llvm::Value *Pattern =
1218 shouldUseMemSetToInitialize(constant, ConstantSize, CGM.getDataLayout());
1219 if (Pattern) {
1220 uint64_t Value = 0x00;
1221 if (!isa<llvm::UndefValue>(Pattern)) {
1222 const llvm::APInt &AP = cast<llvm::ConstantInt>(Pattern)->getValue();
1223 assert(AP.getBitWidth() <= 8);
1224 Value = AP.getLimitedValue();
1226 auto *I = Builder.CreateMemSet(
1227 Loc, llvm::ConstantInt::get(CGM.Int8Ty, Value), SizeVal, isVolatile);
1228 if (IsAutoInit)
1229 I->addAnnotationMetadata("auto-init");
1230 return;
1233 // If the initializer is small, use a handful of stores.
1234 if (shouldSplitConstantStore(CGM, ConstantSize)) {
1235 if (auto *STy = dyn_cast<llvm::StructType>(Ty)) {
1236 // FIXME: handle the case when STy != Loc.getElementType().
1237 if (STy == Loc.getElementType()) {
1238 for (unsigned i = 0; i != constant->getNumOperands(); i++) {
1239 Address EltPtr = Builder.CreateStructGEP(Loc, i);
1240 emitStoresForConstant(
1241 CGM, D, EltPtr, isVolatile, Builder,
1242 cast<llvm::Constant>(Builder.CreateExtractValue(constant, i)),
1243 IsAutoInit);
1245 return;
1247 } else if (auto *ATy = dyn_cast<llvm::ArrayType>(Ty)) {
1248 // FIXME: handle the case when ATy != Loc.getElementType().
1249 if (ATy == Loc.getElementType()) {
1250 for (unsigned i = 0; i != ATy->getNumElements(); i++) {
1251 Address EltPtr = Builder.CreateConstArrayGEP(Loc, i);
1252 emitStoresForConstant(
1253 CGM, D, EltPtr, isVolatile, Builder,
1254 cast<llvm::Constant>(Builder.CreateExtractValue(constant, i)),
1255 IsAutoInit);
1257 return;
1262 // Copy from a global.
1263 auto *I =
1264 Builder.CreateMemCpy(Loc,
1265 createUnnamedGlobalForMemcpyFrom(
1266 CGM, D, Builder, constant, Loc.getAlignment()),
1267 SizeVal, isVolatile);
1268 if (IsAutoInit)
1269 I->addAnnotationMetadata("auto-init");
1272 static void emitStoresForZeroInit(CodeGenModule &CGM, const VarDecl &D,
1273 Address Loc, bool isVolatile,
1274 CGBuilderTy &Builder) {
1275 llvm::Type *ElTy = Loc.getElementType();
1276 llvm::Constant *constant =
1277 constWithPadding(CGM, IsPattern::No, llvm::Constant::getNullValue(ElTy));
1278 emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant,
1279 /*IsAutoInit=*/true);
1282 static void emitStoresForPatternInit(CodeGenModule &CGM, const VarDecl &D,
1283 Address Loc, bool isVolatile,
1284 CGBuilderTy &Builder) {
1285 llvm::Type *ElTy = Loc.getElementType();
1286 llvm::Constant *constant = constWithPadding(
1287 CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));
1288 assert(!isa<llvm::UndefValue>(constant));
1289 emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant,
1290 /*IsAutoInit=*/true);
1293 static bool containsUndef(llvm::Constant *constant) {
1294 auto *Ty = constant->getType();
1295 if (isa<llvm::UndefValue>(constant))
1296 return true;
1297 if (Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy())
1298 for (llvm::Use &Op : constant->operands())
1299 if (containsUndef(cast<llvm::Constant>(Op)))
1300 return true;
1301 return false;
1304 static llvm::Constant *replaceUndef(CodeGenModule &CGM, IsPattern isPattern,
1305 llvm::Constant *constant) {
1306 auto *Ty = constant->getType();
1307 if (isa<llvm::UndefValue>(constant))
1308 return patternOrZeroFor(CGM, isPattern, Ty);
1309 if (!(Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()))
1310 return constant;
1311 if (!containsUndef(constant))
1312 return constant;
1313 llvm::SmallVector<llvm::Constant *, 8> Values(constant->getNumOperands());
1314 for (unsigned Op = 0, NumOp = constant->getNumOperands(); Op != NumOp; ++Op) {
1315 auto *OpValue = cast<llvm::Constant>(constant->getOperand(Op));
1316 Values[Op] = replaceUndef(CGM, isPattern, OpValue);
1318 if (Ty->isStructTy())
1319 return llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Values);
1320 if (Ty->isArrayTy())
1321 return llvm::ConstantArray::get(cast<llvm::ArrayType>(Ty), Values);
1322 assert(Ty->isVectorTy());
1323 return llvm::ConstantVector::get(Values);
1326 /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
1327 /// variable declaration with auto, register, or no storage class specifier.
1328 /// These turn into simple stack objects, or GlobalValues depending on target.
1329 void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
1330 AutoVarEmission emission = EmitAutoVarAlloca(D);
1331 EmitAutoVarInit(emission);
1332 EmitAutoVarCleanups(emission);
1335 /// Emit a lifetime.begin marker if some criteria are satisfied.
1336 /// \return a pointer to the temporary size Value if a marker was emitted, null
1337 /// otherwise
1338 llvm::Value *CodeGenFunction::EmitLifetimeStart(llvm::TypeSize Size,
1339 llvm::Value *Addr) {
1340 if (!ShouldEmitLifetimeMarkers)
1341 return nullptr;
1343 assert(Addr->getType()->getPointerAddressSpace() ==
1344 CGM.getDataLayout().getAllocaAddrSpace() &&
1345 "Pointer should be in alloca address space");
1346 llvm::Value *SizeV = llvm::ConstantInt::get(
1347 Int64Ty, Size.isScalable() ? -1 : Size.getFixedValue());
1348 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
1349 llvm::CallInst *C =
1350 Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
1351 C->setDoesNotThrow();
1352 return SizeV;
1355 void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
1356 assert(Addr->getType()->getPointerAddressSpace() ==
1357 CGM.getDataLayout().getAllocaAddrSpace() &&
1358 "Pointer should be in alloca address space");
1359 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
1360 llvm::CallInst *C =
1361 Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
1362 C->setDoesNotThrow();
1365 void CodeGenFunction::EmitAndRegisterVariableArrayDimensions(
1366 CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo) {
1367 // For each dimension stores its QualType and corresponding
1368 // size-expression Value.
1369 SmallVector<CodeGenFunction::VlaSizePair, 4> Dimensions;
1370 SmallVector<IdentifierInfo *, 4> VLAExprNames;
1372 // Break down the array into individual dimensions.
1373 QualType Type1D = D.getType();
1374 while (getContext().getAsVariableArrayType(Type1D)) {
1375 auto VlaSize = getVLAElements1D(Type1D);
1376 if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1377 Dimensions.emplace_back(C, Type1D.getUnqualifiedType());
1378 else {
1379 // Generate a locally unique name for the size expression.
1380 Twine Name = Twine("__vla_expr") + Twine(VLAExprCounter++);
1381 SmallString<12> Buffer;
1382 StringRef NameRef = Name.toStringRef(Buffer);
1383 auto &Ident = getContext().Idents.getOwn(NameRef);
1384 VLAExprNames.push_back(&Ident);
1385 auto SizeExprAddr =
1386 CreateDefaultAlignTempAlloca(VlaSize.NumElts->getType(), NameRef);
1387 Builder.CreateStore(VlaSize.NumElts, SizeExprAddr);
1388 Dimensions.emplace_back(SizeExprAddr.getPointer(),
1389 Type1D.getUnqualifiedType());
1391 Type1D = VlaSize.Type;
1394 if (!EmitDebugInfo)
1395 return;
1397 // Register each dimension's size-expression with a DILocalVariable,
1398 // so that it can be used by CGDebugInfo when instantiating a DISubrange
1399 // to describe this array.
1400 unsigned NameIdx = 0;
1401 for (auto &VlaSize : Dimensions) {
1402 llvm::Metadata *MD;
1403 if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1404 MD = llvm::ConstantAsMetadata::get(C);
1405 else {
1406 // Create an artificial VarDecl to generate debug info for.
1407 IdentifierInfo *NameIdent = VLAExprNames[NameIdx++];
1408 auto QT = getContext().getIntTypeForBitwidth(
1409 SizeTy->getScalarSizeInBits(), false);
1410 auto *ArtificialDecl = VarDecl::Create(
1411 getContext(), const_cast<DeclContext *>(D.getDeclContext()),
1412 D.getLocation(), D.getLocation(), NameIdent, QT,
1413 getContext().CreateTypeSourceInfo(QT), SC_Auto);
1414 ArtificialDecl->setImplicit();
1416 MD = DI->EmitDeclareOfAutoVariable(ArtificialDecl, VlaSize.NumElts,
1417 Builder);
1419 assert(MD && "No Size expression debug node created");
1420 DI->registerVLASizeExpression(VlaSize.Type, MD);
1424 /// EmitAutoVarAlloca - Emit the alloca and debug information for a
1425 /// local variable. Does not emit initialization or destruction.
1426 CodeGenFunction::AutoVarEmission
1427 CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
1428 QualType Ty = D.getType();
1429 assert(
1430 Ty.getAddressSpace() == LangAS::Default ||
1431 (Ty.getAddressSpace() == LangAS::opencl_private && getLangOpts().OpenCL));
1433 AutoVarEmission emission(D);
1435 bool isEscapingByRef = D.isEscapingByref();
1436 emission.IsEscapingByRef = isEscapingByRef;
1438 CharUnits alignment = getContext().getDeclAlign(&D);
1440 // If the type is variably-modified, emit all the VLA sizes for it.
1441 if (Ty->isVariablyModifiedType())
1442 EmitVariablyModifiedType(Ty);
1444 auto *DI = getDebugInfo();
1445 bool EmitDebugInfo = DI && CGM.getCodeGenOpts().hasReducedDebugInfo();
1447 Address address = Address::invalid();
1448 Address AllocaAddr = Address::invalid();
1449 Address OpenMPLocalAddr = Address::invalid();
1450 if (CGM.getLangOpts().OpenMPIRBuilder)
1451 OpenMPLocalAddr = OMPBuilderCBHelpers::getAddressOfLocalVariable(*this, &D);
1452 else
1453 OpenMPLocalAddr =
1454 getLangOpts().OpenMP
1455 ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
1456 : Address::invalid();
1458 bool NRVO = getLangOpts().ElideConstructors && D.isNRVOVariable();
1460 if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
1461 address = OpenMPLocalAddr;
1462 AllocaAddr = OpenMPLocalAddr;
1463 } else if (Ty->isConstantSizeType()) {
1464 // If this value is an array or struct with a statically determinable
1465 // constant initializer, there are optimizations we can do.
1467 // TODO: We should constant-evaluate the initializer of any variable,
1468 // as long as it is initialized by a constant expression. Currently,
1469 // isConstantInitializer produces wrong answers for structs with
1470 // reference or bitfield members, and a few other cases, and checking
1471 // for POD-ness protects us from some of these.
1472 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
1473 (D.isConstexpr() ||
1474 ((Ty.isPODType(getContext()) ||
1475 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
1476 D.getInit()->isConstantInitializer(getContext(), false)))) {
1478 // If the variable's a const type, and it's neither an NRVO
1479 // candidate nor a __block variable and has no mutable members,
1480 // emit it as a global instead.
1481 // Exception is if a variable is located in non-constant address space
1482 // in OpenCL.
1483 bool NeedsDtor =
1484 D.needsDestruction(getContext()) == QualType::DK_cxx_destructor;
1485 if ((!getLangOpts().OpenCL ||
1486 Ty.getAddressSpace() == LangAS::opencl_constant) &&
1487 (CGM.getCodeGenOpts().MergeAllConstants && !NRVO &&
1488 !isEscapingByRef && CGM.isTypeConstant(Ty, true, !NeedsDtor))) {
1489 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
1491 // Signal this condition to later callbacks.
1492 emission.Addr = Address::invalid();
1493 assert(emission.wasEmittedAsGlobal());
1494 return emission;
1497 // Otherwise, tell the initialization code that we're in this case.
1498 emission.IsConstantAggregate = true;
1501 // A normal fixed sized variable becomes an alloca in the entry block,
1502 // unless:
1503 // - it's an NRVO variable.
1504 // - we are compiling OpenMP and it's an OpenMP local variable.
1505 if (NRVO) {
1506 // The named return value optimization: allocate this variable in the
1507 // return slot, so that we can elide the copy when returning this
1508 // variable (C++0x [class.copy]p34).
1509 address = ReturnValue;
1510 AllocaAddr = ReturnValue;
1512 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1513 const auto *RD = RecordTy->getDecl();
1514 const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1515 if ((CXXRD && !CXXRD->hasTrivialDestructor()) ||
1516 RD->isNonTrivialToPrimitiveDestroy()) {
1517 // Create a flag that is used to indicate when the NRVO was applied
1518 // to this variable. Set it to zero to indicate that NRVO was not
1519 // applied.
1520 llvm::Value *Zero = Builder.getFalse();
1521 Address NRVOFlag =
1522 CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo",
1523 /*ArraySize=*/nullptr, &AllocaAddr);
1524 EnsureInsertPoint();
1525 Builder.CreateStore(Zero, NRVOFlag);
1527 // Record the NRVO flag for this variable.
1528 NRVOFlags[&D] = NRVOFlag.getPointer();
1529 emission.NRVOFlag = NRVOFlag.getPointer();
1532 } else {
1533 CharUnits allocaAlignment;
1534 llvm::Type *allocaTy;
1535 if (isEscapingByRef) {
1536 auto &byrefInfo = getBlockByrefInfo(&D);
1537 allocaTy = byrefInfo.Type;
1538 allocaAlignment = byrefInfo.ByrefAlignment;
1539 } else {
1540 allocaTy = ConvertTypeForMem(Ty);
1541 allocaAlignment = alignment;
1544 // Create the alloca. Note that we set the name separately from
1545 // building the instruction so that it's there even in no-asserts
1546 // builds.
1547 address = CreateTempAlloca(allocaTy, allocaAlignment, D.getName(),
1548 /*ArraySize=*/nullptr, &AllocaAddr);
1550 // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1551 // the catch parameter starts in the catchpad instruction, and we can't
1552 // insert code in those basic blocks.
1553 bool IsMSCatchParam =
1554 D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1556 // Emit a lifetime intrinsic if meaningful. There's no point in doing this
1557 // if we don't have a valid insertion point (?).
1558 if (HaveInsertPoint() && !IsMSCatchParam) {
1559 // If there's a jump into the lifetime of this variable, its lifetime
1560 // gets broken up into several regions in IR, which requires more work
1561 // to handle correctly. For now, just omit the intrinsics; this is a
1562 // rare case, and it's better to just be conservatively correct.
1563 // PR28267.
1565 // We have to do this in all language modes if there's a jump past the
1566 // declaration. We also have to do it in C if there's a jump to an
1567 // earlier point in the current block because non-VLA lifetimes begin as
1568 // soon as the containing block is entered, not when its variables
1569 // actually come into scope; suppressing the lifetime annotations
1570 // completely in this case is unnecessarily pessimistic, but again, this
1571 // is rare.
1572 if (!Bypasses.IsBypassed(&D) &&
1573 !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
1574 llvm::TypeSize Size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
1575 emission.SizeForLifetimeMarkers =
1576 EmitLifetimeStart(Size, AllocaAddr.getPointer());
1578 } else {
1579 assert(!emission.useLifetimeMarkers());
1582 } else {
1583 EnsureInsertPoint();
1585 if (!DidCallStackSave) {
1586 // Save the stack.
1587 Address Stack =
1588 CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
1590 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
1591 llvm::Value *V = Builder.CreateCall(F);
1592 Builder.CreateStore(V, Stack);
1594 DidCallStackSave = true;
1596 // Push a cleanup block and restore the stack there.
1597 // FIXME: in general circumstances, this should be an EH cleanup.
1598 pushStackRestore(NormalCleanup, Stack);
1601 auto VlaSize = getVLASize(Ty);
1602 llvm::Type *llvmTy = ConvertTypeForMem(VlaSize.Type);
1604 // Allocate memory for the array.
1605 address = CreateTempAlloca(llvmTy, alignment, "vla", VlaSize.NumElts,
1606 &AllocaAddr);
1608 // If we have debug info enabled, properly describe the VLA dimensions for
1609 // this type by registering the vla size expression for each of the
1610 // dimensions.
1611 EmitAndRegisterVariableArrayDimensions(DI, D, EmitDebugInfo);
1614 setAddrOfLocalVar(&D, address);
1615 emission.Addr = address;
1616 emission.AllocaAddr = AllocaAddr;
1618 // Emit debug info for local var declaration.
1619 if (EmitDebugInfo && HaveInsertPoint()) {
1620 Address DebugAddr = address;
1621 bool UsePointerValue = NRVO && ReturnValuePointer.isValid();
1622 DI->setLocation(D.getLocation());
1624 // If NRVO, use a pointer to the return address.
1625 if (UsePointerValue) {
1626 DebugAddr = ReturnValuePointer;
1627 AllocaAddr = ReturnValuePointer;
1629 (void)DI->EmitDeclareOfAutoVariable(&D, AllocaAddr.getPointer(), Builder,
1630 UsePointerValue);
1633 if (D.hasAttr<AnnotateAttr>() && HaveInsertPoint())
1634 EmitVarAnnotations(&D, address.getPointer());
1636 // Make sure we call @llvm.lifetime.end.
1637 if (emission.useLifetimeMarkers())
1638 EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
1639 emission.getOriginalAllocatedAddress(),
1640 emission.getSizeForLifetimeMarkers());
1642 return emission;
1645 static bool isCapturedBy(const VarDecl &, const Expr *);
1647 /// Determines whether the given __block variable is potentially
1648 /// captured by the given statement.
1649 static bool isCapturedBy(const VarDecl &Var, const Stmt *S) {
1650 if (const Expr *E = dyn_cast<Expr>(S))
1651 return isCapturedBy(Var, E);
1652 for (const Stmt *SubStmt : S->children())
1653 if (isCapturedBy(Var, SubStmt))
1654 return true;
1655 return false;
1658 /// Determines whether the given __block variable is potentially
1659 /// captured by the given expression.
1660 static bool isCapturedBy(const VarDecl &Var, const Expr *E) {
1661 // Skip the most common kinds of expressions that make
1662 // hierarchy-walking expensive.
1663 E = E->IgnoreParenCasts();
1665 if (const BlockExpr *BE = dyn_cast<BlockExpr>(E)) {
1666 const BlockDecl *Block = BE->getBlockDecl();
1667 for (const auto &I : Block->captures()) {
1668 if (I.getVariable() == &Var)
1669 return true;
1672 // No need to walk into the subexpressions.
1673 return false;
1676 if (const StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
1677 const CompoundStmt *CS = SE->getSubStmt();
1678 for (const auto *BI : CS->body())
1679 if (const auto *BIE = dyn_cast<Expr>(BI)) {
1680 if (isCapturedBy(Var, BIE))
1681 return true;
1683 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
1684 // special case declarations
1685 for (const auto *I : DS->decls()) {
1686 if (const auto *VD = dyn_cast<VarDecl>((I))) {
1687 const Expr *Init = VD->getInit();
1688 if (Init && isCapturedBy(Var, Init))
1689 return true;
1693 else
1694 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1695 // Later, provide code to poke into statements for capture analysis.
1696 return true;
1697 return false;
1700 for (const Stmt *SubStmt : E->children())
1701 if (isCapturedBy(Var, SubStmt))
1702 return true;
1704 return false;
1707 /// Determine whether the given initializer is trivial in the sense
1708 /// that it requires no code to be generated.
1709 bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
1710 if (!Init)
1711 return true;
1713 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1714 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1715 if (Constructor->isTrivial() &&
1716 Constructor->isDefaultConstructor() &&
1717 !Construct->requiresZeroInitialization())
1718 return true;
1720 return false;
1723 void CodeGenFunction::emitZeroOrPatternForAutoVarInit(QualType type,
1724 const VarDecl &D,
1725 Address Loc) {
1726 auto trivialAutoVarInit = getContext().getLangOpts().getTrivialAutoVarInit();
1727 CharUnits Size = getContext().getTypeSizeInChars(type);
1728 bool isVolatile = type.isVolatileQualified();
1729 if (!Size.isZero()) {
1730 switch (trivialAutoVarInit) {
1731 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
1732 llvm_unreachable("Uninitialized handled by caller");
1733 case LangOptions::TrivialAutoVarInitKind::Zero:
1734 if (CGM.stopAutoInit())
1735 return;
1736 emitStoresForZeroInit(CGM, D, Loc, isVolatile, Builder);
1737 break;
1738 case LangOptions::TrivialAutoVarInitKind::Pattern:
1739 if (CGM.stopAutoInit())
1740 return;
1741 emitStoresForPatternInit(CGM, D, Loc, isVolatile, Builder);
1742 break;
1744 return;
1747 // VLAs look zero-sized to getTypeInfo. We can't emit constant stores to
1748 // them, so emit a memcpy with the VLA size to initialize each element.
1749 // Technically zero-sized or negative-sized VLAs are undefined, and UBSan
1750 // will catch that code, but there exists code which generates zero-sized
1751 // VLAs. Be nice and initialize whatever they requested.
1752 const auto *VlaType = getContext().getAsVariableArrayType(type);
1753 if (!VlaType)
1754 return;
1755 auto VlaSize = getVLASize(VlaType);
1756 auto SizeVal = VlaSize.NumElts;
1757 CharUnits EltSize = getContext().getTypeSizeInChars(VlaSize.Type);
1758 switch (trivialAutoVarInit) {
1759 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
1760 llvm_unreachable("Uninitialized handled by caller");
1762 case LangOptions::TrivialAutoVarInitKind::Zero: {
1763 if (CGM.stopAutoInit())
1764 return;
1765 if (!EltSize.isOne())
1766 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
1767 auto *I = Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0),
1768 SizeVal, isVolatile);
1769 I->addAnnotationMetadata("auto-init");
1770 break;
1773 case LangOptions::TrivialAutoVarInitKind::Pattern: {
1774 if (CGM.stopAutoInit())
1775 return;
1776 llvm::Type *ElTy = Loc.getElementType();
1777 llvm::Constant *Constant = constWithPadding(
1778 CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));
1779 CharUnits ConstantAlign = getContext().getTypeAlignInChars(VlaSize.Type);
1780 llvm::BasicBlock *SetupBB = createBasicBlock("vla-setup.loop");
1781 llvm::BasicBlock *LoopBB = createBasicBlock("vla-init.loop");
1782 llvm::BasicBlock *ContBB = createBasicBlock("vla-init.cont");
1783 llvm::Value *IsZeroSizedVLA = Builder.CreateICmpEQ(
1784 SizeVal, llvm::ConstantInt::get(SizeVal->getType(), 0),
1785 "vla.iszerosized");
1786 Builder.CreateCondBr(IsZeroSizedVLA, ContBB, SetupBB);
1787 EmitBlock(SetupBB);
1788 if (!EltSize.isOne())
1789 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
1790 llvm::Value *BaseSizeInChars =
1791 llvm::ConstantInt::get(IntPtrTy, EltSize.getQuantity());
1792 Address Begin = Builder.CreateElementBitCast(Loc, Int8Ty, "vla.begin");
1793 llvm::Value *End = Builder.CreateInBoundsGEP(
1794 Begin.getElementType(), Begin.getPointer(), SizeVal, "vla.end");
1795 llvm::BasicBlock *OriginBB = Builder.GetInsertBlock();
1796 EmitBlock(LoopBB);
1797 llvm::PHINode *Cur = Builder.CreatePHI(Begin.getType(), 2, "vla.cur");
1798 Cur->addIncoming(Begin.getPointer(), OriginBB);
1799 CharUnits CurAlign = Loc.getAlignment().alignmentOfArrayElement(EltSize);
1800 auto *I =
1801 Builder.CreateMemCpy(Address(Cur, Int8Ty, CurAlign),
1802 createUnnamedGlobalForMemcpyFrom(
1803 CGM, D, Builder, Constant, ConstantAlign),
1804 BaseSizeInChars, isVolatile);
1805 I->addAnnotationMetadata("auto-init");
1806 llvm::Value *Next =
1807 Builder.CreateInBoundsGEP(Int8Ty, Cur, BaseSizeInChars, "vla.next");
1808 llvm::Value *Done = Builder.CreateICmpEQ(Next, End, "vla-init.isdone");
1809 Builder.CreateCondBr(Done, ContBB, LoopBB);
1810 Cur->addIncoming(Next, LoopBB);
1811 EmitBlock(ContBB);
1812 } break;
1816 void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
1817 assert(emission.Variable && "emission was not valid!");
1819 // If this was emitted as a global constant, we're done.
1820 if (emission.wasEmittedAsGlobal()) return;
1822 const VarDecl &D = *emission.Variable;
1823 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
1824 QualType type = D.getType();
1826 // If this local has an initializer, emit it now.
1827 const Expr *Init = D.getInit();
1829 // If we are at an unreachable point, we don't need to emit the initializer
1830 // unless it contains a label.
1831 if (!HaveInsertPoint()) {
1832 if (!Init || !ContainsLabel(Init)) return;
1833 EnsureInsertPoint();
1836 // Initialize the structure of a __block variable.
1837 if (emission.IsEscapingByRef)
1838 emitByrefStructureInit(emission);
1840 // Initialize the variable here if it doesn't have a initializer and it is a
1841 // C struct that is non-trivial to initialize or an array containing such a
1842 // struct.
1843 if (!Init &&
1844 type.isNonTrivialToPrimitiveDefaultInitialize() ==
1845 QualType::PDIK_Struct) {
1846 LValue Dst = MakeAddrLValue(emission.getAllocatedAddress(), type);
1847 if (emission.IsEscapingByRef)
1848 drillIntoBlockVariable(*this, Dst, &D);
1849 defaultInitNonTrivialCStructVar(Dst);
1850 return;
1853 // Check whether this is a byref variable that's potentially
1854 // captured and moved by its own initializer. If so, we'll need to
1855 // emit the initializer first, then copy into the variable.
1856 bool capturedByInit =
1857 Init && emission.IsEscapingByRef && isCapturedBy(D, Init);
1859 bool locIsByrefHeader = !capturedByInit;
1860 const Address Loc =
1861 locIsByrefHeader ? emission.getObjectAddress(*this) : emission.Addr;
1863 // Note: constexpr already initializes everything correctly.
1864 LangOptions::TrivialAutoVarInitKind trivialAutoVarInit =
1865 (D.isConstexpr()
1866 ? LangOptions::TrivialAutoVarInitKind::Uninitialized
1867 : (D.getAttr<UninitializedAttr>()
1868 ? LangOptions::TrivialAutoVarInitKind::Uninitialized
1869 : getContext().getLangOpts().getTrivialAutoVarInit()));
1871 auto initializeWhatIsTechnicallyUninitialized = [&](Address Loc) {
1872 if (trivialAutoVarInit ==
1873 LangOptions::TrivialAutoVarInitKind::Uninitialized)
1874 return;
1876 // Only initialize a __block's storage: we always initialize the header.
1877 if (emission.IsEscapingByRef && !locIsByrefHeader)
1878 Loc = emitBlockByrefAddress(Loc, &D, /*follow=*/false);
1880 return emitZeroOrPatternForAutoVarInit(type, D, Loc);
1883 if (isTrivialInitializer(Init))
1884 return initializeWhatIsTechnicallyUninitialized(Loc);
1886 llvm::Constant *constant = nullptr;
1887 if (emission.IsConstantAggregate ||
1888 D.mightBeUsableInConstantExpressions(getContext())) {
1889 assert(!capturedByInit && "constant init contains a capturing block?");
1890 constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(D);
1891 if (constant && !constant->isZeroValue() &&
1892 (trivialAutoVarInit !=
1893 LangOptions::TrivialAutoVarInitKind::Uninitialized)) {
1894 IsPattern isPattern =
1895 (trivialAutoVarInit == LangOptions::TrivialAutoVarInitKind::Pattern)
1896 ? IsPattern::Yes
1897 : IsPattern::No;
1898 // C guarantees that brace-init with fewer initializers than members in
1899 // the aggregate will initialize the rest of the aggregate as-if it were
1900 // static initialization. In turn static initialization guarantees that
1901 // padding is initialized to zero bits. We could instead pattern-init if D
1902 // has any ImplicitValueInitExpr, but that seems to be unintuitive
1903 // behavior.
1904 constant = constWithPadding(CGM, IsPattern::No,
1905 replaceUndef(CGM, isPattern, constant));
1909 if (!constant) {
1910 initializeWhatIsTechnicallyUninitialized(Loc);
1911 LValue lv = MakeAddrLValue(Loc, type);
1912 lv.setNonGC(true);
1913 return EmitExprAsInit(Init, &D, lv, capturedByInit);
1916 if (!emission.IsConstantAggregate) {
1917 // For simple scalar/complex initialization, store the value directly.
1918 LValue lv = MakeAddrLValue(Loc, type);
1919 lv.setNonGC(true);
1920 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1923 emitStoresForConstant(CGM, D, Builder.CreateElementBitCast(Loc, CGM.Int8Ty),
1924 type.isVolatileQualified(), Builder, constant,
1925 /*IsAutoInit=*/false);
1928 /// Emit an expression as an initializer for an object (variable, field, etc.)
1929 /// at the given location. The expression is not necessarily the normal
1930 /// initializer for the object, and the address is not necessarily
1931 /// its normal location.
1933 /// \param init the initializing expression
1934 /// \param D the object to act as if we're initializing
1935 /// \param lvalue the lvalue to initialize
1936 /// \param capturedByInit true if \p D is a __block variable
1937 /// whose address is potentially changed by the initializer
1938 void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
1939 LValue lvalue, bool capturedByInit) {
1940 QualType type = D->getType();
1942 if (type->isReferenceType()) {
1943 RValue rvalue = EmitReferenceBindingToExpr(init);
1944 if (capturedByInit)
1945 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1946 EmitStoreThroughLValue(rvalue, lvalue, true);
1947 return;
1949 switch (getEvaluationKind(type)) {
1950 case TEK_Scalar:
1951 EmitScalarInit(init, D, lvalue, capturedByInit);
1952 return;
1953 case TEK_Complex: {
1954 ComplexPairTy complex = EmitComplexExpr(init);
1955 if (capturedByInit)
1956 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1957 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
1958 return;
1960 case TEK_Aggregate:
1961 if (type->isAtomicType()) {
1962 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1963 } else {
1964 AggValueSlot::Overlap_t Overlap = AggValueSlot::MayOverlap;
1965 if (isa<VarDecl>(D))
1966 Overlap = AggValueSlot::DoesNotOverlap;
1967 else if (auto *FD = dyn_cast<FieldDecl>(D))
1968 Overlap = getOverlapForFieldInit(FD);
1969 // TODO: how can we delay here if D is captured by its initializer?
1970 EmitAggExpr(init, AggValueSlot::forLValue(
1971 lvalue, *this, AggValueSlot::IsDestructed,
1972 AggValueSlot::DoesNotNeedGCBarriers,
1973 AggValueSlot::IsNotAliased, Overlap));
1975 return;
1977 llvm_unreachable("bad evaluation kind");
1980 /// Enter a destroy cleanup for the given local variable.
1981 void CodeGenFunction::emitAutoVarTypeCleanup(
1982 const CodeGenFunction::AutoVarEmission &emission,
1983 QualType::DestructionKind dtorKind) {
1984 assert(dtorKind != QualType::DK_none);
1986 // Note that for __block variables, we want to destroy the
1987 // original stack object, not the possibly forwarded object.
1988 Address addr = emission.getObjectAddress(*this);
1990 const VarDecl *var = emission.Variable;
1991 QualType type = var->getType();
1993 CleanupKind cleanupKind = NormalAndEHCleanup;
1994 CodeGenFunction::Destroyer *destroyer = nullptr;
1996 switch (dtorKind) {
1997 case QualType::DK_none:
1998 llvm_unreachable("no cleanup for trivially-destructible variable");
2000 case QualType::DK_cxx_destructor:
2001 // If there's an NRVO flag on the emission, we need a different
2002 // cleanup.
2003 if (emission.NRVOFlag) {
2004 assert(!type->isArrayType());
2005 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
2006 EHStack.pushCleanup<DestroyNRVOVariableCXX>(cleanupKind, addr, type, dtor,
2007 emission.NRVOFlag);
2008 return;
2010 break;
2012 case QualType::DK_objc_strong_lifetime:
2013 // Suppress cleanups for pseudo-strong variables.
2014 if (var->isARCPseudoStrong()) return;
2016 // Otherwise, consider whether to use an EH cleanup or not.
2017 cleanupKind = getARCCleanupKind();
2019 // Use the imprecise destroyer by default.
2020 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
2021 destroyer = CodeGenFunction::destroyARCStrongImprecise;
2022 break;
2024 case QualType::DK_objc_weak_lifetime:
2025 break;
2027 case QualType::DK_nontrivial_c_struct:
2028 destroyer = CodeGenFunction::destroyNonTrivialCStruct;
2029 if (emission.NRVOFlag) {
2030 assert(!type->isArrayType());
2031 EHStack.pushCleanup<DestroyNRVOVariableC>(cleanupKind, addr,
2032 emission.NRVOFlag, type);
2033 return;
2035 break;
2038 // If we haven't chosen a more specific destroyer, use the default.
2039 if (!destroyer) destroyer = getDestroyer(dtorKind);
2041 // Use an EH cleanup in array destructors iff the destructor itself
2042 // is being pushed as an EH cleanup.
2043 bool useEHCleanup = (cleanupKind & EHCleanup);
2044 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
2045 useEHCleanup);
2048 void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
2049 assert(emission.Variable && "emission was not valid!");
2051 // If this was emitted as a global constant, we're done.
2052 if (emission.wasEmittedAsGlobal()) return;
2054 // If we don't have an insertion point, we're done. Sema prevents
2055 // us from jumping into any of these scopes anyway.
2056 if (!HaveInsertPoint()) return;
2058 const VarDecl &D = *emission.Variable;
2060 // Check the type for a cleanup.
2061 if (QualType::DestructionKind dtorKind = D.needsDestruction(getContext()))
2062 emitAutoVarTypeCleanup(emission, dtorKind);
2064 // In GC mode, honor objc_precise_lifetime.
2065 if (getLangOpts().getGC() != LangOptions::NonGC &&
2066 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
2067 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
2070 // Handle the cleanup attribute.
2071 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
2072 const FunctionDecl *FD = CA->getFunctionDecl();
2074 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
2075 assert(F && "Could not find function!");
2077 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
2078 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
2081 // If this is a block variable, call _Block_object_destroy
2082 // (on the unforwarded address). Don't enter this cleanup if we're in pure-GC
2083 // mode.
2084 if (emission.IsEscapingByRef &&
2085 CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
2086 BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
2087 if (emission.Variable->getType().isObjCGCWeak())
2088 Flags |= BLOCK_FIELD_IS_WEAK;
2089 enterByrefCleanup(NormalAndEHCleanup, emission.Addr, Flags,
2090 /*LoadBlockVarAddr*/ false,
2091 cxxDestructorCanThrow(emission.Variable->getType()));
2095 CodeGenFunction::Destroyer *
2096 CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
2097 switch (kind) {
2098 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
2099 case QualType::DK_cxx_destructor:
2100 return destroyCXXObject;
2101 case QualType::DK_objc_strong_lifetime:
2102 return destroyARCStrongPrecise;
2103 case QualType::DK_objc_weak_lifetime:
2104 return destroyARCWeak;
2105 case QualType::DK_nontrivial_c_struct:
2106 return destroyNonTrivialCStruct;
2108 llvm_unreachable("Unknown DestructionKind");
2111 /// pushEHDestroy - Push the standard destructor for the given type as
2112 /// an EH-only cleanup.
2113 void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
2114 Address addr, QualType type) {
2115 assert(dtorKind && "cannot push destructor for trivial type");
2116 assert(needsEHCleanup(dtorKind));
2118 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
2121 /// pushDestroy - Push the standard destructor for the given type as
2122 /// at least a normal cleanup.
2123 void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
2124 Address addr, QualType type) {
2125 assert(dtorKind && "cannot push destructor for trivial type");
2127 CleanupKind cleanupKind = getCleanupKind(dtorKind);
2128 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
2129 cleanupKind & EHCleanup);
2132 void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
2133 QualType type, Destroyer *destroyer,
2134 bool useEHCleanupForArray) {
2135 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
2136 destroyer, useEHCleanupForArray);
2139 void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
2140 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
2143 void CodeGenFunction::pushLifetimeExtendedDestroy(CleanupKind cleanupKind,
2144 Address addr, QualType type,
2145 Destroyer *destroyer,
2146 bool useEHCleanupForArray) {
2147 // If we're not in a conditional branch, we don't need to bother generating a
2148 // conditional cleanup.
2149 if (!isInConditionalBranch()) {
2150 // Push an EH-only cleanup for the object now.
2151 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
2152 // around in case a temporary's destructor throws an exception.
2153 if (cleanupKind & EHCleanup)
2154 EHStack.pushCleanup<DestroyObject>(
2155 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
2156 destroyer, useEHCleanupForArray);
2158 return pushCleanupAfterFullExprWithActiveFlag<DestroyObject>(
2159 cleanupKind, Address::invalid(), addr, type, destroyer, useEHCleanupForArray);
2162 // Otherwise, we should only destroy the object if it's been initialized.
2163 // Re-use the active flag and saved address across both the EH and end of
2164 // scope cleanups.
2166 using SavedType = typename DominatingValue<Address>::saved_type;
2167 using ConditionalCleanupType =
2168 EHScopeStack::ConditionalCleanup<DestroyObject, Address, QualType,
2169 Destroyer *, bool>;
2171 Address ActiveFlag = createCleanupActiveFlag();
2172 SavedType SavedAddr = saveValueInCond(addr);
2174 if (cleanupKind & EHCleanup) {
2175 EHStack.pushCleanup<ConditionalCleanupType>(
2176 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), SavedAddr, type,
2177 destroyer, useEHCleanupForArray);
2178 initFullExprCleanupWithFlag(ActiveFlag);
2181 pushCleanupAfterFullExprWithActiveFlag<ConditionalCleanupType>(
2182 cleanupKind, ActiveFlag, SavedAddr, type, destroyer,
2183 useEHCleanupForArray);
2186 /// emitDestroy - Immediately perform the destruction of the given
2187 /// object.
2189 /// \param addr - the address of the object; a type*
2190 /// \param type - the type of the object; if an array type, all
2191 /// objects are destroyed in reverse order
2192 /// \param destroyer - the function to call to destroy individual
2193 /// elements
2194 /// \param useEHCleanupForArray - whether an EH cleanup should be
2195 /// used when destroying array elements, in case one of the
2196 /// destructions throws an exception
2197 void CodeGenFunction::emitDestroy(Address addr, QualType type,
2198 Destroyer *destroyer,
2199 bool useEHCleanupForArray) {
2200 const ArrayType *arrayType = getContext().getAsArrayType(type);
2201 if (!arrayType)
2202 return destroyer(*this, addr, type);
2204 llvm::Value *length = emitArrayLength(arrayType, type, addr);
2206 CharUnits elementAlign =
2207 addr.getAlignment()
2208 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
2210 // Normally we have to check whether the array is zero-length.
2211 bool checkZeroLength = true;
2213 // But if the array length is constant, we can suppress that.
2214 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
2215 // ...and if it's constant zero, we can just skip the entire thing.
2216 if (constLength->isZero()) return;
2217 checkZeroLength = false;
2220 llvm::Value *begin = addr.getPointer();
2221 llvm::Value *end =
2222 Builder.CreateInBoundsGEP(addr.getElementType(), begin, length);
2223 emitArrayDestroy(begin, end, type, elementAlign, destroyer,
2224 checkZeroLength, useEHCleanupForArray);
2227 /// emitArrayDestroy - Destroys all the elements of the given array,
2228 /// beginning from last to first. The array cannot be zero-length.
2230 /// \param begin - a type* denoting the first element of the array
2231 /// \param end - a type* denoting one past the end of the array
2232 /// \param elementType - the element type of the array
2233 /// \param destroyer - the function to call to destroy elements
2234 /// \param useEHCleanup - whether to push an EH cleanup to destroy
2235 /// the remaining elements in case the destruction of a single
2236 /// element throws
2237 void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
2238 llvm::Value *end,
2239 QualType elementType,
2240 CharUnits elementAlign,
2241 Destroyer *destroyer,
2242 bool checkZeroLength,
2243 bool useEHCleanup) {
2244 assert(!elementType->isArrayType());
2246 // The basic structure here is a do-while loop, because we don't
2247 // need to check for the zero-element case.
2248 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
2249 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
2251 if (checkZeroLength) {
2252 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
2253 "arraydestroy.isempty");
2254 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
2257 // Enter the loop body, making that address the current address.
2258 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
2259 EmitBlock(bodyBB);
2260 llvm::PHINode *elementPast =
2261 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
2262 elementPast->addIncoming(end, entryBB);
2264 // Shift the address back by one element.
2265 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
2266 llvm::Type *llvmElementType = ConvertTypeForMem(elementType);
2267 llvm::Value *element = Builder.CreateInBoundsGEP(
2268 llvmElementType, elementPast, negativeOne, "arraydestroy.element");
2270 if (useEHCleanup)
2271 pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
2272 destroyer);
2274 // Perform the actual destruction there.
2275 destroyer(*this, Address(element, llvmElementType, elementAlign),
2276 elementType);
2278 if (useEHCleanup)
2279 PopCleanupBlock();
2281 // Check whether we've reached the end.
2282 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
2283 Builder.CreateCondBr(done, doneBB, bodyBB);
2284 elementPast->addIncoming(element, Builder.GetInsertBlock());
2286 // Done.
2287 EmitBlock(doneBB);
2290 /// Perform partial array destruction as if in an EH cleanup. Unlike
2291 /// emitArrayDestroy, the element type here may still be an array type.
2292 static void emitPartialArrayDestroy(CodeGenFunction &CGF,
2293 llvm::Value *begin, llvm::Value *end,
2294 QualType type, CharUnits elementAlign,
2295 CodeGenFunction::Destroyer *destroyer) {
2296 llvm::Type *elemTy = CGF.ConvertTypeForMem(type);
2298 // If the element type is itself an array, drill down.
2299 unsigned arrayDepth = 0;
2300 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
2301 // VLAs don't require a GEP index to walk into.
2302 if (!isa<VariableArrayType>(arrayType))
2303 arrayDepth++;
2304 type = arrayType->getElementType();
2307 if (arrayDepth) {
2308 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
2310 SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
2311 begin = CGF.Builder.CreateInBoundsGEP(
2312 elemTy, begin, gepIndices, "pad.arraybegin");
2313 end = CGF.Builder.CreateInBoundsGEP(
2314 elemTy, end, gepIndices, "pad.arrayend");
2317 // Destroy the array. We don't ever need an EH cleanup because we
2318 // assume that we're in an EH cleanup ourselves, so a throwing
2319 // destructor causes an immediate terminate.
2320 CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
2321 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
2324 namespace {
2325 /// RegularPartialArrayDestroy - a cleanup which performs a partial
2326 /// array destroy where the end pointer is regularly determined and
2327 /// does not need to be loaded from a local.
2328 class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
2329 llvm::Value *ArrayBegin;
2330 llvm::Value *ArrayEnd;
2331 QualType ElementType;
2332 CodeGenFunction::Destroyer *Destroyer;
2333 CharUnits ElementAlign;
2334 public:
2335 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
2336 QualType elementType, CharUnits elementAlign,
2337 CodeGenFunction::Destroyer *destroyer)
2338 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
2339 ElementType(elementType), Destroyer(destroyer),
2340 ElementAlign(elementAlign) {}
2342 void Emit(CodeGenFunction &CGF, Flags flags) override {
2343 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
2344 ElementType, ElementAlign, Destroyer);
2348 /// IrregularPartialArrayDestroy - a cleanup which performs a
2349 /// partial array destroy where the end pointer is irregularly
2350 /// determined and must be loaded from a local.
2351 class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
2352 llvm::Value *ArrayBegin;
2353 Address ArrayEndPointer;
2354 QualType ElementType;
2355 CodeGenFunction::Destroyer *Destroyer;
2356 CharUnits ElementAlign;
2357 public:
2358 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
2359 Address arrayEndPointer,
2360 QualType elementType,
2361 CharUnits elementAlign,
2362 CodeGenFunction::Destroyer *destroyer)
2363 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
2364 ElementType(elementType), Destroyer(destroyer),
2365 ElementAlign(elementAlign) {}
2367 void Emit(CodeGenFunction &CGF, Flags flags) override {
2368 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
2369 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
2370 ElementType, ElementAlign, Destroyer);
2373 } // end anonymous namespace
2375 /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
2376 /// already-constructed elements of the given array. The cleanup
2377 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
2379 /// \param elementType - the immediate element type of the array;
2380 /// possibly still an array type
2381 void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
2382 Address arrayEndPointer,
2383 QualType elementType,
2384 CharUnits elementAlign,
2385 Destroyer *destroyer) {
2386 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
2387 arrayBegin, arrayEndPointer,
2388 elementType, elementAlign,
2389 destroyer);
2392 /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
2393 /// already-constructed elements of the given array. The cleanup
2394 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
2396 /// \param elementType - the immediate element type of the array;
2397 /// possibly still an array type
2398 void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
2399 llvm::Value *arrayEnd,
2400 QualType elementType,
2401 CharUnits elementAlign,
2402 Destroyer *destroyer) {
2403 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
2404 arrayBegin, arrayEnd,
2405 elementType, elementAlign,
2406 destroyer);
2409 /// Lazily declare the @llvm.lifetime.start intrinsic.
2410 llvm::Function *CodeGenModule::getLLVMLifetimeStartFn() {
2411 if (LifetimeStartFn)
2412 return LifetimeStartFn;
2413 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
2414 llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);
2415 return LifetimeStartFn;
2418 /// Lazily declare the @llvm.lifetime.end intrinsic.
2419 llvm::Function *CodeGenModule::getLLVMLifetimeEndFn() {
2420 if (LifetimeEndFn)
2421 return LifetimeEndFn;
2422 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
2423 llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);
2424 return LifetimeEndFn;
2427 namespace {
2428 /// A cleanup to perform a release of an object at the end of a
2429 /// function. This is used to balance out the incoming +1 of a
2430 /// ns_consumed argument when we can't reasonably do that just by
2431 /// not doing the initial retain for a __block argument.
2432 struct ConsumeARCParameter final : EHScopeStack::Cleanup {
2433 ConsumeARCParameter(llvm::Value *param,
2434 ARCPreciseLifetime_t precise)
2435 : Param(param), Precise(precise) {}
2437 llvm::Value *Param;
2438 ARCPreciseLifetime_t Precise;
2440 void Emit(CodeGenFunction &CGF, Flags flags) override {
2441 CGF.EmitARCRelease(Param, Precise);
2444 } // end anonymous namespace
2446 /// Emit an alloca (or GlobalValue depending on target)
2447 /// for the specified parameter and set up LocalDeclMap.
2448 void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
2449 unsigned ArgNo) {
2450 bool NoDebugInfo = false;
2451 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
2452 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
2453 "Invalid argument to EmitParmDecl");
2455 Arg.getAnyValue()->setName(D.getName());
2457 QualType Ty = D.getType();
2459 // Use better IR generation for certain implicit parameters.
2460 if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
2461 // The only implicit argument a block has is its literal.
2462 // This may be passed as an inalloca'ed value on Windows x86.
2463 if (BlockInfo) {
2464 llvm::Value *V = Arg.isIndirect()
2465 ? Builder.CreateLoad(Arg.getIndirectAddress())
2466 : Arg.getDirectValue();
2467 setBlockContextParameter(IPD, ArgNo, V);
2468 return;
2470 // Suppressing debug info for ThreadPrivateVar parameters, else it hides
2471 // debug info of TLS variables.
2472 NoDebugInfo =
2473 (IPD->getParameterKind() == ImplicitParamDecl::ThreadPrivateVar);
2476 Address DeclPtr = Address::invalid();
2477 Address AllocaPtr = Address::invalid();
2478 bool DoStore = false;
2479 bool IsScalar = hasScalarEvaluationKind(Ty);
2480 bool UseIndirectDebugAddress = false;
2482 // If we already have a pointer to the argument, reuse the input pointer.
2483 if (Arg.isIndirect()) {
2484 // If we have a prettier pointer type at this point, bitcast to that.
2485 DeclPtr = Arg.getIndirectAddress();
2486 DeclPtr = Builder.CreateElementBitCast(DeclPtr, ConvertTypeForMem(Ty),
2487 D.getName());
2488 // Indirect argument is in alloca address space, which may be different
2489 // from the default address space.
2490 auto AllocaAS = CGM.getASTAllocaAddressSpace();
2491 auto *V = DeclPtr.getPointer();
2492 AllocaPtr = DeclPtr;
2494 // For truly ABI indirect arguments -- those that are not `byval` -- store
2495 // the address of the argument on the stack to preserve debug information.
2496 ABIArgInfo ArgInfo = CurFnInfo->arguments()[ArgNo - 1].info;
2497 if (ArgInfo.isIndirect())
2498 UseIndirectDebugAddress = !ArgInfo.getIndirectByVal();
2499 if (UseIndirectDebugAddress) {
2500 auto PtrTy = getContext().getPointerType(Ty);
2501 AllocaPtr = CreateMemTemp(PtrTy, getContext().getTypeAlignInChars(PtrTy),
2502 D.getName() + ".indirect_addr");
2503 EmitStoreOfScalar(V, AllocaPtr, /* Volatile */ false, PtrTy);
2506 auto SrcLangAS = getLangOpts().OpenCL ? LangAS::opencl_private : AllocaAS;
2507 auto DestLangAS =
2508 getLangOpts().OpenCL ? LangAS::opencl_private : LangAS::Default;
2509 if (SrcLangAS != DestLangAS) {
2510 assert(getContext().getTargetAddressSpace(SrcLangAS) ==
2511 CGM.getDataLayout().getAllocaAddrSpace());
2512 auto DestAS = getContext().getTargetAddressSpace(DestLangAS);
2513 auto *T = DeclPtr.getElementType()->getPointerTo(DestAS);
2514 DeclPtr =
2515 DeclPtr.withPointer(getTargetHooks().performAddrSpaceCast(
2516 *this, V, SrcLangAS, DestLangAS, T, true),
2517 DeclPtr.isKnownNonNull());
2520 // Push a destructor cleanup for this parameter if the ABI requires it.
2521 // Don't push a cleanup in a thunk for a method that will also emit a
2522 // cleanup.
2523 if (Ty->isRecordType() && !CurFuncIsThunk &&
2524 Ty->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
2525 if (QualType::DestructionKind DtorKind =
2526 D.needsDestruction(getContext())) {
2527 assert((DtorKind == QualType::DK_cxx_destructor ||
2528 DtorKind == QualType::DK_nontrivial_c_struct) &&
2529 "unexpected destructor type");
2530 pushDestroy(DtorKind, DeclPtr, Ty);
2531 CalleeDestructedParamCleanups[cast<ParmVarDecl>(&D)] =
2532 EHStack.stable_begin();
2535 } else {
2536 // Check if the parameter address is controlled by OpenMP runtime.
2537 Address OpenMPLocalAddr =
2538 getLangOpts().OpenMP
2539 ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
2540 : Address::invalid();
2541 if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
2542 DeclPtr = OpenMPLocalAddr;
2543 AllocaPtr = DeclPtr;
2544 } else {
2545 // Otherwise, create a temporary to hold the value.
2546 DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
2547 D.getName() + ".addr", &AllocaPtr);
2549 DoStore = true;
2552 llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
2554 LValue lv = MakeAddrLValue(DeclPtr, Ty);
2555 if (IsScalar) {
2556 Qualifiers qs = Ty.getQualifiers();
2557 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
2558 // We honor __attribute__((ns_consumed)) for types with lifetime.
2559 // For __strong, it's handled by just skipping the initial retain;
2560 // otherwise we have to balance out the initial +1 with an extra
2561 // cleanup to do the release at the end of the function.
2562 bool isConsumed = D.hasAttr<NSConsumedAttr>();
2564 // If a parameter is pseudo-strong then we can omit the implicit retain.
2565 if (D.isARCPseudoStrong()) {
2566 assert(lt == Qualifiers::OCL_Strong &&
2567 "pseudo-strong variable isn't strong?");
2568 assert(qs.hasConst() && "pseudo-strong variable should be const!");
2569 lt = Qualifiers::OCL_ExplicitNone;
2572 // Load objects passed indirectly.
2573 if (Arg.isIndirect() && !ArgVal)
2574 ArgVal = Builder.CreateLoad(DeclPtr);
2576 if (lt == Qualifiers::OCL_Strong) {
2577 if (!isConsumed) {
2578 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2579 // use objc_storeStrong(&dest, value) for retaining the
2580 // object. But first, store a null into 'dest' because
2581 // objc_storeStrong attempts to release its old value.
2582 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
2583 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
2584 EmitARCStoreStrongCall(lv.getAddress(*this), ArgVal, true);
2585 DoStore = false;
2587 else
2588 // Don't use objc_retainBlock for block pointers, because we
2589 // don't want to Block_copy something just because we got it
2590 // as a parameter.
2591 ArgVal = EmitARCRetainNonBlock(ArgVal);
2593 } else {
2594 // Push the cleanup for a consumed parameter.
2595 if (isConsumed) {
2596 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
2597 ? ARCPreciseLifetime : ARCImpreciseLifetime);
2598 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
2599 precise);
2602 if (lt == Qualifiers::OCL_Weak) {
2603 EmitARCInitWeak(DeclPtr, ArgVal);
2604 DoStore = false; // The weak init is a store, no need to do two.
2608 // Enter the cleanup scope.
2609 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
2613 // Store the initial value into the alloca.
2614 if (DoStore)
2615 EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
2617 setAddrOfLocalVar(&D, DeclPtr);
2619 // Emit debug info for param declarations in non-thunk functions.
2620 if (CGDebugInfo *DI = getDebugInfo()) {
2621 if (CGM.getCodeGenOpts().hasReducedDebugInfo() && !CurFuncIsThunk &&
2622 !NoDebugInfo) {
2623 llvm::DILocalVariable *DILocalVar = DI->EmitDeclareOfArgVariable(
2624 &D, AllocaPtr.getPointer(), ArgNo, Builder, UseIndirectDebugAddress);
2625 if (const auto *Var = dyn_cast_or_null<ParmVarDecl>(&D))
2626 DI->getParamDbgMappings().insert({Var, DILocalVar});
2630 if (D.hasAttr<AnnotateAttr>())
2631 EmitVarAnnotations(&D, DeclPtr.getPointer());
2633 // We can only check return value nullability if all arguments to the
2634 // function satisfy their nullability preconditions. This makes it necessary
2635 // to emit null checks for args in the function body itself.
2636 if (requiresReturnValueNullabilityCheck()) {
2637 auto Nullability = Ty->getNullability();
2638 if (Nullability && *Nullability == NullabilityKind::NonNull) {
2639 SanitizerScope SanScope(this);
2640 RetValNullabilityPrecondition =
2641 Builder.CreateAnd(RetValNullabilityPrecondition,
2642 Builder.CreateIsNotNull(Arg.getAnyValue()));
2647 void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
2648 CodeGenFunction *CGF) {
2649 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
2650 return;
2651 getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
2654 void CodeGenModule::EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D,
2655 CodeGenFunction *CGF) {
2656 if (!LangOpts.OpenMP || LangOpts.OpenMPSimd ||
2657 (!LangOpts.EmitAllDecls && !D->isUsed()))
2658 return;
2659 getOpenMPRuntime().emitUserDefinedMapper(D, CGF);
2662 void CodeGenModule::EmitOMPRequiresDecl(const OMPRequiresDecl *D) {
2663 getOpenMPRuntime().processRequiresDirective(D);
2666 void CodeGenModule::EmitOMPAllocateDecl(const OMPAllocateDecl *D) {
2667 for (const Expr *E : D->varlists()) {
2668 const auto *DE = cast<DeclRefExpr>(E);
2669 const auto *VD = cast<VarDecl>(DE->getDecl());
2671 // Skip all but globals.
2672 if (!VD->hasGlobalStorage())
2673 continue;
2675 // Check if the global has been materialized yet or not. If not, we are done
2676 // as any later generation will utilize the OMPAllocateDeclAttr. However, if
2677 // we already emitted the global we might have done so before the
2678 // OMPAllocateDeclAttr was attached, leading to the wrong address space
2679 // (potentially). While not pretty, common practise is to remove the old IR
2680 // global and generate a new one, so we do that here too. Uses are replaced
2681 // properly.
2682 StringRef MangledName = getMangledName(VD);
2683 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2684 if (!Entry)
2685 continue;
2687 // We can also keep the existing global if the address space is what we
2688 // expect it to be, if not, it is replaced.
2689 QualType ASTTy = VD->getType();
2690 clang::LangAS GVAS = GetGlobalVarAddressSpace(VD);
2691 auto TargetAS = getContext().getTargetAddressSpace(GVAS);
2692 if (Entry->getType()->getAddressSpace() == TargetAS)
2693 continue;
2695 // Make a new global with the correct type / address space.
2696 llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
2697 llvm::PointerType *PTy = llvm::PointerType::get(Ty, TargetAS);
2699 // Replace all uses of the old global with a cast. Since we mutate the type
2700 // in place we neeed an intermediate that takes the spot of the old entry
2701 // until we can create the cast.
2702 llvm::GlobalVariable *DummyGV = new llvm::GlobalVariable(
2703 getModule(), Entry->getValueType(), false,
2704 llvm::GlobalValue::CommonLinkage, nullptr, "dummy", nullptr,
2705 llvm::GlobalVariable::NotThreadLocal, Entry->getAddressSpace());
2706 Entry->replaceAllUsesWith(DummyGV);
2708 Entry->mutateType(PTy);
2709 llvm::Constant *NewPtrForOldDecl =
2710 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
2711 Entry, DummyGV->getType());
2713 // Now we have a casted version of the changed global, the dummy can be
2714 // replaced and deleted.
2715 DummyGV->replaceAllUsesWith(NewPtrForOldDecl);
2716 DummyGV->eraseFromParent();
2720 std::optional<CharUnits>
2721 CodeGenModule::getOMPAllocateAlignment(const VarDecl *VD) {
2722 if (const auto *AA = VD->getAttr<OMPAllocateDeclAttr>()) {
2723 if (Expr *Alignment = AA->getAlignment()) {
2724 unsigned UserAlign =
2725 Alignment->EvaluateKnownConstInt(getContext()).getExtValue();
2726 CharUnits NaturalAlign =
2727 getNaturalTypeAlignment(VD->getType().getNonReferenceType());
2729 // OpenMP5.1 pg 185 lines 7-10
2730 // Each item in the align modifier list must be aligned to the maximum
2731 // of the specified alignment and the type's natural alignment.
2732 return CharUnits::fromQuantity(
2733 std::max<unsigned>(UserAlign, NaturalAlign.getQuantity()));
2736 return std::nullopt;