[clang][modules] Don't prevent translation of FW_Private includes when explicitly...
[llvm-project.git] / clang / lib / CodeGen / CGDecl.cpp
blob0420f438ec1392ccd8dbb51e8ebed0aab1ad8a93
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::UsingShadow:
100 case Decl::ConstructorUsingShadow:
101 case Decl::ObjCTypeParam:
102 case Decl::Binding:
103 case Decl::UnresolvedUsingIfExists:
104 case Decl::HLSLBuffer:
105 llvm_unreachable("Declaration should not be in declstmts!");
106 case Decl::Record: // struct/union/class X;
107 case Decl::CXXRecord: // struct/union/class X; [C++]
108 if (CGDebugInfo *DI = getDebugInfo())
109 if (cast<RecordDecl>(D).getDefinition())
110 DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(&D)));
111 return;
112 case Decl::Enum: // enum X;
113 if (CGDebugInfo *DI = getDebugInfo())
114 if (cast<EnumDecl>(D).getDefinition())
115 DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(&D)));
116 return;
117 case Decl::Function: // void X();
118 case Decl::EnumConstant: // enum ? { X = ? }
119 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
120 case Decl::Label: // __label__ x;
121 case Decl::Import:
122 case Decl::MSGuid: // __declspec(uuid("..."))
123 case Decl::UnnamedGlobalConstant:
124 case Decl::TemplateParamObject:
125 case Decl::OMPThreadPrivate:
126 case Decl::OMPAllocate:
127 case Decl::OMPCapturedExpr:
128 case Decl::OMPRequires:
129 case Decl::Empty:
130 case Decl::Concept:
131 case Decl::ImplicitConceptSpecialization:
132 case Decl::LifetimeExtendedTemporary:
133 case Decl::RequiresExprBody:
134 // None of these decls require codegen support.
135 return;
137 case Decl::NamespaceAlias:
138 if (CGDebugInfo *DI = getDebugInfo())
139 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
140 return;
141 case Decl::Using: // using X; [C++]
142 if (CGDebugInfo *DI = getDebugInfo())
143 DI->EmitUsingDecl(cast<UsingDecl>(D));
144 return;
145 case Decl::UsingEnum: // using enum X; [C++]
146 if (CGDebugInfo *DI = getDebugInfo())
147 DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(D));
148 return;
149 case Decl::UsingPack:
150 for (auto *Using : cast<UsingPackDecl>(D).expansions())
151 EmitDecl(*Using);
152 return;
153 case Decl::UsingDirective: // using namespace X; [C++]
154 if (CGDebugInfo *DI = getDebugInfo())
155 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
156 return;
157 case Decl::Var:
158 case Decl::Decomposition: {
159 const VarDecl &VD = cast<VarDecl>(D);
160 assert(VD.isLocalVarDecl() &&
161 "Should not see file-scope variables inside a function!");
162 EmitVarDecl(VD);
163 if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
164 for (auto *B : DD->bindings())
165 if (auto *HD = B->getHoldingVar())
166 EmitVarDecl(*HD);
167 return;
170 case Decl::OMPDeclareReduction:
171 return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
173 case Decl::OMPDeclareMapper:
174 return CGM.EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(&D), this);
176 case Decl::Typedef: // typedef int X;
177 case Decl::TypeAlias: { // using X = int; [C++0x]
178 QualType Ty = cast<TypedefNameDecl>(D).getUnderlyingType();
179 if (CGDebugInfo *DI = getDebugInfo())
180 DI->EmitAndRetainType(Ty);
181 if (Ty->isVariablyModifiedType())
182 EmitVariablyModifiedType(Ty);
183 return;
188 /// EmitVarDecl - This method handles emission of any variable declaration
189 /// inside a function, including static vars etc.
190 void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
191 if (D.hasExternalStorage())
192 // Don't emit it now, allow it to be emitted lazily on its first use.
193 return;
195 // Some function-scope variable does not have static storage but still
196 // needs to be emitted like a static variable, e.g. a function-scope
197 // variable in constant address space in OpenCL.
198 if (D.getStorageDuration() != SD_Automatic) {
199 // Static sampler variables translated to function calls.
200 if (D.getType()->isSamplerT())
201 return;
203 llvm::GlobalValue::LinkageTypes Linkage =
204 CGM.getLLVMLinkageVarDefinition(&D);
206 // FIXME: We need to force the emission/use of a guard variable for
207 // some variables even if we can constant-evaluate them because
208 // we can't guarantee every translation unit will constant-evaluate them.
210 return EmitStaticVarDecl(D, Linkage);
213 if (D.getType().getAddressSpace() == LangAS::opencl_local)
214 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
216 assert(D.hasLocalStorage());
217 return EmitAutoVarDecl(D);
220 static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
221 if (CGM.getLangOpts().CPlusPlus)
222 return CGM.getMangledName(&D).str();
224 // If this isn't C++, we don't need a mangled name, just a pretty one.
225 assert(!D.isExternallyVisible() && "name shouldn't matter");
226 std::string ContextName;
227 const DeclContext *DC = D.getDeclContext();
228 if (auto *CD = dyn_cast<CapturedDecl>(DC))
229 DC = cast<DeclContext>(CD->getNonClosureContext());
230 if (const auto *FD = dyn_cast<FunctionDecl>(DC))
231 ContextName = std::string(CGM.getMangledName(FD));
232 else if (const auto *BD = dyn_cast<BlockDecl>(DC))
233 ContextName = std::string(CGM.getBlockMangledName(GlobalDecl(), BD));
234 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
235 ContextName = OMD->getSelector().getAsString();
236 else
237 llvm_unreachable("Unknown context for static var decl");
239 ContextName += "." + D.getNameAsString();
240 return ContextName;
243 llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
244 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
245 // In general, we don't always emit static var decls once before we reference
246 // them. It is possible to reference them before emitting the function that
247 // contains them, and it is possible to emit the containing function multiple
248 // times.
249 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
250 return ExistingGV;
252 QualType Ty = D.getType();
253 assert(Ty->isConstantSizeType() && "VLAs can't be static");
255 // Use the label if the variable is renamed with the asm-label extension.
256 std::string Name;
257 if (D.hasAttr<AsmLabelAttr>())
258 Name = std::string(getMangledName(&D));
259 else
260 Name = getStaticDeclName(*this, D);
262 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
263 LangAS AS = GetGlobalVarAddressSpace(&D);
264 unsigned TargetAS = getContext().getTargetAddressSpace(AS);
266 // OpenCL variables in local address space and CUDA shared
267 // variables cannot have an initializer.
268 llvm::Constant *Init = nullptr;
269 if (Ty.getAddressSpace() == LangAS::opencl_local ||
270 D.hasAttr<CUDASharedAttr>() || D.hasAttr<LoaderUninitializedAttr>())
271 Init = llvm::UndefValue::get(LTy);
272 else
273 Init = EmitNullConstant(Ty);
275 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
276 getModule(), LTy, Ty.isConstant(getContext()), Linkage, Init, Name,
277 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
278 GV->setAlignment(getContext().getDeclAlign(&D).getAsAlign());
280 if (supportsCOMDAT() && GV->isWeakForLinker())
281 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
283 if (D.getTLSKind())
284 setTLSMode(GV, D);
286 setGVProperties(GV, &D);
288 // Make sure the result is of the correct type.
289 LangAS ExpectedAS = Ty.getAddressSpace();
290 llvm::Constant *Addr = GV;
291 if (AS != ExpectedAS) {
292 Addr = getTargetCodeGenInfo().performAddrSpaceCast(
293 *this, GV, AS, ExpectedAS,
294 llvm::PointerType::get(getLLVMContext(),
295 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 OldGV->replaceAllUsesWith(GV);
391 // Erase the old global, since it is no longer used.
392 OldGV->eraseFromParent();
395 bool NeedsDtor =
396 D.needsDestruction(getContext()) == QualType::DK_cxx_destructor;
398 GV->setConstant(
399 D.getType().isConstantStorage(getContext(), true, !NeedsDtor));
400 GV->setInitializer(Init);
402 emitter.finalize(GV);
404 if (NeedsDtor && HaveInsertPoint()) {
405 // We have a constant initializer, but a nontrivial destructor. We still
406 // need to perform a guarded "initialization" in order to register the
407 // destructor.
408 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
411 return GV;
414 void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
415 llvm::GlobalValue::LinkageTypes Linkage) {
416 // Check to see if we already have a global variable for this
417 // declaration. This can happen when double-emitting function
418 // bodies, e.g. with complete and base constructors.
419 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
420 CharUnits alignment = getContext().getDeclAlign(&D);
422 // Store into LocalDeclMap before generating initializer to handle
423 // circular references.
424 llvm::Type *elemTy = ConvertTypeForMem(D.getType());
425 setAddrOfLocalVar(&D, Address(addr, elemTy, alignment));
427 // We can't have a VLA here, but we can have a pointer to a VLA,
428 // even though that doesn't really make any sense.
429 // Make sure to evaluate VLA bounds now so that we have them for later.
430 if (D.getType()->isVariablyModifiedType())
431 EmitVariablyModifiedType(D.getType());
433 // Save the type in case adding the initializer forces a type change.
434 llvm::Type *expectedType = addr->getType();
436 llvm::GlobalVariable *var =
437 cast<llvm::GlobalVariable>(addr->stripPointerCasts());
439 // CUDA's local and local static __shared__ variables should not
440 // have any non-empty initializers. This is ensured by Sema.
441 // Whatever initializer such variable may have when it gets here is
442 // a no-op and should not be emitted.
443 bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
444 D.hasAttr<CUDASharedAttr>();
445 // If this value has an initializer, emit it.
446 if (D.getInit() && !isCudaSharedVar)
447 var = AddInitializerToStaticVarDecl(D, var);
449 var->setAlignment(alignment.getAsAlign());
451 if (D.hasAttr<AnnotateAttr>())
452 CGM.AddGlobalAnnotations(&D, var);
454 if (auto *SA = D.getAttr<PragmaClangBSSSectionAttr>())
455 var->addAttribute("bss-section", SA->getName());
456 if (auto *SA = D.getAttr<PragmaClangDataSectionAttr>())
457 var->addAttribute("data-section", SA->getName());
458 if (auto *SA = D.getAttr<PragmaClangRodataSectionAttr>())
459 var->addAttribute("rodata-section", SA->getName());
460 if (auto *SA = D.getAttr<PragmaClangRelroSectionAttr>())
461 var->addAttribute("relro-section", SA->getName());
463 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
464 var->setSection(SA->getName());
466 if (D.hasAttr<RetainAttr>())
467 CGM.addUsedGlobal(var);
468 else if (D.hasAttr<UsedAttr>())
469 CGM.addUsedOrCompilerUsedGlobal(var);
471 if (CGM.getCodeGenOpts().KeepPersistentStorageVariables)
472 CGM.addUsedOrCompilerUsedGlobal(var);
474 // We may have to cast the constant because of the initializer
475 // mismatch above.
477 // FIXME: It is really dangerous to store this in the map; if anyone
478 // RAUW's the GV uses of this constant will be invalid.
479 llvm::Constant *castedAddr =
480 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
481 LocalDeclMap.find(&D)->second = Address(castedAddr, elemTy, alignment);
482 CGM.setStaticLocalDeclAddress(&D, castedAddr);
484 CGM.getSanitizerMetadata()->reportGlobal(var, D);
486 // Emit global variable debug descriptor for static vars.
487 CGDebugInfo *DI = getDebugInfo();
488 if (DI && CGM.getCodeGenOpts().hasReducedDebugInfo()) {
489 DI->setLocation(D.getLocation());
490 DI->EmitGlobalVariable(var, &D);
494 namespace {
495 struct DestroyObject final : EHScopeStack::Cleanup {
496 DestroyObject(Address addr, QualType type,
497 CodeGenFunction::Destroyer *destroyer,
498 bool useEHCleanupForArray)
499 : addr(addr), type(type), destroyer(destroyer),
500 useEHCleanupForArray(useEHCleanupForArray) {}
502 Address addr;
503 QualType type;
504 CodeGenFunction::Destroyer *destroyer;
505 bool useEHCleanupForArray;
507 void Emit(CodeGenFunction &CGF, Flags flags) override {
508 // Don't use an EH cleanup recursively from an EH cleanup.
509 bool useEHCleanupForArray =
510 flags.isForNormalCleanup() && this->useEHCleanupForArray;
512 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
516 template <class Derived>
517 struct DestroyNRVOVariable : EHScopeStack::Cleanup {
518 DestroyNRVOVariable(Address addr, QualType type, llvm::Value *NRVOFlag)
519 : NRVOFlag(NRVOFlag), Loc(addr), Ty(type) {}
521 llvm::Value *NRVOFlag;
522 Address Loc;
523 QualType Ty;
525 void Emit(CodeGenFunction &CGF, Flags flags) override {
526 // Along the exceptions path we always execute the dtor.
527 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
529 llvm::BasicBlock *SkipDtorBB = nullptr;
530 if (NRVO) {
531 // If we exited via NRVO, we skip the destructor call.
532 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
533 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
534 llvm::Value *DidNRVO =
535 CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
536 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
537 CGF.EmitBlock(RunDtorBB);
540 static_cast<Derived *>(this)->emitDestructorCall(CGF);
542 if (NRVO) CGF.EmitBlock(SkipDtorBB);
545 virtual ~DestroyNRVOVariable() = default;
548 struct DestroyNRVOVariableCXX final
549 : DestroyNRVOVariable<DestroyNRVOVariableCXX> {
550 DestroyNRVOVariableCXX(Address addr, QualType type,
551 const CXXDestructorDecl *Dtor, llvm::Value *NRVOFlag)
552 : DestroyNRVOVariable<DestroyNRVOVariableCXX>(addr, type, NRVOFlag),
553 Dtor(Dtor) {}
555 const CXXDestructorDecl *Dtor;
557 void emitDestructorCall(CodeGenFunction &CGF) {
558 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
559 /*ForVirtualBase=*/false,
560 /*Delegating=*/false, Loc, Ty);
564 struct DestroyNRVOVariableC final
565 : DestroyNRVOVariable<DestroyNRVOVariableC> {
566 DestroyNRVOVariableC(Address addr, llvm::Value *NRVOFlag, QualType Ty)
567 : DestroyNRVOVariable<DestroyNRVOVariableC>(addr, Ty, NRVOFlag) {}
569 void emitDestructorCall(CodeGenFunction &CGF) {
570 CGF.destroyNonTrivialCStruct(CGF, Loc, Ty);
574 struct CallStackRestore final : EHScopeStack::Cleanup {
575 Address Stack;
576 CallStackRestore(Address Stack) : Stack(Stack) {}
577 bool isRedundantBeforeReturn() override { return true; }
578 void Emit(CodeGenFunction &CGF, Flags flags) override {
579 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
580 CGF.Builder.CreateStackRestore(V);
584 struct KmpcAllocFree final : EHScopeStack::Cleanup {
585 std::pair<llvm::Value *, llvm::Value *> AddrSizePair;
586 KmpcAllocFree(const std::pair<llvm::Value *, llvm::Value *> &AddrSizePair)
587 : AddrSizePair(AddrSizePair) {}
588 void Emit(CodeGenFunction &CGF, Flags EmissionFlags) override {
589 auto &RT = CGF.CGM.getOpenMPRuntime();
590 RT.getKmpcFreeShared(CGF, AddrSizePair);
594 struct ExtendGCLifetime final : EHScopeStack::Cleanup {
595 const VarDecl &Var;
596 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
598 void Emit(CodeGenFunction &CGF, Flags flags) override {
599 // Compute the address of the local variable, in case it's a
600 // byref or something.
601 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
602 Var.getType(), VK_LValue, SourceLocation());
603 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
604 SourceLocation());
605 CGF.EmitExtendGCLifetime(value);
609 struct CallCleanupFunction final : EHScopeStack::Cleanup {
610 llvm::Constant *CleanupFn;
611 const CGFunctionInfo &FnInfo;
612 const VarDecl &Var;
614 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
615 const VarDecl *Var)
616 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
618 void Emit(CodeGenFunction &CGF, Flags flags) override {
619 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
620 Var.getType(), VK_LValue, SourceLocation());
621 // Compute the address of the local variable, in case it's a byref
622 // or something.
623 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer(CGF);
625 // In some cases, the type of the function argument will be different from
626 // the type of the pointer. An example of this is
627 // void f(void* arg);
628 // __attribute__((cleanup(f))) void *g;
630 // To fix this we insert a bitcast here.
631 QualType ArgTy = FnInfo.arg_begin()->type;
632 llvm::Value *Arg =
633 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
635 CallArgList Args;
636 Args.add(RValue::get(Arg),
637 CGF.getContext().getPointerType(Var.getType()));
638 auto Callee = CGCallee::forDirect(CleanupFn);
639 CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
642 } // end anonymous namespace
644 /// EmitAutoVarWithLifetime - Does the setup required for an automatic
645 /// variable with lifetime.
646 static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
647 Address addr,
648 Qualifiers::ObjCLifetime lifetime) {
649 switch (lifetime) {
650 case Qualifiers::OCL_None:
651 llvm_unreachable("present but none");
653 case Qualifiers::OCL_ExplicitNone:
654 // nothing to do
655 break;
657 case Qualifiers::OCL_Strong: {
658 CodeGenFunction::Destroyer *destroyer =
659 (var.hasAttr<ObjCPreciseLifetimeAttr>()
660 ? CodeGenFunction::destroyARCStrongPrecise
661 : CodeGenFunction::destroyARCStrongImprecise);
663 CleanupKind cleanupKind = CGF.getARCCleanupKind();
664 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
665 cleanupKind & EHCleanup);
666 break;
668 case Qualifiers::OCL_Autoreleasing:
669 // nothing to do
670 break;
672 case Qualifiers::OCL_Weak:
673 // __weak objects always get EH cleanups; otherwise, exceptions
674 // could cause really nasty crashes instead of mere leaks.
675 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
676 CodeGenFunction::destroyARCWeak,
677 /*useEHCleanup*/ true);
678 break;
682 static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
683 if (const Expr *e = dyn_cast<Expr>(s)) {
684 // Skip the most common kinds of expressions that make
685 // hierarchy-walking expensive.
686 s = e = e->IgnoreParenCasts();
688 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
689 return (ref->getDecl() == &var);
690 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
691 const BlockDecl *block = be->getBlockDecl();
692 for (const auto &I : block->captures()) {
693 if (I.getVariable() == &var)
694 return true;
699 for (const Stmt *SubStmt : s->children())
700 // SubStmt might be null; as in missing decl or conditional of an if-stmt.
701 if (SubStmt && isAccessedBy(var, SubStmt))
702 return true;
704 return false;
707 static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
708 if (!decl) return false;
709 if (!isa<VarDecl>(decl)) return false;
710 const VarDecl *var = cast<VarDecl>(decl);
711 return isAccessedBy(*var, e);
714 static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
715 const LValue &destLV, const Expr *init) {
716 bool needsCast = false;
718 while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
719 switch (castExpr->getCastKind()) {
720 // Look through casts that don't require representation changes.
721 case CK_NoOp:
722 case CK_BitCast:
723 case CK_BlockPointerToObjCPointerCast:
724 needsCast = true;
725 break;
727 // If we find an l-value to r-value cast from a __weak variable,
728 // emit this operation as a copy or move.
729 case CK_LValueToRValue: {
730 const Expr *srcExpr = castExpr->getSubExpr();
731 if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
732 return false;
734 // Emit the source l-value.
735 LValue srcLV = CGF.EmitLValue(srcExpr);
737 // Handle a formal type change to avoid asserting.
738 auto srcAddr = srcLV.getAddress(CGF);
739 if (needsCast) {
740 srcAddr =
741 srcAddr.withElementType(destLV.getAddress(CGF).getElementType());
744 // If it was an l-value, use objc_copyWeak.
745 if (srcExpr->isLValue()) {
746 CGF.EmitARCCopyWeak(destLV.getAddress(CGF), srcAddr);
747 } else {
748 assert(srcExpr->isXValue());
749 CGF.EmitARCMoveWeak(destLV.getAddress(CGF), srcAddr);
751 return true;
754 // Stop at anything else.
755 default:
756 return false;
759 init = castExpr->getSubExpr();
761 return false;
764 static void drillIntoBlockVariable(CodeGenFunction &CGF,
765 LValue &lvalue,
766 const VarDecl *var) {
767 lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(CGF), var));
770 void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS,
771 SourceLocation Loc) {
772 if (!SanOpts.has(SanitizerKind::NullabilityAssign))
773 return;
775 auto Nullability = LHS.getType()->getNullability();
776 if (!Nullability || *Nullability != NullabilityKind::NonNull)
777 return;
779 // Check if the right hand side of the assignment is nonnull, if the left
780 // hand side must be nonnull.
781 SanitizerScope SanScope(this);
782 llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS);
783 llvm::Constant *StaticData[] = {
784 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(LHS.getType()),
785 llvm::ConstantInt::get(Int8Ty, 0), // The LogAlignment info is unused.
786 llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)};
787 EmitCheck({{IsNotNull, SanitizerKind::NullabilityAssign}},
788 SanitizerHandler::TypeMismatch, StaticData, RHS);
791 void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
792 LValue lvalue, bool capturedByInit) {
793 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
794 if (!lifetime) {
795 llvm::Value *value = EmitScalarExpr(init);
796 if (capturedByInit)
797 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
798 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
799 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
800 return;
803 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
804 init = DIE->getExpr();
806 // If we're emitting a value with lifetime, we have to do the
807 // initialization *before* we leave the cleanup scopes.
808 if (auto *EWC = dyn_cast<ExprWithCleanups>(init)) {
809 CodeGenFunction::RunCleanupsScope Scope(*this);
810 return EmitScalarInit(EWC->getSubExpr(), D, lvalue, capturedByInit);
813 // We have to maintain the illusion that the variable is
814 // zero-initialized. If the variable might be accessed in its
815 // initializer, zero-initialize before running the initializer, then
816 // actually perform the initialization with an assign.
817 bool accessedByInit = false;
818 if (lifetime != Qualifiers::OCL_ExplicitNone)
819 accessedByInit = (capturedByInit || isAccessedBy(D, init));
820 if (accessedByInit) {
821 LValue tempLV = lvalue;
822 // Drill down to the __block object if necessary.
823 if (capturedByInit) {
824 // We can use a simple GEP for this because it can't have been
825 // moved yet.
826 tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(*this),
827 cast<VarDecl>(D),
828 /*follow*/ false));
831 auto ty =
832 cast<llvm::PointerType>(tempLV.getAddress(*this).getElementType());
833 llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());
835 // If __weak, we want to use a barrier under certain conditions.
836 if (lifetime == Qualifiers::OCL_Weak)
837 EmitARCInitWeak(tempLV.getAddress(*this), zero);
839 // Otherwise just do a simple store.
840 else
841 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
844 // Emit the initializer.
845 llvm::Value *value = nullptr;
847 switch (lifetime) {
848 case Qualifiers::OCL_None:
849 llvm_unreachable("present but none");
851 case Qualifiers::OCL_Strong: {
852 if (!D || !isa<VarDecl>(D) || !cast<VarDecl>(D)->isARCPseudoStrong()) {
853 value = EmitARCRetainScalarExpr(init);
854 break;
856 // If D is pseudo-strong, treat it like __unsafe_unretained here. This means
857 // that we omit the retain, and causes non-autoreleased return values to be
858 // immediately released.
859 [[fallthrough]];
862 case Qualifiers::OCL_ExplicitNone:
863 value = EmitARCUnsafeUnretainedScalarExpr(init);
864 break;
866 case Qualifiers::OCL_Weak: {
867 // If it's not accessed by the initializer, try to emit the
868 // initialization with a copy or move.
869 if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
870 return;
873 // No way to optimize a producing initializer into this. It's not
874 // worth optimizing for, because the value will immediately
875 // disappear in the common case.
876 value = EmitScalarExpr(init);
878 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
879 if (accessedByInit)
880 EmitARCStoreWeak(lvalue.getAddress(*this), value, /*ignored*/ true);
881 else
882 EmitARCInitWeak(lvalue.getAddress(*this), value);
883 return;
886 case Qualifiers::OCL_Autoreleasing:
887 value = EmitARCRetainAutoreleaseScalarExpr(init);
888 break;
891 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
893 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
895 // If the variable might have been accessed by its initializer, we
896 // might have to initialize with a barrier. We have to do this for
897 // both __weak and __strong, but __weak got filtered out above.
898 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
899 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
900 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
901 EmitARCRelease(oldValue, ARCImpreciseLifetime);
902 return;
905 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
908 /// Decide whether we can emit the non-zero parts of the specified initializer
909 /// with equal or fewer than NumStores scalar stores.
910 static bool canEmitInitWithFewStoresAfterBZero(llvm::Constant *Init,
911 unsigned &NumStores) {
912 // Zero and Undef never requires any extra stores.
913 if (isa<llvm::ConstantAggregateZero>(Init) ||
914 isa<llvm::ConstantPointerNull>(Init) ||
915 isa<llvm::UndefValue>(Init))
916 return true;
917 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
918 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
919 isa<llvm::ConstantExpr>(Init))
920 return Init->isNullValue() || NumStores--;
922 // See if we can emit each element.
923 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
924 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
925 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
926 if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
927 return false;
929 return true;
932 if (llvm::ConstantDataSequential *CDS =
933 dyn_cast<llvm::ConstantDataSequential>(Init)) {
934 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
935 llvm::Constant *Elt = CDS->getElementAsConstant(i);
936 if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
937 return false;
939 return true;
942 // Anything else is hard and scary.
943 return false;
946 /// For inits that canEmitInitWithFewStoresAfterBZero returned true for, emit
947 /// the scalar stores that would be required.
948 static void emitStoresForInitAfterBZero(CodeGenModule &CGM,
949 llvm::Constant *Init, Address Loc,
950 bool isVolatile, CGBuilderTy &Builder,
951 bool IsAutoInit) {
952 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
953 "called emitStoresForInitAfterBZero for zero or undef value.");
955 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
956 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
957 isa<llvm::ConstantExpr>(Init)) {
958 auto *I = Builder.CreateStore(Init, Loc, isVolatile);
959 if (IsAutoInit)
960 I->addAnnotationMetadata("auto-init");
961 return;
964 if (llvm::ConstantDataSequential *CDS =
965 dyn_cast<llvm::ConstantDataSequential>(Init)) {
966 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
967 llvm::Constant *Elt = CDS->getElementAsConstant(i);
969 // If necessary, get a pointer to the element and emit it.
970 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
971 emitStoresForInitAfterBZero(
972 CGM, Elt, Builder.CreateConstInBoundsGEP2_32(Loc, 0, i), isVolatile,
973 Builder, IsAutoInit);
975 return;
978 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
979 "Unknown value type!");
981 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
982 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
984 // If necessary, get a pointer to the element and emit it.
985 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
986 emitStoresForInitAfterBZero(CGM, Elt,
987 Builder.CreateConstInBoundsGEP2_32(Loc, 0, i),
988 isVolatile, Builder, IsAutoInit);
992 /// Decide whether we should use bzero plus some stores to initialize a local
993 /// variable instead of using a memcpy from a constant global. It is beneficial
994 /// to use bzero if the global is all zeros, or mostly zeros and large.
995 static bool shouldUseBZeroPlusStoresToInitialize(llvm::Constant *Init,
996 uint64_t GlobalSize) {
997 // If a global is all zeros, always use a bzero.
998 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
1000 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
1001 // do it if it will require 6 or fewer scalar stores.
1002 // TODO: Should budget depends on the size? Avoiding a large global warrants
1003 // plopping in more stores.
1004 unsigned StoreBudget = 6;
1005 uint64_t SizeLimit = 32;
1007 return GlobalSize > SizeLimit &&
1008 canEmitInitWithFewStoresAfterBZero(Init, StoreBudget);
1011 /// Decide whether we should use memset to initialize a local variable instead
1012 /// of using a memcpy from a constant global. Assumes we've already decided to
1013 /// not user bzero.
1014 /// FIXME We could be more clever, as we are for bzero above, and generate
1015 /// memset followed by stores. It's unclear that's worth the effort.
1016 static llvm::Value *shouldUseMemSetToInitialize(llvm::Constant *Init,
1017 uint64_t GlobalSize,
1018 const llvm::DataLayout &DL) {
1019 uint64_t SizeLimit = 32;
1020 if (GlobalSize <= SizeLimit)
1021 return nullptr;
1022 return llvm::isBytewiseValue(Init, DL);
1025 /// Decide whether we want to split a constant structure or array store into a
1026 /// sequence of its fields' stores. This may cost us code size and compilation
1027 /// speed, but plays better with store optimizations.
1028 static bool shouldSplitConstantStore(CodeGenModule &CGM,
1029 uint64_t GlobalByteSize) {
1030 // Don't break things that occupy more than one cacheline.
1031 uint64_t ByteSizeLimit = 64;
1032 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
1033 return false;
1034 if (GlobalByteSize <= ByteSizeLimit)
1035 return true;
1036 return false;
1039 enum class IsPattern { No, Yes };
1041 /// Generate a constant filled with either a pattern or zeroes.
1042 static llvm::Constant *patternOrZeroFor(CodeGenModule &CGM, IsPattern isPattern,
1043 llvm::Type *Ty) {
1044 if (isPattern == IsPattern::Yes)
1045 return initializationPatternFor(CGM, Ty);
1046 else
1047 return llvm::Constant::getNullValue(Ty);
1050 static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
1051 llvm::Constant *constant);
1053 /// Helper function for constWithPadding() to deal with padding in structures.
1054 static llvm::Constant *constStructWithPadding(CodeGenModule &CGM,
1055 IsPattern isPattern,
1056 llvm::StructType *STy,
1057 llvm::Constant *constant) {
1058 const llvm::DataLayout &DL = CGM.getDataLayout();
1059 const llvm::StructLayout *Layout = DL.getStructLayout(STy);
1060 llvm::Type *Int8Ty = llvm::IntegerType::getInt8Ty(CGM.getLLVMContext());
1061 unsigned SizeSoFar = 0;
1062 SmallVector<llvm::Constant *, 8> Values;
1063 bool NestedIntact = true;
1064 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1065 unsigned CurOff = Layout->getElementOffset(i);
1066 if (SizeSoFar < CurOff) {
1067 assert(!STy->isPacked());
1068 auto *PadTy = llvm::ArrayType::get(Int8Ty, CurOff - SizeSoFar);
1069 Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy));
1071 llvm::Constant *CurOp;
1072 if (constant->isZeroValue())
1073 CurOp = llvm::Constant::getNullValue(STy->getElementType(i));
1074 else
1075 CurOp = cast<llvm::Constant>(constant->getAggregateElement(i));
1076 auto *NewOp = constWithPadding(CGM, isPattern, CurOp);
1077 if (CurOp != NewOp)
1078 NestedIntact = false;
1079 Values.push_back(NewOp);
1080 SizeSoFar = CurOff + DL.getTypeAllocSize(CurOp->getType());
1082 unsigned TotalSize = Layout->getSizeInBytes();
1083 if (SizeSoFar < TotalSize) {
1084 auto *PadTy = llvm::ArrayType::get(Int8Ty, TotalSize - SizeSoFar);
1085 Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy));
1087 if (NestedIntact && Values.size() == STy->getNumElements())
1088 return constant;
1089 return llvm::ConstantStruct::getAnon(Values, STy->isPacked());
1092 /// Replace all padding bytes in a given constant with either a pattern byte or
1093 /// 0x00.
1094 static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
1095 llvm::Constant *constant) {
1096 llvm::Type *OrigTy = constant->getType();
1097 if (const auto STy = dyn_cast<llvm::StructType>(OrigTy))
1098 return constStructWithPadding(CGM, isPattern, STy, constant);
1099 if (auto *ArrayTy = dyn_cast<llvm::ArrayType>(OrigTy)) {
1100 llvm::SmallVector<llvm::Constant *, 8> Values;
1101 uint64_t Size = ArrayTy->getNumElements();
1102 if (!Size)
1103 return constant;
1104 llvm::Type *ElemTy = ArrayTy->getElementType();
1105 bool ZeroInitializer = constant->isNullValue();
1106 llvm::Constant *OpValue, *PaddedOp;
1107 if (ZeroInitializer) {
1108 OpValue = llvm::Constant::getNullValue(ElemTy);
1109 PaddedOp = constWithPadding(CGM, isPattern, OpValue);
1111 for (unsigned Op = 0; Op != Size; ++Op) {
1112 if (!ZeroInitializer) {
1113 OpValue = constant->getAggregateElement(Op);
1114 PaddedOp = constWithPadding(CGM, isPattern, OpValue);
1116 Values.push_back(PaddedOp);
1118 auto *NewElemTy = Values[0]->getType();
1119 if (NewElemTy == ElemTy)
1120 return constant;
1121 auto *NewArrayTy = llvm::ArrayType::get(NewElemTy, Size);
1122 return llvm::ConstantArray::get(NewArrayTy, Values);
1124 // FIXME: Add handling for tail padding in vectors. Vectors don't
1125 // have padding between or inside elements, but the total amount of
1126 // data can be less than the allocated size.
1127 return constant;
1130 Address CodeGenModule::createUnnamedGlobalFrom(const VarDecl &D,
1131 llvm::Constant *Constant,
1132 CharUnits Align) {
1133 auto FunctionName = [&](const DeclContext *DC) -> std::string {
1134 if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
1135 if (const auto *CC = dyn_cast<CXXConstructorDecl>(FD))
1136 return CC->getNameAsString();
1137 if (const auto *CD = dyn_cast<CXXDestructorDecl>(FD))
1138 return CD->getNameAsString();
1139 return std::string(getMangledName(FD));
1140 } else if (const auto *OM = dyn_cast<ObjCMethodDecl>(DC)) {
1141 return OM->getNameAsString();
1142 } else if (isa<BlockDecl>(DC)) {
1143 return "<block>";
1144 } else if (isa<CapturedDecl>(DC)) {
1145 return "<captured>";
1146 } else {
1147 llvm_unreachable("expected a function or method");
1151 // Form a simple per-variable cache of these values in case we find we
1152 // want to reuse them.
1153 llvm::GlobalVariable *&CacheEntry = InitializerConstants[&D];
1154 if (!CacheEntry || CacheEntry->getInitializer() != Constant) {
1155 auto *Ty = Constant->getType();
1156 bool isConstant = true;
1157 llvm::GlobalVariable *InsertBefore = nullptr;
1158 unsigned AS =
1159 getContext().getTargetAddressSpace(GetGlobalConstantAddressSpace());
1160 std::string Name;
1161 if (D.hasGlobalStorage())
1162 Name = getMangledName(&D).str() + ".const";
1163 else if (const DeclContext *DC = D.getParentFunctionOrMethod())
1164 Name = ("__const." + FunctionName(DC) + "." + D.getName()).str();
1165 else
1166 llvm_unreachable("local variable has no parent function or method");
1167 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1168 getModule(), Ty, isConstant, llvm::GlobalValue::PrivateLinkage,
1169 Constant, Name, InsertBefore, llvm::GlobalValue::NotThreadLocal, AS);
1170 GV->setAlignment(Align.getAsAlign());
1171 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1172 CacheEntry = GV;
1173 } else if (CacheEntry->getAlignment() < uint64_t(Align.getQuantity())) {
1174 CacheEntry->setAlignment(Align.getAsAlign());
1177 return Address(CacheEntry, CacheEntry->getValueType(), Align);
1180 static Address createUnnamedGlobalForMemcpyFrom(CodeGenModule &CGM,
1181 const VarDecl &D,
1182 CGBuilderTy &Builder,
1183 llvm::Constant *Constant,
1184 CharUnits Align) {
1185 Address SrcPtr = CGM.createUnnamedGlobalFrom(D, Constant, Align);
1186 return SrcPtr.withElementType(CGM.Int8Ty);
1189 static void emitStoresForConstant(CodeGenModule &CGM, const VarDecl &D,
1190 Address Loc, bool isVolatile,
1191 CGBuilderTy &Builder,
1192 llvm::Constant *constant, bool IsAutoInit) {
1193 auto *Ty = constant->getType();
1194 uint64_t ConstantSize = CGM.getDataLayout().getTypeAllocSize(Ty);
1195 if (!ConstantSize)
1196 return;
1198 bool canDoSingleStore = Ty->isIntOrIntVectorTy() ||
1199 Ty->isPtrOrPtrVectorTy() || Ty->isFPOrFPVectorTy();
1200 if (canDoSingleStore) {
1201 auto *I = Builder.CreateStore(constant, Loc, isVolatile);
1202 if (IsAutoInit)
1203 I->addAnnotationMetadata("auto-init");
1204 return;
1207 auto *SizeVal = llvm::ConstantInt::get(CGM.IntPtrTy, ConstantSize);
1209 // If the initializer is all or mostly the same, codegen with bzero / memset
1210 // then do a few stores afterward.
1211 if (shouldUseBZeroPlusStoresToInitialize(constant, ConstantSize)) {
1212 auto *I = Builder.CreateMemSet(Loc, llvm::ConstantInt::get(CGM.Int8Ty, 0),
1213 SizeVal, isVolatile);
1214 if (IsAutoInit)
1215 I->addAnnotationMetadata("auto-init");
1217 bool valueAlreadyCorrect =
1218 constant->isNullValue() || isa<llvm::UndefValue>(constant);
1219 if (!valueAlreadyCorrect) {
1220 Loc = Loc.withElementType(Ty);
1221 emitStoresForInitAfterBZero(CGM, constant, Loc, isVolatile, Builder,
1222 IsAutoInit);
1224 return;
1227 // If the initializer is a repeated byte pattern, use memset.
1228 llvm::Value *Pattern =
1229 shouldUseMemSetToInitialize(constant, ConstantSize, CGM.getDataLayout());
1230 if (Pattern) {
1231 uint64_t Value = 0x00;
1232 if (!isa<llvm::UndefValue>(Pattern)) {
1233 const llvm::APInt &AP = cast<llvm::ConstantInt>(Pattern)->getValue();
1234 assert(AP.getBitWidth() <= 8);
1235 Value = AP.getLimitedValue();
1237 auto *I = Builder.CreateMemSet(
1238 Loc, llvm::ConstantInt::get(CGM.Int8Ty, Value), SizeVal, isVolatile);
1239 if (IsAutoInit)
1240 I->addAnnotationMetadata("auto-init");
1241 return;
1244 // If the initializer is small, use a handful of stores.
1245 if (shouldSplitConstantStore(CGM, ConstantSize)) {
1246 if (auto *STy = dyn_cast<llvm::StructType>(Ty)) {
1247 // FIXME: handle the case when STy != Loc.getElementType().
1248 if (STy == Loc.getElementType()) {
1249 for (unsigned i = 0; i != constant->getNumOperands(); i++) {
1250 Address EltPtr = Builder.CreateStructGEP(Loc, i);
1251 emitStoresForConstant(
1252 CGM, D, EltPtr, isVolatile, Builder,
1253 cast<llvm::Constant>(Builder.CreateExtractValue(constant, i)),
1254 IsAutoInit);
1256 return;
1258 } else if (auto *ATy = dyn_cast<llvm::ArrayType>(Ty)) {
1259 // FIXME: handle the case when ATy != Loc.getElementType().
1260 if (ATy == Loc.getElementType()) {
1261 for (unsigned i = 0; i != ATy->getNumElements(); i++) {
1262 Address EltPtr = Builder.CreateConstArrayGEP(Loc, i);
1263 emitStoresForConstant(
1264 CGM, D, EltPtr, isVolatile, Builder,
1265 cast<llvm::Constant>(Builder.CreateExtractValue(constant, i)),
1266 IsAutoInit);
1268 return;
1273 // Copy from a global.
1274 auto *I =
1275 Builder.CreateMemCpy(Loc,
1276 createUnnamedGlobalForMemcpyFrom(
1277 CGM, D, Builder, constant, Loc.getAlignment()),
1278 SizeVal, isVolatile);
1279 if (IsAutoInit)
1280 I->addAnnotationMetadata("auto-init");
1283 static void emitStoresForZeroInit(CodeGenModule &CGM, const VarDecl &D,
1284 Address Loc, bool isVolatile,
1285 CGBuilderTy &Builder) {
1286 llvm::Type *ElTy = Loc.getElementType();
1287 llvm::Constant *constant =
1288 constWithPadding(CGM, IsPattern::No, llvm::Constant::getNullValue(ElTy));
1289 emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant,
1290 /*IsAutoInit=*/true);
1293 static void emitStoresForPatternInit(CodeGenModule &CGM, const VarDecl &D,
1294 Address Loc, bool isVolatile,
1295 CGBuilderTy &Builder) {
1296 llvm::Type *ElTy = Loc.getElementType();
1297 llvm::Constant *constant = constWithPadding(
1298 CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));
1299 assert(!isa<llvm::UndefValue>(constant));
1300 emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant,
1301 /*IsAutoInit=*/true);
1304 static bool containsUndef(llvm::Constant *constant) {
1305 auto *Ty = constant->getType();
1306 if (isa<llvm::UndefValue>(constant))
1307 return true;
1308 if (Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy())
1309 for (llvm::Use &Op : constant->operands())
1310 if (containsUndef(cast<llvm::Constant>(Op)))
1311 return true;
1312 return false;
1315 static llvm::Constant *replaceUndef(CodeGenModule &CGM, IsPattern isPattern,
1316 llvm::Constant *constant) {
1317 auto *Ty = constant->getType();
1318 if (isa<llvm::UndefValue>(constant))
1319 return patternOrZeroFor(CGM, isPattern, Ty);
1320 if (!(Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()))
1321 return constant;
1322 if (!containsUndef(constant))
1323 return constant;
1324 llvm::SmallVector<llvm::Constant *, 8> Values(constant->getNumOperands());
1325 for (unsigned Op = 0, NumOp = constant->getNumOperands(); Op != NumOp; ++Op) {
1326 auto *OpValue = cast<llvm::Constant>(constant->getOperand(Op));
1327 Values[Op] = replaceUndef(CGM, isPattern, OpValue);
1329 if (Ty->isStructTy())
1330 return llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Values);
1331 if (Ty->isArrayTy())
1332 return llvm::ConstantArray::get(cast<llvm::ArrayType>(Ty), Values);
1333 assert(Ty->isVectorTy());
1334 return llvm::ConstantVector::get(Values);
1337 /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
1338 /// variable declaration with auto, register, or no storage class specifier.
1339 /// These turn into simple stack objects, or GlobalValues depending on target.
1340 void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
1341 AutoVarEmission emission = EmitAutoVarAlloca(D);
1342 EmitAutoVarInit(emission);
1343 EmitAutoVarCleanups(emission);
1346 /// Emit a lifetime.begin marker if some criteria are satisfied.
1347 /// \return a pointer to the temporary size Value if a marker was emitted, null
1348 /// otherwise
1349 llvm::Value *CodeGenFunction::EmitLifetimeStart(llvm::TypeSize Size,
1350 llvm::Value *Addr) {
1351 if (!ShouldEmitLifetimeMarkers)
1352 return nullptr;
1354 assert(Addr->getType()->getPointerAddressSpace() ==
1355 CGM.getDataLayout().getAllocaAddrSpace() &&
1356 "Pointer should be in alloca address space");
1357 llvm::Value *SizeV = llvm::ConstantInt::get(
1358 Int64Ty, Size.isScalable() ? -1 : Size.getFixedValue());
1359 llvm::CallInst *C =
1360 Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
1361 C->setDoesNotThrow();
1362 return SizeV;
1365 void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
1366 assert(Addr->getType()->getPointerAddressSpace() ==
1367 CGM.getDataLayout().getAllocaAddrSpace() &&
1368 "Pointer should be in alloca address space");
1369 llvm::CallInst *C =
1370 Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
1371 C->setDoesNotThrow();
1374 void CodeGenFunction::EmitAndRegisterVariableArrayDimensions(
1375 CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo) {
1376 // For each dimension stores its QualType and corresponding
1377 // size-expression Value.
1378 SmallVector<CodeGenFunction::VlaSizePair, 4> Dimensions;
1379 SmallVector<IdentifierInfo *, 4> VLAExprNames;
1381 // Break down the array into individual dimensions.
1382 QualType Type1D = D.getType();
1383 while (getContext().getAsVariableArrayType(Type1D)) {
1384 auto VlaSize = getVLAElements1D(Type1D);
1385 if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1386 Dimensions.emplace_back(C, Type1D.getUnqualifiedType());
1387 else {
1388 // Generate a locally unique name for the size expression.
1389 Twine Name = Twine("__vla_expr") + Twine(VLAExprCounter++);
1390 SmallString<12> Buffer;
1391 StringRef NameRef = Name.toStringRef(Buffer);
1392 auto &Ident = getContext().Idents.getOwn(NameRef);
1393 VLAExprNames.push_back(&Ident);
1394 auto SizeExprAddr =
1395 CreateDefaultAlignTempAlloca(VlaSize.NumElts->getType(), NameRef);
1396 Builder.CreateStore(VlaSize.NumElts, SizeExprAddr);
1397 Dimensions.emplace_back(SizeExprAddr.getPointer(),
1398 Type1D.getUnqualifiedType());
1400 Type1D = VlaSize.Type;
1403 if (!EmitDebugInfo)
1404 return;
1406 // Register each dimension's size-expression with a DILocalVariable,
1407 // so that it can be used by CGDebugInfo when instantiating a DISubrange
1408 // to describe this array.
1409 unsigned NameIdx = 0;
1410 for (auto &VlaSize : Dimensions) {
1411 llvm::Metadata *MD;
1412 if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1413 MD = llvm::ConstantAsMetadata::get(C);
1414 else {
1415 // Create an artificial VarDecl to generate debug info for.
1416 IdentifierInfo *NameIdent = VLAExprNames[NameIdx++];
1417 auto QT = getContext().getIntTypeForBitwidth(
1418 SizeTy->getScalarSizeInBits(), false);
1419 auto *ArtificialDecl = VarDecl::Create(
1420 getContext(), const_cast<DeclContext *>(D.getDeclContext()),
1421 D.getLocation(), D.getLocation(), NameIdent, QT,
1422 getContext().CreateTypeSourceInfo(QT), SC_Auto);
1423 ArtificialDecl->setImplicit();
1425 MD = DI->EmitDeclareOfAutoVariable(ArtificialDecl, VlaSize.NumElts,
1426 Builder);
1428 assert(MD && "No Size expression debug node created");
1429 DI->registerVLASizeExpression(VlaSize.Type, MD);
1433 /// EmitAutoVarAlloca - Emit the alloca and debug information for a
1434 /// local variable. Does not emit initialization or destruction.
1435 CodeGenFunction::AutoVarEmission
1436 CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
1437 QualType Ty = D.getType();
1438 assert(
1439 Ty.getAddressSpace() == LangAS::Default ||
1440 (Ty.getAddressSpace() == LangAS::opencl_private && getLangOpts().OpenCL));
1442 AutoVarEmission emission(D);
1444 bool isEscapingByRef = D.isEscapingByref();
1445 emission.IsEscapingByRef = isEscapingByRef;
1447 CharUnits alignment = getContext().getDeclAlign(&D);
1449 // If the type is variably-modified, emit all the VLA sizes for it.
1450 if (Ty->isVariablyModifiedType())
1451 EmitVariablyModifiedType(Ty);
1453 auto *DI = getDebugInfo();
1454 bool EmitDebugInfo = DI && CGM.getCodeGenOpts().hasReducedDebugInfo();
1456 Address address = Address::invalid();
1457 Address AllocaAddr = Address::invalid();
1458 Address OpenMPLocalAddr = Address::invalid();
1459 if (CGM.getLangOpts().OpenMPIRBuilder)
1460 OpenMPLocalAddr = OMPBuilderCBHelpers::getAddressOfLocalVariable(*this, &D);
1461 else
1462 OpenMPLocalAddr =
1463 getLangOpts().OpenMP
1464 ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
1465 : Address::invalid();
1467 bool NRVO = getLangOpts().ElideConstructors && D.isNRVOVariable();
1469 if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
1470 address = OpenMPLocalAddr;
1471 AllocaAddr = OpenMPLocalAddr;
1472 } else if (Ty->isConstantSizeType()) {
1473 // If this value is an array or struct with a statically determinable
1474 // constant initializer, there are optimizations we can do.
1476 // TODO: We should constant-evaluate the initializer of any variable,
1477 // as long as it is initialized by a constant expression. Currently,
1478 // isConstantInitializer produces wrong answers for structs with
1479 // reference or bitfield members, and a few other cases, and checking
1480 // for POD-ness protects us from some of these.
1481 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
1482 (D.isConstexpr() ||
1483 ((Ty.isPODType(getContext()) ||
1484 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
1485 D.getInit()->isConstantInitializer(getContext(), false)))) {
1487 // If the variable's a const type, and it's neither an NRVO
1488 // candidate nor a __block variable and has no mutable members,
1489 // emit it as a global instead.
1490 // Exception is if a variable is located in non-constant address space
1491 // in OpenCL.
1492 bool NeedsDtor =
1493 D.needsDestruction(getContext()) == QualType::DK_cxx_destructor;
1494 if ((!getLangOpts().OpenCL ||
1495 Ty.getAddressSpace() == LangAS::opencl_constant) &&
1496 (CGM.getCodeGenOpts().MergeAllConstants && !NRVO &&
1497 !isEscapingByRef &&
1498 Ty.isConstantStorage(getContext(), true, !NeedsDtor))) {
1499 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
1501 // Signal this condition to later callbacks.
1502 emission.Addr = Address::invalid();
1503 assert(emission.wasEmittedAsGlobal());
1504 return emission;
1507 // Otherwise, tell the initialization code that we're in this case.
1508 emission.IsConstantAggregate = true;
1511 // A normal fixed sized variable becomes an alloca in the entry block,
1512 // unless:
1513 // - it's an NRVO variable.
1514 // - we are compiling OpenMP and it's an OpenMP local variable.
1515 if (NRVO) {
1516 // The named return value optimization: allocate this variable in the
1517 // return slot, so that we can elide the copy when returning this
1518 // variable (C++0x [class.copy]p34).
1519 address = ReturnValue;
1520 AllocaAddr = ReturnValue;
1522 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1523 const auto *RD = RecordTy->getDecl();
1524 const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1525 if ((CXXRD && !CXXRD->hasTrivialDestructor()) ||
1526 RD->isNonTrivialToPrimitiveDestroy()) {
1527 // Create a flag that is used to indicate when the NRVO was applied
1528 // to this variable. Set it to zero to indicate that NRVO was not
1529 // applied.
1530 llvm::Value *Zero = Builder.getFalse();
1531 Address NRVOFlag =
1532 CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
1533 EnsureInsertPoint();
1534 Builder.CreateStore(Zero, NRVOFlag);
1536 // Record the NRVO flag for this variable.
1537 NRVOFlags[&D] = NRVOFlag.getPointer();
1538 emission.NRVOFlag = NRVOFlag.getPointer();
1541 } else {
1542 CharUnits allocaAlignment;
1543 llvm::Type *allocaTy;
1544 if (isEscapingByRef) {
1545 auto &byrefInfo = getBlockByrefInfo(&D);
1546 allocaTy = byrefInfo.Type;
1547 allocaAlignment = byrefInfo.ByrefAlignment;
1548 } else {
1549 allocaTy = ConvertTypeForMem(Ty);
1550 allocaAlignment = alignment;
1553 // Create the alloca. Note that we set the name separately from
1554 // building the instruction so that it's there even in no-asserts
1555 // builds.
1556 address = CreateTempAlloca(allocaTy, allocaAlignment, D.getName(),
1557 /*ArraySize=*/nullptr, &AllocaAddr);
1559 // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1560 // the catch parameter starts in the catchpad instruction, and we can't
1561 // insert code in those basic blocks.
1562 bool IsMSCatchParam =
1563 D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1565 // Emit a lifetime intrinsic if meaningful. There's no point in doing this
1566 // if we don't have a valid insertion point (?).
1567 if (HaveInsertPoint() && !IsMSCatchParam) {
1568 // If there's a jump into the lifetime of this variable, its lifetime
1569 // gets broken up into several regions in IR, which requires more work
1570 // to handle correctly. For now, just omit the intrinsics; this is a
1571 // rare case, and it's better to just be conservatively correct.
1572 // PR28267.
1574 // We have to do this in all language modes if there's a jump past the
1575 // declaration. We also have to do it in C if there's a jump to an
1576 // earlier point in the current block because non-VLA lifetimes begin as
1577 // soon as the containing block is entered, not when its variables
1578 // actually come into scope; suppressing the lifetime annotations
1579 // completely in this case is unnecessarily pessimistic, but again, this
1580 // is rare.
1581 if (!Bypasses.IsBypassed(&D) &&
1582 !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
1583 llvm::TypeSize Size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
1584 emission.SizeForLifetimeMarkers =
1585 EmitLifetimeStart(Size, AllocaAddr.getPointer());
1587 } else {
1588 assert(!emission.useLifetimeMarkers());
1591 } else {
1592 EnsureInsertPoint();
1594 // Delayed globalization for variable length declarations. This ensures that
1595 // the expression representing the length has been emitted and can be used
1596 // by the definition of the VLA. Since this is an escaped declaration, in
1597 // OpenMP we have to use a call to __kmpc_alloc_shared(). The matching
1598 // deallocation call to __kmpc_free_shared() is emitted later.
1599 bool VarAllocated = false;
1600 if (getLangOpts().OpenMPIsTargetDevice) {
1601 auto &RT = CGM.getOpenMPRuntime();
1602 if (RT.isDelayedVariableLengthDecl(*this, &D)) {
1603 // Emit call to __kmpc_alloc_shared() instead of the alloca.
1604 std::pair<llvm::Value *, llvm::Value *> AddrSizePair =
1605 RT.getKmpcAllocShared(*this, &D);
1607 // Save the address of the allocation:
1608 LValue Base = MakeAddrLValue(AddrSizePair.first, D.getType(),
1609 CGM.getContext().getDeclAlign(&D),
1610 AlignmentSource::Decl);
1611 address = Base.getAddress(*this);
1613 // Push a cleanup block to emit the call to __kmpc_free_shared in the
1614 // appropriate location at the end of the scope of the
1615 // __kmpc_alloc_shared functions:
1616 pushKmpcAllocFree(NormalCleanup, AddrSizePair);
1618 // Mark variable as allocated:
1619 VarAllocated = true;
1623 if (!VarAllocated) {
1624 if (!DidCallStackSave) {
1625 // Save the stack.
1626 Address Stack =
1627 CreateDefaultAlignTempAlloca(AllocaInt8PtrTy, "saved_stack");
1629 llvm::Value *V = Builder.CreateStackSave();
1630 assert(V->getType() == AllocaInt8PtrTy);
1631 Builder.CreateStore(V, Stack);
1633 DidCallStackSave = true;
1635 // Push a cleanup block and restore the stack there.
1636 // FIXME: in general circumstances, this should be an EH cleanup.
1637 pushStackRestore(NormalCleanup, Stack);
1640 auto VlaSize = getVLASize(Ty);
1641 llvm::Type *llvmTy = ConvertTypeForMem(VlaSize.Type);
1643 // Allocate memory for the array.
1644 address = CreateTempAlloca(llvmTy, alignment, "vla", VlaSize.NumElts,
1645 &AllocaAddr);
1648 // If we have debug info enabled, properly describe the VLA dimensions for
1649 // this type by registering the vla size expression for each of the
1650 // dimensions.
1651 EmitAndRegisterVariableArrayDimensions(DI, D, EmitDebugInfo);
1654 setAddrOfLocalVar(&D, address);
1655 emission.Addr = address;
1656 emission.AllocaAddr = AllocaAddr;
1658 // Emit debug info for local var declaration.
1659 if (EmitDebugInfo && HaveInsertPoint()) {
1660 Address DebugAddr = address;
1661 bool UsePointerValue = NRVO && ReturnValuePointer.isValid();
1662 DI->setLocation(D.getLocation());
1664 // If NRVO, use a pointer to the return address.
1665 if (UsePointerValue) {
1666 DebugAddr = ReturnValuePointer;
1667 AllocaAddr = ReturnValuePointer;
1669 (void)DI->EmitDeclareOfAutoVariable(&D, AllocaAddr.getPointer(), Builder,
1670 UsePointerValue);
1673 if (D.hasAttr<AnnotateAttr>() && HaveInsertPoint())
1674 EmitVarAnnotations(&D, address.getPointer());
1676 // Make sure we call @llvm.lifetime.end.
1677 if (emission.useLifetimeMarkers())
1678 EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
1679 emission.getOriginalAllocatedAddress(),
1680 emission.getSizeForLifetimeMarkers());
1682 return emission;
1685 static bool isCapturedBy(const VarDecl &, const Expr *);
1687 /// Determines whether the given __block variable is potentially
1688 /// captured by the given statement.
1689 static bool isCapturedBy(const VarDecl &Var, const Stmt *S) {
1690 if (const Expr *E = dyn_cast<Expr>(S))
1691 return isCapturedBy(Var, E);
1692 for (const Stmt *SubStmt : S->children())
1693 if (isCapturedBy(Var, SubStmt))
1694 return true;
1695 return false;
1698 /// Determines whether the given __block variable is potentially
1699 /// captured by the given expression.
1700 static bool isCapturedBy(const VarDecl &Var, const Expr *E) {
1701 // Skip the most common kinds of expressions that make
1702 // hierarchy-walking expensive.
1703 E = E->IgnoreParenCasts();
1705 if (const BlockExpr *BE = dyn_cast<BlockExpr>(E)) {
1706 const BlockDecl *Block = BE->getBlockDecl();
1707 for (const auto &I : Block->captures()) {
1708 if (I.getVariable() == &Var)
1709 return true;
1712 // No need to walk into the subexpressions.
1713 return false;
1716 if (const StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
1717 const CompoundStmt *CS = SE->getSubStmt();
1718 for (const auto *BI : CS->body())
1719 if (const auto *BIE = dyn_cast<Expr>(BI)) {
1720 if (isCapturedBy(Var, BIE))
1721 return true;
1723 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
1724 // special case declarations
1725 for (const auto *I : DS->decls()) {
1726 if (const auto *VD = dyn_cast<VarDecl>((I))) {
1727 const Expr *Init = VD->getInit();
1728 if (Init && isCapturedBy(Var, Init))
1729 return true;
1733 else
1734 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1735 // Later, provide code to poke into statements for capture analysis.
1736 return true;
1737 return false;
1740 for (const Stmt *SubStmt : E->children())
1741 if (isCapturedBy(Var, SubStmt))
1742 return true;
1744 return false;
1747 /// Determine whether the given initializer is trivial in the sense
1748 /// that it requires no code to be generated.
1749 bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
1750 if (!Init)
1751 return true;
1753 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1754 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1755 if (Constructor->isTrivial() &&
1756 Constructor->isDefaultConstructor() &&
1757 !Construct->requiresZeroInitialization())
1758 return true;
1760 return false;
1763 void CodeGenFunction::emitZeroOrPatternForAutoVarInit(QualType type,
1764 const VarDecl &D,
1765 Address Loc) {
1766 auto trivialAutoVarInit = getContext().getLangOpts().getTrivialAutoVarInit();
1767 CharUnits Size = getContext().getTypeSizeInChars(type);
1768 bool isVolatile = type.isVolatileQualified();
1769 if (!Size.isZero()) {
1770 switch (trivialAutoVarInit) {
1771 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
1772 llvm_unreachable("Uninitialized handled by caller");
1773 case LangOptions::TrivialAutoVarInitKind::Zero:
1774 if (CGM.stopAutoInit())
1775 return;
1776 emitStoresForZeroInit(CGM, D, Loc, isVolatile, Builder);
1777 break;
1778 case LangOptions::TrivialAutoVarInitKind::Pattern:
1779 if (CGM.stopAutoInit())
1780 return;
1781 emitStoresForPatternInit(CGM, D, Loc, isVolatile, Builder);
1782 break;
1784 return;
1787 // VLAs look zero-sized to getTypeInfo. We can't emit constant stores to
1788 // them, so emit a memcpy with the VLA size to initialize each element.
1789 // Technically zero-sized or negative-sized VLAs are undefined, and UBSan
1790 // will catch that code, but there exists code which generates zero-sized
1791 // VLAs. Be nice and initialize whatever they requested.
1792 const auto *VlaType = getContext().getAsVariableArrayType(type);
1793 if (!VlaType)
1794 return;
1795 auto VlaSize = getVLASize(VlaType);
1796 auto SizeVal = VlaSize.NumElts;
1797 CharUnits EltSize = getContext().getTypeSizeInChars(VlaSize.Type);
1798 switch (trivialAutoVarInit) {
1799 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
1800 llvm_unreachable("Uninitialized handled by caller");
1802 case LangOptions::TrivialAutoVarInitKind::Zero: {
1803 if (CGM.stopAutoInit())
1804 return;
1805 if (!EltSize.isOne())
1806 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
1807 auto *I = Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0),
1808 SizeVal, isVolatile);
1809 I->addAnnotationMetadata("auto-init");
1810 break;
1813 case LangOptions::TrivialAutoVarInitKind::Pattern: {
1814 if (CGM.stopAutoInit())
1815 return;
1816 llvm::Type *ElTy = Loc.getElementType();
1817 llvm::Constant *Constant = constWithPadding(
1818 CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));
1819 CharUnits ConstantAlign = getContext().getTypeAlignInChars(VlaSize.Type);
1820 llvm::BasicBlock *SetupBB = createBasicBlock("vla-setup.loop");
1821 llvm::BasicBlock *LoopBB = createBasicBlock("vla-init.loop");
1822 llvm::BasicBlock *ContBB = createBasicBlock("vla-init.cont");
1823 llvm::Value *IsZeroSizedVLA = Builder.CreateICmpEQ(
1824 SizeVal, llvm::ConstantInt::get(SizeVal->getType(), 0),
1825 "vla.iszerosized");
1826 Builder.CreateCondBr(IsZeroSizedVLA, ContBB, SetupBB);
1827 EmitBlock(SetupBB);
1828 if (!EltSize.isOne())
1829 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
1830 llvm::Value *BaseSizeInChars =
1831 llvm::ConstantInt::get(IntPtrTy, EltSize.getQuantity());
1832 Address Begin = Loc.withElementType(Int8Ty);
1833 llvm::Value *End = Builder.CreateInBoundsGEP(
1834 Begin.getElementType(), Begin.getPointer(), SizeVal, "vla.end");
1835 llvm::BasicBlock *OriginBB = Builder.GetInsertBlock();
1836 EmitBlock(LoopBB);
1837 llvm::PHINode *Cur = Builder.CreatePHI(Begin.getType(), 2, "vla.cur");
1838 Cur->addIncoming(Begin.getPointer(), OriginBB);
1839 CharUnits CurAlign = Loc.getAlignment().alignmentOfArrayElement(EltSize);
1840 auto *I =
1841 Builder.CreateMemCpy(Address(Cur, Int8Ty, CurAlign),
1842 createUnnamedGlobalForMemcpyFrom(
1843 CGM, D, Builder, Constant, ConstantAlign),
1844 BaseSizeInChars, isVolatile);
1845 I->addAnnotationMetadata("auto-init");
1846 llvm::Value *Next =
1847 Builder.CreateInBoundsGEP(Int8Ty, Cur, BaseSizeInChars, "vla.next");
1848 llvm::Value *Done = Builder.CreateICmpEQ(Next, End, "vla-init.isdone");
1849 Builder.CreateCondBr(Done, ContBB, LoopBB);
1850 Cur->addIncoming(Next, LoopBB);
1851 EmitBlock(ContBB);
1852 } break;
1856 void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
1857 assert(emission.Variable && "emission was not valid!");
1859 // If this was emitted as a global constant, we're done.
1860 if (emission.wasEmittedAsGlobal()) return;
1862 const VarDecl &D = *emission.Variable;
1863 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
1864 QualType type = D.getType();
1866 // If this local has an initializer, emit it now.
1867 const Expr *Init = D.getInit();
1869 // If we are at an unreachable point, we don't need to emit the initializer
1870 // unless it contains a label.
1871 if (!HaveInsertPoint()) {
1872 if (!Init || !ContainsLabel(Init)) return;
1873 EnsureInsertPoint();
1876 // Initialize the structure of a __block variable.
1877 if (emission.IsEscapingByRef)
1878 emitByrefStructureInit(emission);
1880 // Initialize the variable here if it doesn't have a initializer and it is a
1881 // C struct that is non-trivial to initialize or an array containing such a
1882 // struct.
1883 if (!Init &&
1884 type.isNonTrivialToPrimitiveDefaultInitialize() ==
1885 QualType::PDIK_Struct) {
1886 LValue Dst = MakeAddrLValue(emission.getAllocatedAddress(), type);
1887 if (emission.IsEscapingByRef)
1888 drillIntoBlockVariable(*this, Dst, &D);
1889 defaultInitNonTrivialCStructVar(Dst);
1890 return;
1893 // Check whether this is a byref variable that's potentially
1894 // captured and moved by its own initializer. If so, we'll need to
1895 // emit the initializer first, then copy into the variable.
1896 bool capturedByInit =
1897 Init && emission.IsEscapingByRef && isCapturedBy(D, Init);
1899 bool locIsByrefHeader = !capturedByInit;
1900 const Address Loc =
1901 locIsByrefHeader ? emission.getObjectAddress(*this) : emission.Addr;
1903 // Note: constexpr already initializes everything correctly.
1904 LangOptions::TrivialAutoVarInitKind trivialAutoVarInit =
1905 (D.isConstexpr()
1906 ? LangOptions::TrivialAutoVarInitKind::Uninitialized
1907 : (D.getAttr<UninitializedAttr>()
1908 ? LangOptions::TrivialAutoVarInitKind::Uninitialized
1909 : getContext().getLangOpts().getTrivialAutoVarInit()));
1911 auto initializeWhatIsTechnicallyUninitialized = [&](Address Loc) {
1912 if (trivialAutoVarInit ==
1913 LangOptions::TrivialAutoVarInitKind::Uninitialized)
1914 return;
1916 // Only initialize a __block's storage: we always initialize the header.
1917 if (emission.IsEscapingByRef && !locIsByrefHeader)
1918 Loc = emitBlockByrefAddress(Loc, &D, /*follow=*/false);
1920 return emitZeroOrPatternForAutoVarInit(type, D, Loc);
1923 if (isTrivialInitializer(Init))
1924 return initializeWhatIsTechnicallyUninitialized(Loc);
1926 llvm::Constant *constant = nullptr;
1927 if (emission.IsConstantAggregate ||
1928 D.mightBeUsableInConstantExpressions(getContext())) {
1929 assert(!capturedByInit && "constant init contains a capturing block?");
1930 constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(D);
1931 if (constant && !constant->isZeroValue() &&
1932 (trivialAutoVarInit !=
1933 LangOptions::TrivialAutoVarInitKind::Uninitialized)) {
1934 IsPattern isPattern =
1935 (trivialAutoVarInit == LangOptions::TrivialAutoVarInitKind::Pattern)
1936 ? IsPattern::Yes
1937 : IsPattern::No;
1938 // C guarantees that brace-init with fewer initializers than members in
1939 // the aggregate will initialize the rest of the aggregate as-if it were
1940 // static initialization. In turn static initialization guarantees that
1941 // padding is initialized to zero bits. We could instead pattern-init if D
1942 // has any ImplicitValueInitExpr, but that seems to be unintuitive
1943 // behavior.
1944 constant = constWithPadding(CGM, IsPattern::No,
1945 replaceUndef(CGM, isPattern, constant));
1949 if (!constant) {
1950 initializeWhatIsTechnicallyUninitialized(Loc);
1951 LValue lv = MakeAddrLValue(Loc, type);
1952 lv.setNonGC(true);
1953 return EmitExprAsInit(Init, &D, lv, capturedByInit);
1956 if (!emission.IsConstantAggregate) {
1957 // For simple scalar/complex initialization, store the value directly.
1958 LValue lv = MakeAddrLValue(Loc, type);
1959 lv.setNonGC(true);
1960 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1963 emitStoresForConstant(CGM, D, Loc.withElementType(CGM.Int8Ty),
1964 type.isVolatileQualified(), Builder, constant,
1965 /*IsAutoInit=*/false);
1968 /// Emit an expression as an initializer for an object (variable, field, etc.)
1969 /// at the given location. The expression is not necessarily the normal
1970 /// initializer for the object, and the address is not necessarily
1971 /// its normal location.
1973 /// \param init the initializing expression
1974 /// \param D the object to act as if we're initializing
1975 /// \param lvalue the lvalue to initialize
1976 /// \param capturedByInit true if \p D is a __block variable
1977 /// whose address is potentially changed by the initializer
1978 void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
1979 LValue lvalue, bool capturedByInit) {
1980 QualType type = D->getType();
1982 if (type->isReferenceType()) {
1983 RValue rvalue = EmitReferenceBindingToExpr(init);
1984 if (capturedByInit)
1985 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1986 EmitStoreThroughLValue(rvalue, lvalue, true);
1987 return;
1989 switch (getEvaluationKind(type)) {
1990 case TEK_Scalar:
1991 EmitScalarInit(init, D, lvalue, capturedByInit);
1992 return;
1993 case TEK_Complex: {
1994 ComplexPairTy complex = EmitComplexExpr(init);
1995 if (capturedByInit)
1996 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1997 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
1998 return;
2000 case TEK_Aggregate:
2001 if (type->isAtomicType()) {
2002 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
2003 } else {
2004 AggValueSlot::Overlap_t Overlap = AggValueSlot::MayOverlap;
2005 if (isa<VarDecl>(D))
2006 Overlap = AggValueSlot::DoesNotOverlap;
2007 else if (auto *FD = dyn_cast<FieldDecl>(D))
2008 Overlap = getOverlapForFieldInit(FD);
2009 // TODO: how can we delay here if D is captured by its initializer?
2010 EmitAggExpr(init, AggValueSlot::forLValue(
2011 lvalue, *this, AggValueSlot::IsDestructed,
2012 AggValueSlot::DoesNotNeedGCBarriers,
2013 AggValueSlot::IsNotAliased, Overlap));
2015 return;
2017 llvm_unreachable("bad evaluation kind");
2020 /// Enter a destroy cleanup for the given local variable.
2021 void CodeGenFunction::emitAutoVarTypeCleanup(
2022 const CodeGenFunction::AutoVarEmission &emission,
2023 QualType::DestructionKind dtorKind) {
2024 assert(dtorKind != QualType::DK_none);
2026 // Note that for __block variables, we want to destroy the
2027 // original stack object, not the possibly forwarded object.
2028 Address addr = emission.getObjectAddress(*this);
2030 const VarDecl *var = emission.Variable;
2031 QualType type = var->getType();
2033 CleanupKind cleanupKind = NormalAndEHCleanup;
2034 CodeGenFunction::Destroyer *destroyer = nullptr;
2036 switch (dtorKind) {
2037 case QualType::DK_none:
2038 llvm_unreachable("no cleanup for trivially-destructible variable");
2040 case QualType::DK_cxx_destructor:
2041 // If there's an NRVO flag on the emission, we need a different
2042 // cleanup.
2043 if (emission.NRVOFlag) {
2044 assert(!type->isArrayType());
2045 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
2046 EHStack.pushCleanup<DestroyNRVOVariableCXX>(cleanupKind, addr, type, dtor,
2047 emission.NRVOFlag);
2048 return;
2050 break;
2052 case QualType::DK_objc_strong_lifetime:
2053 // Suppress cleanups for pseudo-strong variables.
2054 if (var->isARCPseudoStrong()) return;
2056 // Otherwise, consider whether to use an EH cleanup or not.
2057 cleanupKind = getARCCleanupKind();
2059 // Use the imprecise destroyer by default.
2060 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
2061 destroyer = CodeGenFunction::destroyARCStrongImprecise;
2062 break;
2064 case QualType::DK_objc_weak_lifetime:
2065 break;
2067 case QualType::DK_nontrivial_c_struct:
2068 destroyer = CodeGenFunction::destroyNonTrivialCStruct;
2069 if (emission.NRVOFlag) {
2070 assert(!type->isArrayType());
2071 EHStack.pushCleanup<DestroyNRVOVariableC>(cleanupKind, addr,
2072 emission.NRVOFlag, type);
2073 return;
2075 break;
2078 // If we haven't chosen a more specific destroyer, use the default.
2079 if (!destroyer) destroyer = getDestroyer(dtorKind);
2081 // Use an EH cleanup in array destructors iff the destructor itself
2082 // is being pushed as an EH cleanup.
2083 bool useEHCleanup = (cleanupKind & EHCleanup);
2084 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
2085 useEHCleanup);
2088 void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
2089 assert(emission.Variable && "emission was not valid!");
2091 // If this was emitted as a global constant, we're done.
2092 if (emission.wasEmittedAsGlobal()) return;
2094 // If we don't have an insertion point, we're done. Sema prevents
2095 // us from jumping into any of these scopes anyway.
2096 if (!HaveInsertPoint()) return;
2098 const VarDecl &D = *emission.Variable;
2100 // Check the type for a cleanup.
2101 if (QualType::DestructionKind dtorKind = D.needsDestruction(getContext()))
2102 emitAutoVarTypeCleanup(emission, dtorKind);
2104 // In GC mode, honor objc_precise_lifetime.
2105 if (getLangOpts().getGC() != LangOptions::NonGC &&
2106 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
2107 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
2110 // Handle the cleanup attribute.
2111 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
2112 const FunctionDecl *FD = CA->getFunctionDecl();
2114 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
2115 assert(F && "Could not find function!");
2117 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
2118 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
2121 // If this is a block variable, call _Block_object_destroy
2122 // (on the unforwarded address). Don't enter this cleanup if we're in pure-GC
2123 // mode.
2124 if (emission.IsEscapingByRef &&
2125 CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
2126 BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
2127 if (emission.Variable->getType().isObjCGCWeak())
2128 Flags |= BLOCK_FIELD_IS_WEAK;
2129 enterByrefCleanup(NormalAndEHCleanup, emission.Addr, Flags,
2130 /*LoadBlockVarAddr*/ false,
2131 cxxDestructorCanThrow(emission.Variable->getType()));
2135 CodeGenFunction::Destroyer *
2136 CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
2137 switch (kind) {
2138 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
2139 case QualType::DK_cxx_destructor:
2140 return destroyCXXObject;
2141 case QualType::DK_objc_strong_lifetime:
2142 return destroyARCStrongPrecise;
2143 case QualType::DK_objc_weak_lifetime:
2144 return destroyARCWeak;
2145 case QualType::DK_nontrivial_c_struct:
2146 return destroyNonTrivialCStruct;
2148 llvm_unreachable("Unknown DestructionKind");
2151 /// pushEHDestroy - Push the standard destructor for the given type as
2152 /// an EH-only cleanup.
2153 void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
2154 Address addr, QualType type) {
2155 assert(dtorKind && "cannot push destructor for trivial type");
2156 assert(needsEHCleanup(dtorKind));
2158 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
2161 /// pushDestroy - Push the standard destructor for the given type as
2162 /// at least a normal cleanup.
2163 void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
2164 Address addr, QualType type) {
2165 assert(dtorKind && "cannot push destructor for trivial type");
2167 CleanupKind cleanupKind = getCleanupKind(dtorKind);
2168 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
2169 cleanupKind & EHCleanup);
2172 void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
2173 QualType type, Destroyer *destroyer,
2174 bool useEHCleanupForArray) {
2175 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
2176 destroyer, useEHCleanupForArray);
2179 void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
2180 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
2183 void CodeGenFunction::pushKmpcAllocFree(
2184 CleanupKind Kind, std::pair<llvm::Value *, llvm::Value *> AddrSizePair) {
2185 EHStack.pushCleanup<KmpcAllocFree>(Kind, AddrSizePair);
2188 void CodeGenFunction::pushLifetimeExtendedDestroy(CleanupKind cleanupKind,
2189 Address addr, QualType type,
2190 Destroyer *destroyer,
2191 bool useEHCleanupForArray) {
2192 // If we're not in a conditional branch, we don't need to bother generating a
2193 // conditional cleanup.
2194 if (!isInConditionalBranch()) {
2195 // Push an EH-only cleanup for the object now.
2196 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
2197 // around in case a temporary's destructor throws an exception.
2198 if (cleanupKind & EHCleanup)
2199 EHStack.pushCleanup<DestroyObject>(
2200 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
2201 destroyer, useEHCleanupForArray);
2203 return pushCleanupAfterFullExprWithActiveFlag<DestroyObject>(
2204 cleanupKind, Address::invalid(), addr, type, destroyer, useEHCleanupForArray);
2207 // Otherwise, we should only destroy the object if it's been initialized.
2208 // Re-use the active flag and saved address across both the EH and end of
2209 // scope cleanups.
2211 using SavedType = typename DominatingValue<Address>::saved_type;
2212 using ConditionalCleanupType =
2213 EHScopeStack::ConditionalCleanup<DestroyObject, Address, QualType,
2214 Destroyer *, bool>;
2216 Address ActiveFlag = createCleanupActiveFlag();
2217 SavedType SavedAddr = saveValueInCond(addr);
2219 if (cleanupKind & EHCleanup) {
2220 EHStack.pushCleanup<ConditionalCleanupType>(
2221 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), SavedAddr, type,
2222 destroyer, useEHCleanupForArray);
2223 initFullExprCleanupWithFlag(ActiveFlag);
2226 pushCleanupAfterFullExprWithActiveFlag<ConditionalCleanupType>(
2227 cleanupKind, ActiveFlag, SavedAddr, type, destroyer,
2228 useEHCleanupForArray);
2231 /// emitDestroy - Immediately perform the destruction of the given
2232 /// object.
2234 /// \param addr - the address of the object; a type*
2235 /// \param type - the type of the object; if an array type, all
2236 /// objects are destroyed in reverse order
2237 /// \param destroyer - the function to call to destroy individual
2238 /// elements
2239 /// \param useEHCleanupForArray - whether an EH cleanup should be
2240 /// used when destroying array elements, in case one of the
2241 /// destructions throws an exception
2242 void CodeGenFunction::emitDestroy(Address addr, QualType type,
2243 Destroyer *destroyer,
2244 bool useEHCleanupForArray) {
2245 const ArrayType *arrayType = getContext().getAsArrayType(type);
2246 if (!arrayType)
2247 return destroyer(*this, addr, type);
2249 llvm::Value *length = emitArrayLength(arrayType, type, addr);
2251 CharUnits elementAlign =
2252 addr.getAlignment()
2253 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
2255 // Normally we have to check whether the array is zero-length.
2256 bool checkZeroLength = true;
2258 // But if the array length is constant, we can suppress that.
2259 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
2260 // ...and if it's constant zero, we can just skip the entire thing.
2261 if (constLength->isZero()) return;
2262 checkZeroLength = false;
2265 llvm::Value *begin = addr.getPointer();
2266 llvm::Value *end =
2267 Builder.CreateInBoundsGEP(addr.getElementType(), begin, length);
2268 emitArrayDestroy(begin, end, type, elementAlign, destroyer,
2269 checkZeroLength, useEHCleanupForArray);
2272 /// emitArrayDestroy - Destroys all the elements of the given array,
2273 /// beginning from last to first. The array cannot be zero-length.
2275 /// \param begin - a type* denoting the first element of the array
2276 /// \param end - a type* denoting one past the end of the array
2277 /// \param elementType - the element type of the array
2278 /// \param destroyer - the function to call to destroy elements
2279 /// \param useEHCleanup - whether to push an EH cleanup to destroy
2280 /// the remaining elements in case the destruction of a single
2281 /// element throws
2282 void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
2283 llvm::Value *end,
2284 QualType elementType,
2285 CharUnits elementAlign,
2286 Destroyer *destroyer,
2287 bool checkZeroLength,
2288 bool useEHCleanup) {
2289 assert(!elementType->isArrayType());
2291 // The basic structure here is a do-while loop, because we don't
2292 // need to check for the zero-element case.
2293 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
2294 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
2296 if (checkZeroLength) {
2297 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
2298 "arraydestroy.isempty");
2299 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
2302 // Enter the loop body, making that address the current address.
2303 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
2304 EmitBlock(bodyBB);
2305 llvm::PHINode *elementPast =
2306 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
2307 elementPast->addIncoming(end, entryBB);
2309 // Shift the address back by one element.
2310 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
2311 llvm::Type *llvmElementType = ConvertTypeForMem(elementType);
2312 llvm::Value *element = Builder.CreateInBoundsGEP(
2313 llvmElementType, elementPast, negativeOne, "arraydestroy.element");
2315 if (useEHCleanup)
2316 pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
2317 destroyer);
2319 // Perform the actual destruction there.
2320 destroyer(*this, Address(element, llvmElementType, elementAlign),
2321 elementType);
2323 if (useEHCleanup)
2324 PopCleanupBlock();
2326 // Check whether we've reached the end.
2327 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
2328 Builder.CreateCondBr(done, doneBB, bodyBB);
2329 elementPast->addIncoming(element, Builder.GetInsertBlock());
2331 // Done.
2332 EmitBlock(doneBB);
2335 /// Perform partial array destruction as if in an EH cleanup. Unlike
2336 /// emitArrayDestroy, the element type here may still be an array type.
2337 static void emitPartialArrayDestroy(CodeGenFunction &CGF,
2338 llvm::Value *begin, llvm::Value *end,
2339 QualType type, CharUnits elementAlign,
2340 CodeGenFunction::Destroyer *destroyer) {
2341 llvm::Type *elemTy = CGF.ConvertTypeForMem(type);
2343 // If the element type is itself an array, drill down.
2344 unsigned arrayDepth = 0;
2345 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
2346 // VLAs don't require a GEP index to walk into.
2347 if (!isa<VariableArrayType>(arrayType))
2348 arrayDepth++;
2349 type = arrayType->getElementType();
2352 if (arrayDepth) {
2353 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
2355 SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
2356 begin = CGF.Builder.CreateInBoundsGEP(
2357 elemTy, begin, gepIndices, "pad.arraybegin");
2358 end = CGF.Builder.CreateInBoundsGEP(
2359 elemTy, end, gepIndices, "pad.arrayend");
2362 // Destroy the array. We don't ever need an EH cleanup because we
2363 // assume that we're in an EH cleanup ourselves, so a throwing
2364 // destructor causes an immediate terminate.
2365 CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
2366 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
2369 namespace {
2370 /// RegularPartialArrayDestroy - a cleanup which performs a partial
2371 /// array destroy where the end pointer is regularly determined and
2372 /// does not need to be loaded from a local.
2373 class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
2374 llvm::Value *ArrayBegin;
2375 llvm::Value *ArrayEnd;
2376 QualType ElementType;
2377 CodeGenFunction::Destroyer *Destroyer;
2378 CharUnits ElementAlign;
2379 public:
2380 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
2381 QualType elementType, CharUnits elementAlign,
2382 CodeGenFunction::Destroyer *destroyer)
2383 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
2384 ElementType(elementType), Destroyer(destroyer),
2385 ElementAlign(elementAlign) {}
2387 void Emit(CodeGenFunction &CGF, Flags flags) override {
2388 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
2389 ElementType, ElementAlign, Destroyer);
2393 /// IrregularPartialArrayDestroy - a cleanup which performs a
2394 /// partial array destroy where the end pointer is irregularly
2395 /// determined and must be loaded from a local.
2396 class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
2397 llvm::Value *ArrayBegin;
2398 Address ArrayEndPointer;
2399 QualType ElementType;
2400 CodeGenFunction::Destroyer *Destroyer;
2401 CharUnits ElementAlign;
2402 public:
2403 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
2404 Address arrayEndPointer,
2405 QualType elementType,
2406 CharUnits elementAlign,
2407 CodeGenFunction::Destroyer *destroyer)
2408 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
2409 ElementType(elementType), Destroyer(destroyer),
2410 ElementAlign(elementAlign) {}
2412 void Emit(CodeGenFunction &CGF, Flags flags) override {
2413 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
2414 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
2415 ElementType, ElementAlign, Destroyer);
2418 } // end anonymous namespace
2420 /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
2421 /// already-constructed elements of the given array. The cleanup
2422 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
2424 /// \param elementType - the immediate element type of the array;
2425 /// possibly still an array type
2426 void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
2427 Address arrayEndPointer,
2428 QualType elementType,
2429 CharUnits elementAlign,
2430 Destroyer *destroyer) {
2431 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
2432 arrayBegin, arrayEndPointer,
2433 elementType, elementAlign,
2434 destroyer);
2437 /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
2438 /// already-constructed elements of the given array. The cleanup
2439 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
2441 /// \param elementType - the immediate element type of the array;
2442 /// possibly still an array type
2443 void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
2444 llvm::Value *arrayEnd,
2445 QualType elementType,
2446 CharUnits elementAlign,
2447 Destroyer *destroyer) {
2448 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
2449 arrayBegin, arrayEnd,
2450 elementType, elementAlign,
2451 destroyer);
2454 /// Lazily declare the @llvm.lifetime.start intrinsic.
2455 llvm::Function *CodeGenModule::getLLVMLifetimeStartFn() {
2456 if (LifetimeStartFn)
2457 return LifetimeStartFn;
2458 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
2459 llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);
2460 return LifetimeStartFn;
2463 /// Lazily declare the @llvm.lifetime.end intrinsic.
2464 llvm::Function *CodeGenModule::getLLVMLifetimeEndFn() {
2465 if (LifetimeEndFn)
2466 return LifetimeEndFn;
2467 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
2468 llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);
2469 return LifetimeEndFn;
2472 namespace {
2473 /// A cleanup to perform a release of an object at the end of a
2474 /// function. This is used to balance out the incoming +1 of a
2475 /// ns_consumed argument when we can't reasonably do that just by
2476 /// not doing the initial retain for a __block argument.
2477 struct ConsumeARCParameter final : EHScopeStack::Cleanup {
2478 ConsumeARCParameter(llvm::Value *param,
2479 ARCPreciseLifetime_t precise)
2480 : Param(param), Precise(precise) {}
2482 llvm::Value *Param;
2483 ARCPreciseLifetime_t Precise;
2485 void Emit(CodeGenFunction &CGF, Flags flags) override {
2486 CGF.EmitARCRelease(Param, Precise);
2489 } // end anonymous namespace
2491 /// Emit an alloca (or GlobalValue depending on target)
2492 /// for the specified parameter and set up LocalDeclMap.
2493 void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
2494 unsigned ArgNo) {
2495 bool NoDebugInfo = false;
2496 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
2497 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
2498 "Invalid argument to EmitParmDecl");
2500 // Set the name of the parameter's initial value to make IR easier to
2501 // read. Don't modify the names of globals.
2502 if (!isa<llvm::GlobalValue>(Arg.getAnyValue()))
2503 Arg.getAnyValue()->setName(D.getName());
2505 QualType Ty = D.getType();
2507 // Use better IR generation for certain implicit parameters.
2508 if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
2509 // The only implicit argument a block has is its literal.
2510 // This may be passed as an inalloca'ed value on Windows x86.
2511 if (BlockInfo) {
2512 llvm::Value *V = Arg.isIndirect()
2513 ? Builder.CreateLoad(Arg.getIndirectAddress())
2514 : Arg.getDirectValue();
2515 setBlockContextParameter(IPD, ArgNo, V);
2516 return;
2518 // Suppressing debug info for ThreadPrivateVar parameters, else it hides
2519 // debug info of TLS variables.
2520 NoDebugInfo =
2521 (IPD->getParameterKind() == ImplicitParamDecl::ThreadPrivateVar);
2524 Address DeclPtr = Address::invalid();
2525 Address AllocaPtr = Address::invalid();
2526 bool DoStore = false;
2527 bool IsScalar = hasScalarEvaluationKind(Ty);
2528 bool UseIndirectDebugAddress = false;
2530 // If we already have a pointer to the argument, reuse the input pointer.
2531 if (Arg.isIndirect()) {
2532 DeclPtr = Arg.getIndirectAddress();
2533 DeclPtr = DeclPtr.withElementType(ConvertTypeForMem(Ty));
2534 // Indirect argument is in alloca address space, which may be different
2535 // from the default address space.
2536 auto AllocaAS = CGM.getASTAllocaAddressSpace();
2537 auto *V = DeclPtr.getPointer();
2538 AllocaPtr = DeclPtr;
2540 // For truly ABI indirect arguments -- those that are not `byval` -- store
2541 // the address of the argument on the stack to preserve debug information.
2542 ABIArgInfo ArgInfo = CurFnInfo->arguments()[ArgNo - 1].info;
2543 if (ArgInfo.isIndirect())
2544 UseIndirectDebugAddress = !ArgInfo.getIndirectByVal();
2545 if (UseIndirectDebugAddress) {
2546 auto PtrTy = getContext().getPointerType(Ty);
2547 AllocaPtr = CreateMemTemp(PtrTy, getContext().getTypeAlignInChars(PtrTy),
2548 D.getName() + ".indirect_addr");
2549 EmitStoreOfScalar(V, AllocaPtr, /* Volatile */ false, PtrTy);
2552 auto SrcLangAS = getLangOpts().OpenCL ? LangAS::opencl_private : AllocaAS;
2553 auto DestLangAS =
2554 getLangOpts().OpenCL ? LangAS::opencl_private : LangAS::Default;
2555 if (SrcLangAS != DestLangAS) {
2556 assert(getContext().getTargetAddressSpace(SrcLangAS) ==
2557 CGM.getDataLayout().getAllocaAddrSpace());
2558 auto DestAS = getContext().getTargetAddressSpace(DestLangAS);
2559 auto *T = llvm::PointerType::get(getLLVMContext(), DestAS);
2560 DeclPtr =
2561 DeclPtr.withPointer(getTargetHooks().performAddrSpaceCast(
2562 *this, V, SrcLangAS, DestLangAS, T, true),
2563 DeclPtr.isKnownNonNull());
2566 // Push a destructor cleanup for this parameter if the ABI requires it.
2567 // Don't push a cleanup in a thunk for a method that will also emit a
2568 // cleanup.
2569 if (Ty->isRecordType() && !CurFuncIsThunk &&
2570 Ty->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
2571 if (QualType::DestructionKind DtorKind =
2572 D.needsDestruction(getContext())) {
2573 assert((DtorKind == QualType::DK_cxx_destructor ||
2574 DtorKind == QualType::DK_nontrivial_c_struct) &&
2575 "unexpected destructor type");
2576 pushDestroy(DtorKind, DeclPtr, Ty);
2577 CalleeDestructedParamCleanups[cast<ParmVarDecl>(&D)] =
2578 EHStack.stable_begin();
2581 } else {
2582 // Check if the parameter address is controlled by OpenMP runtime.
2583 Address OpenMPLocalAddr =
2584 getLangOpts().OpenMP
2585 ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
2586 : Address::invalid();
2587 if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
2588 DeclPtr = OpenMPLocalAddr;
2589 AllocaPtr = DeclPtr;
2590 } else {
2591 // Otherwise, create a temporary to hold the value.
2592 DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
2593 D.getName() + ".addr", &AllocaPtr);
2595 DoStore = true;
2598 llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
2600 LValue lv = MakeAddrLValue(DeclPtr, Ty);
2601 if (IsScalar) {
2602 Qualifiers qs = Ty.getQualifiers();
2603 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
2604 // We honor __attribute__((ns_consumed)) for types with lifetime.
2605 // For __strong, it's handled by just skipping the initial retain;
2606 // otherwise we have to balance out the initial +1 with an extra
2607 // cleanup to do the release at the end of the function.
2608 bool isConsumed = D.hasAttr<NSConsumedAttr>();
2610 // If a parameter is pseudo-strong then we can omit the implicit retain.
2611 if (D.isARCPseudoStrong()) {
2612 assert(lt == Qualifiers::OCL_Strong &&
2613 "pseudo-strong variable isn't strong?");
2614 assert(qs.hasConst() && "pseudo-strong variable should be const!");
2615 lt = Qualifiers::OCL_ExplicitNone;
2618 // Load objects passed indirectly.
2619 if (Arg.isIndirect() && !ArgVal)
2620 ArgVal = Builder.CreateLoad(DeclPtr);
2622 if (lt == Qualifiers::OCL_Strong) {
2623 if (!isConsumed) {
2624 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2625 // use objc_storeStrong(&dest, value) for retaining the
2626 // object. But first, store a null into 'dest' because
2627 // objc_storeStrong attempts to release its old value.
2628 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
2629 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
2630 EmitARCStoreStrongCall(lv.getAddress(*this), ArgVal, true);
2631 DoStore = false;
2633 else
2634 // Don't use objc_retainBlock for block pointers, because we
2635 // don't want to Block_copy something just because we got it
2636 // as a parameter.
2637 ArgVal = EmitARCRetainNonBlock(ArgVal);
2639 } else {
2640 // Push the cleanup for a consumed parameter.
2641 if (isConsumed) {
2642 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
2643 ? ARCPreciseLifetime : ARCImpreciseLifetime);
2644 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
2645 precise);
2648 if (lt == Qualifiers::OCL_Weak) {
2649 EmitARCInitWeak(DeclPtr, ArgVal);
2650 DoStore = false; // The weak init is a store, no need to do two.
2654 // Enter the cleanup scope.
2655 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
2659 // Store the initial value into the alloca.
2660 if (DoStore)
2661 EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
2663 setAddrOfLocalVar(&D, DeclPtr);
2665 // Emit debug info for param declarations in non-thunk functions.
2666 if (CGDebugInfo *DI = getDebugInfo()) {
2667 if (CGM.getCodeGenOpts().hasReducedDebugInfo() && !CurFuncIsThunk &&
2668 !NoDebugInfo) {
2669 llvm::DILocalVariable *DILocalVar = DI->EmitDeclareOfArgVariable(
2670 &D, AllocaPtr.getPointer(), ArgNo, Builder, UseIndirectDebugAddress);
2671 if (const auto *Var = dyn_cast_or_null<ParmVarDecl>(&D))
2672 DI->getParamDbgMappings().insert({Var, DILocalVar});
2676 if (D.hasAttr<AnnotateAttr>())
2677 EmitVarAnnotations(&D, DeclPtr.getPointer());
2679 // We can only check return value nullability if all arguments to the
2680 // function satisfy their nullability preconditions. This makes it necessary
2681 // to emit null checks for args in the function body itself.
2682 if (requiresReturnValueNullabilityCheck()) {
2683 auto Nullability = Ty->getNullability();
2684 if (Nullability && *Nullability == NullabilityKind::NonNull) {
2685 SanitizerScope SanScope(this);
2686 RetValNullabilityPrecondition =
2687 Builder.CreateAnd(RetValNullabilityPrecondition,
2688 Builder.CreateIsNotNull(Arg.getAnyValue()));
2693 void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
2694 CodeGenFunction *CGF) {
2695 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
2696 return;
2697 getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
2700 void CodeGenModule::EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D,
2701 CodeGenFunction *CGF) {
2702 if (!LangOpts.OpenMP || LangOpts.OpenMPSimd ||
2703 (!LangOpts.EmitAllDecls && !D->isUsed()))
2704 return;
2705 getOpenMPRuntime().emitUserDefinedMapper(D, CGF);
2708 void CodeGenModule::EmitOMPRequiresDecl(const OMPRequiresDecl *D) {
2709 getOpenMPRuntime().processRequiresDirective(D);
2712 void CodeGenModule::EmitOMPAllocateDecl(const OMPAllocateDecl *D) {
2713 for (const Expr *E : D->varlists()) {
2714 const auto *DE = cast<DeclRefExpr>(E);
2715 const auto *VD = cast<VarDecl>(DE->getDecl());
2717 // Skip all but globals.
2718 if (!VD->hasGlobalStorage())
2719 continue;
2721 // Check if the global has been materialized yet or not. If not, we are done
2722 // as any later generation will utilize the OMPAllocateDeclAttr. However, if
2723 // we already emitted the global we might have done so before the
2724 // OMPAllocateDeclAttr was attached, leading to the wrong address space
2725 // (potentially). While not pretty, common practise is to remove the old IR
2726 // global and generate a new one, so we do that here too. Uses are replaced
2727 // properly.
2728 StringRef MangledName = getMangledName(VD);
2729 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2730 if (!Entry)
2731 continue;
2733 // We can also keep the existing global if the address space is what we
2734 // expect it to be, if not, it is replaced.
2735 QualType ASTTy = VD->getType();
2736 clang::LangAS GVAS = GetGlobalVarAddressSpace(VD);
2737 auto TargetAS = getContext().getTargetAddressSpace(GVAS);
2738 if (Entry->getType()->getAddressSpace() == TargetAS)
2739 continue;
2741 // Make a new global with the correct type / address space.
2742 llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
2743 llvm::PointerType *PTy = llvm::PointerType::get(Ty, TargetAS);
2745 // Replace all uses of the old global with a cast. Since we mutate the type
2746 // in place we neeed an intermediate that takes the spot of the old entry
2747 // until we can create the cast.
2748 llvm::GlobalVariable *DummyGV = new llvm::GlobalVariable(
2749 getModule(), Entry->getValueType(), false,
2750 llvm::GlobalValue::CommonLinkage, nullptr, "dummy", nullptr,
2751 llvm::GlobalVariable::NotThreadLocal, Entry->getAddressSpace());
2752 Entry->replaceAllUsesWith(DummyGV);
2754 Entry->mutateType(PTy);
2755 llvm::Constant *NewPtrForOldDecl =
2756 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
2757 Entry, DummyGV->getType());
2759 // Now we have a casted version of the changed global, the dummy can be
2760 // replaced and deleted.
2761 DummyGV->replaceAllUsesWith(NewPtrForOldDecl);
2762 DummyGV->eraseFromParent();
2766 std::optional<CharUnits>
2767 CodeGenModule::getOMPAllocateAlignment(const VarDecl *VD) {
2768 if (const auto *AA = VD->getAttr<OMPAllocateDeclAttr>()) {
2769 if (Expr *Alignment = AA->getAlignment()) {
2770 unsigned UserAlign =
2771 Alignment->EvaluateKnownConstInt(getContext()).getExtValue();
2772 CharUnits NaturalAlign =
2773 getNaturalTypeAlignment(VD->getType().getNonReferenceType());
2775 // OpenMP5.1 pg 185 lines 7-10
2776 // Each item in the align modifier list must be aligned to the maximum
2777 // of the specified alignment and the type's natural alignment.
2778 return CharUnits::fromQuantity(
2779 std::max<unsigned>(UserAlign, NaturalAlign.getQuantity()));
2782 return std::nullopt;