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.
10//
11//===----------------------------------------------------------------------===//
12
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 "CodeGenPGO.h"
22#include "ConstantEmitter.h"
23#include "EHScopeStack.h"
24#include "PatternInit.h"
25#include "TargetInfo.h"
26#include "clang/AST/ASTContext.h"
27#include "clang/AST/Attr.h"
28#include "clang/AST/CharUnits.h"
29#include "clang/AST/Decl.h"
30#include "clang/AST/DeclObjC.h"
31#include "clang/AST/DeclOpenACC.h"
32#include "clang/AST/DeclOpenMP.h"
33#include "clang/Basic/CodeGenOptions.h"
34#include "clang/Basic/TargetInfo.h"
35#include "clang/CodeGen/CGFunctionInfo.h"
36#include "clang/Sema/Sema.h"
37#include "llvm/Analysis/ConstantFolding.h"
38#include "llvm/Analysis/ValueTracking.h"
39#include "llvm/IR/DataLayout.h"
40#include "llvm/IR/GlobalVariable.h"
41#include "llvm/IR/Instructions.h"
42#include "llvm/IR/Intrinsics.h"
43#include "llvm/IR/Type.h"
44#include <optional>
45
46using namespace clang;
47using namespace CodeGen;
48
49static_assert(clang::Sema::MaximumAlignment <= llvm::Value::MaximumAlignment,
50 "Clang max alignment greater than what LLVM supports?");
51
52void CodeGenFunction::EmitDecl(const Decl &D, bool EvaluateConditionDecl) {
53 switch (D.getKind()) {
54 case Decl::BuiltinTemplate:
55 case Decl::TranslationUnit:
56 case Decl::ExternCContext:
57 case Decl::Namespace:
58 case Decl::UnresolvedUsingTypename:
59 case Decl::ClassTemplateSpecialization:
60 case Decl::ClassTemplatePartialSpecialization:
61 case Decl::VarTemplateSpecialization:
62 case Decl::VarTemplatePartialSpecialization:
63 case Decl::TemplateTypeParm:
64 case Decl::UnresolvedUsingValue:
65 case Decl::NonTypeTemplateParm:
66 case Decl::CXXDeductionGuide:
67 case Decl::CXXMethod:
68 case Decl::CXXConstructor:
69 case Decl::CXXDestructor:
70 case Decl::CXXConversion:
71 case Decl::Field:
72 case Decl::MSProperty:
73 case Decl::IndirectField:
74 case Decl::ObjCIvar:
75 case Decl::ObjCAtDefsField:
76 case Decl::ParmVar:
77 case Decl::ImplicitParam:
78 case Decl::ClassTemplate:
79 case Decl::VarTemplate:
80 case Decl::FunctionTemplate:
81 case Decl::TypeAliasTemplate:
82 case Decl::TemplateTemplateParm:
83 case Decl::ObjCMethod:
84 case Decl::ObjCCategory:
85 case Decl::ObjCProtocol:
86 case Decl::ObjCInterface:
87 case Decl::ObjCCategoryImpl:
88 case Decl::ObjCImplementation:
89 case Decl::ObjCProperty:
90 case Decl::ObjCCompatibleAlias:
91 case Decl::PragmaComment:
92 case Decl::PragmaDetectMismatch:
93 case Decl::AccessSpec:
94 case Decl::LinkageSpec:
95 case Decl::Export:
96 case Decl::ObjCPropertyImpl:
97 case Decl::FileScopeAsm:
98 case Decl::TopLevelStmt:
99 case Decl::Friend:
100 case Decl::FriendTemplate:
101 case Decl::Block:
102 case Decl::OutlinedFunction:
103 case Decl::Captured:
104 case Decl::UsingShadow:
105 case Decl::ConstructorUsingShadow:
106 case Decl::ObjCTypeParam:
107 case Decl::Binding:
108 case Decl::UnresolvedUsingIfExists:
109 case Decl::HLSLBuffer:
110 case Decl::HLSLRootSignature:
111 llvm_unreachable("Declaration should not be in declstmts!");
112 case Decl::Record: // struct/union/class X;
113 case Decl::CXXRecord: // struct/union/class X; [C++]
114 if (CGDebugInfo *DI = getDebugInfo()) {
115 DI->recordDeclarationLexicalScope(D);
116 if (cast<RecordDecl>(Val: D).getDefinition())
117 DI->EmitAndRetainType(
118 Ty: getContext().getCanonicalTagType(TD: cast<RecordDecl>(Val: &D)));
119 }
120 return;
121 case Decl::Enum: // enum X;
122 if (CGDebugInfo *DI = getDebugInfo()) {
123 DI->recordDeclarationLexicalScope(D);
124 if (cast<EnumDecl>(Val: D).getDefinition())
125 DI->EmitAndRetainType(
126 Ty: getContext().getCanonicalTagType(TD: cast<EnumDecl>(Val: &D)));
127 }
128 return;
129 case Decl::Function: // void X();
130 case Decl::EnumConstant: // enum ? { X = ? }
131 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
132 case Decl::ExplicitInstantiation:
133 case Decl::Label: // __label__ x;
134 case Decl::Import:
135 case Decl::MSGuid: // __declspec(uuid("..."))
136 case Decl::UnnamedGlobalConstant:
137 case Decl::TemplateParamObject:
138 case Decl::OMPThreadPrivate:
139 case Decl::OMPGroupPrivate:
140 case Decl::OMPAllocate:
141 case Decl::OMPCapturedExpr:
142 case Decl::OMPRequires:
143 case Decl::Empty:
144 case Decl::Concept:
145 case Decl::ImplicitConceptSpecialization:
146 case Decl::LifetimeExtendedTemporary:
147 case Decl::RequiresExprBody:
148 // None of these decls require codegen support.
149 return;
150
151 case Decl::CXXExpansionStmt: {
152 const auto *ESD = cast<CXXExpansionStmtDecl>(Val: &D);
153 assert(ESD->getInstantiations() && "expansion statement not expanded?");
154 EmitStmt(S: ESD->getInstantiations());
155 return;
156 }
157
158 case Decl::NamespaceAlias:
159 if (CGDebugInfo *DI = getDebugInfo())
160 DI->EmitNamespaceAlias(NA: cast<NamespaceAliasDecl>(Val: D));
161 return;
162 case Decl::Using: // using X; [C++]
163 if (CGDebugInfo *DI = getDebugInfo())
164 DI->EmitUsingDecl(UD: cast<UsingDecl>(Val: D));
165 return;
166 case Decl::UsingEnum: // using enum X; [C++]
167 if (CGDebugInfo *DI = getDebugInfo())
168 DI->EmitUsingEnumDecl(UD: cast<UsingEnumDecl>(Val: D));
169 return;
170 case Decl::UsingPack:
171 for (auto *Using : cast<UsingPackDecl>(Val: D).expansions())
172 EmitDecl(D: *Using, /*EvaluateConditionDecl=*/EvaluateConditionDecl);
173 return;
174 case Decl::UsingDirective: // using namespace X; [C++]
175 if (CGDebugInfo *DI = getDebugInfo())
176 DI->EmitUsingDirective(UD: cast<UsingDirectiveDecl>(Val: D));
177 return;
178 case Decl::Var:
179 case Decl::Decomposition: {
180 const VarDecl &VD = cast<VarDecl>(Val: D);
181 assert(VD.isLocalVarDecl() &&
182 "Should not see file-scope variables inside a function!");
183 EmitVarDecl(D: VD);
184 if (EvaluateConditionDecl)
185 MaybeEmitDeferredVarDeclInit(var: &VD);
186
187 return;
188 }
189
190 case Decl::OMPDeclareReduction:
191 return CGM.EmitOMPDeclareReduction(D: cast<OMPDeclareReductionDecl>(Val: &D), CGF: this);
192
193 case Decl::OMPDeclareMapper:
194 return CGM.EmitOMPDeclareMapper(D: cast<OMPDeclareMapperDecl>(Val: &D), CGF: this);
195
196 case Decl::OpenACCDeclare:
197 return CGM.EmitOpenACCDeclare(D: cast<OpenACCDeclareDecl>(Val: &D), CGF: this);
198 case Decl::OpenACCRoutine:
199 return CGM.EmitOpenACCRoutine(D: cast<OpenACCRoutineDecl>(Val: &D), CGF: this);
200
201 case Decl::Typedef: // typedef int X;
202 case Decl::TypeAlias: { // using X = int; [C++0x]
203 QualType Ty = cast<TypedefNameDecl>(Val: D).getUnderlyingType();
204 if (CGDebugInfo *DI = getDebugInfo()) {
205 DI->recordDeclarationLexicalScope(D);
206 DI->EmitAndRetainType(Ty);
207 }
208 if (Ty->isVariablyModifiedType())
209 EmitVariablyModifiedType(Ty);
210 return;
211 }
212 }
213}
214
215/// EmitVarDecl - This method handles emission of any variable declaration
216/// inside a function, including static vars etc.
217void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
218 if (D.hasExternalStorage())
219 // Don't emit it now, allow it to be emitted lazily on its first use.
220 return;
221
222 // Some function-scope variable does not have static storage but still
223 // needs to be emitted like a static variable, e.g. a function-scope
224 // variable in constant address space in OpenCL.
225 if (D.getStorageDuration() != SD_Automatic) {
226 // Static sampler variables translated to function calls.
227 if (D.getType()->isSamplerT())
228 return;
229
230 llvm::GlobalValue::LinkageTypes Linkage =
231 CGM.getLLVMLinkageVarDefinition(VD: &D);
232
233 // FIXME: We need to force the emission/use of a guard variable for
234 // some variables even if we can constant-evaluate them because
235 // we can't guarantee every translation unit will constant-evaluate them.
236
237 return EmitStaticVarDecl(D, Linkage);
238 }
239
240 if (D.getType().getAddressSpace() == LangAS::opencl_local)
241 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(CGF&: *this, D);
242
243 assert(D.hasLocalStorage());
244 return EmitAutoVarDecl(D);
245}
246
247static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
248 if (CGM.getLangOpts().CPlusPlus)
249 return CGM.getMangledName(GD: &D).str();
250
251 // If this isn't C++, we don't need a mangled name, just a pretty one.
252 assert(!D.isExternallyVisible() && "name shouldn't matter");
253 std::string ContextName;
254 const DeclContext *DC = D.getDeclContext();
255 if (auto *CD = dyn_cast<CapturedDecl>(Val: DC))
256 DC = cast<DeclContext>(Val: CD->getNonClosureContext());
257 if (const auto *FD = dyn_cast<FunctionDecl>(Val: DC))
258 ContextName = std::string(CGM.getMangledName(GD: FD));
259 else if (const auto *BD = dyn_cast<BlockDecl>(Val: DC))
260 ContextName = std::string(CGM.getBlockMangledName(GD: GlobalDecl(), BD));
261 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(Val: DC))
262 ContextName = OMD->getSelector().getAsString();
263 else
264 llvm_unreachable("Unknown context for static var decl");
265
266 ContextName += "." + D.getNameAsString();
267 return ContextName;
268}
269
270llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
271 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
272 // In general, we don't always emit static var decls once before we reference
273 // them. It is possible to reference them before emitting the function that
274 // contains them, and it is possible to emit the containing function multiple
275 // times.
276 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
277 return ExistingGV;
278
279 QualType Ty = D.getType();
280 assert(Ty->isConstantSizeType() && "VLAs can't be static");
281
282 // Use the label if the variable is renamed with the asm-label extension.
283 std::string Name;
284 if (D.hasAttr<AsmLabelAttr>())
285 Name = std::string(getMangledName(GD: &D));
286 else
287 Name = getStaticDeclName(CGM&: *this, D);
288
289 llvm::Type *LTy = getTypes().ConvertTypeForMem(T: Ty);
290 LangAS AS = GetGlobalVarAddressSpace(D: &D);
291 unsigned TargetAS = getContext().getTargetAddressSpace(AS);
292
293 // OpenCL variables in local address space and CUDA shared
294 // variables cannot have an initializer.
295 llvm::Constant *Init = nullptr;
296 if (Ty.getAddressSpace() == LangAS::opencl_local ||
297 D.hasAttr<CUDASharedAttr>() || D.hasAttr<LoaderUninitializedAttr>())
298 Init = llvm::UndefValue::get(T: LTy);
299 else
300 Init = EmitNullConstant(T: Ty);
301
302 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
303 getModule(), LTy, Ty.isConstant(Ctx: getContext()), Linkage, Init, Name,
304 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
305 GV->setAlignment(getContext().getDeclAlign(D: &D).getAsAlign());
306
307 if (supportsCOMDAT() && GV->isWeakForLinker())
308 GV->setComdat(TheModule.getOrInsertComdat(Name: GV->getName()));
309
310 if (D.getTLSKind())
311 setTLSMode(GV, D);
312
313 setGVProperties(GV, D: &D);
314 getTargetCodeGenInfo().setTargetAttributes(D: cast<Decl>(Val: &D), GV, M&: *this);
315
316 // Make sure the result is of the correct type.
317 LangAS ExpectedAS = Ty.getAddressSpace();
318 llvm::Constant *Addr = GV;
319 if (AS != ExpectedAS && D.getTLSKind() == VarDecl::TLS_None) {
320 Addr = performAddrSpaceCast(
321 Src: GV,
322 DestTy: llvm::PointerType::get(C&: getLLVMContext(),
323 AddressSpace: getContext().getTargetAddressSpace(AS: ExpectedAS)));
324 }
325
326 setStaticLocalDeclAddress(D: &D, C: Addr);
327
328 // Ensure that the static local gets initialized by making sure the parent
329 // function gets emitted eventually.
330 const Decl *DC = cast<Decl>(Val: D.getDeclContext());
331
332 // We can't name blocks or captured statements directly, so try to emit their
333 // parents.
334 if (isa<BlockDecl>(Val: DC) || isa<CapturedDecl>(Val: DC)) {
335 DC = DC->getNonClosureContext();
336 // FIXME: Ensure that global blocks get emitted.
337 if (!DC)
338 return Addr;
339 }
340
341 GlobalDecl GD;
342 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Val: DC))
343 GD = GlobalDecl(CD, Ctor_Base);
344 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Val: DC))
345 GD = GlobalDecl(DD, Dtor_Base);
346 else if (const auto *FD = dyn_cast<FunctionDecl>(Val: DC))
347 GD = GlobalDecl(FD);
348 else {
349 // Don't do anything for Obj-C method decls or global closures. We should
350 // never defer them.
351 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
352 }
353 if (GD.getDecl()) {
354 // Disable emission of the parent function for the OpenMP device codegen.
355 CGOpenMPRuntime::DisableAutoDeclareTargetRAII NoDeclTarget(*this);
356 (void)GetAddrOfGlobal(GD);
357 }
358
359 return Addr;
360}
361
362/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
363/// global variable that has already been created for it. If the initializer
364/// has a different type than GV does, this may free GV and return a different
365/// one. Otherwise it just returns GV.
366llvm::GlobalVariable *
367CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
368 llvm::GlobalVariable *GV) {
369 ConstantEmitter emitter(*this);
370 llvm::Constant *Init = emitter.tryEmitForInitializer(D);
371
372 // If constant emission failed, then this should be a C++ static
373 // initializer.
374 if (!Init) {
375 if (!getLangOpts().CPlusPlus)
376 CGM.ErrorUnsupported(S: D.getInit(), Type: "constant l-value expression");
377 else if (D.hasFlexibleArrayInit(Ctx: getContext()))
378 CGM.ErrorUnsupported(S: D.getInit(), Type: "flexible array initializer");
379 else if (HaveInsertPoint()) {
380 // Since we have a static initializer, this global variable can't
381 // be constant.
382 GV->setConstant(false);
383
384 EmitCXXGuardedInit(D, DeclPtr: GV, /*PerformInit*/true);
385 }
386 return GV;
387 }
388
389 PGO->markStmtMaybeUsed(S: D.getInit()); // FIXME: Too lazy
390
391#ifndef NDEBUG
392 CharUnits VarSize = CGM.getContext().getTypeSizeInChars(D.getType()) +
393 D.getFlexibleArrayInitChars(getContext());
394 CharUnits CstSize = CharUnits::fromQuantity(
395 CGM.getDataLayout().getTypeAllocSize(Init->getType()));
396 assert(VarSize == CstSize && "Emitted constant has unexpected size");
397#endif
398
399 bool NeedsDtor =
400 D.needsDestruction(Ctx: getContext()) == QualType::DK_cxx_destructor;
401
402 GV->setConstant(
403 D.getType().isConstantStorage(Ctx: getContext(), ExcludeCtor: true, ExcludeDtor: !NeedsDtor));
404 GV->replaceInitializer(InitVal: Init);
405
406 emitter.finalize(global: GV);
407
408 if (NeedsDtor && HaveInsertPoint()) {
409 // We have a constant initializer, but a nontrivial destructor. We still
410 // need to perform a guarded "initialization" in order to register the
411 // destructor.
412 EmitCXXGuardedInit(D, DeclPtr: GV, /*PerformInit*/false);
413 }
414
415 return GV;
416}
417
418void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
419 llvm::GlobalValue::LinkageTypes Linkage) {
420 // Check to see if we already have a global variable for this
421 // declaration. This can happen when double-emitting function
422 // bodies, e.g. with complete and base constructors.
423 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
424 CharUnits alignment = getContext().getDeclAlign(D: &D);
425
426 // Store into LocalDeclMap before generating initializer to handle
427 // circular references.
428 llvm::Type *elemTy = ConvertTypeForMem(T: D.getType());
429 setAddrOfLocalVar(VD: &D, Addr: Address(addr, elemTy, alignment));
430
431 // We can't have a VLA here, but we can have a pointer to a VLA,
432 // even though that doesn't really make any sense.
433 // Make sure to evaluate VLA bounds now so that we have them for later.
434 if (D.getType()->isVariablyModifiedType())
435 EmitVariablyModifiedType(Ty: D.getType());
436
437 // Save the type in case adding the initializer forces a type change.
438 llvm::Type *expectedType = addr->getType();
439
440 llvm::GlobalVariable *var =
441 cast<llvm::GlobalVariable>(Val: addr->stripPointerCasts());
442
443 // CUDA's local and local static __shared__ variables should not
444 // have any non-empty initializers. This is ensured by Sema.
445 // Whatever initializer such variable may have when it gets here is
446 // a no-op and should not be emitted.
447 bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
448 D.hasAttr<CUDASharedAttr>();
449 // If this value has an initializer, emit it.
450 if (D.getInit() && !isCudaSharedVar) {
451 ApplyAtomGroup Grp(getDebugInfo());
452 var = AddInitializerToStaticVarDecl(D, GV: var);
453 }
454
455 var->setAlignment(alignment.getAsAlign());
456
457 if (D.hasAttr<AnnotateAttr>())
458 CGM.AddGlobalAnnotations(D: &D, GV: var);
459
460 if (auto *SA = D.getAttr<PragmaClangBSSSectionAttr>())
461 var->addAttribute(Kind: "bss-section", Val: SA->getName());
462 if (auto *SA = D.getAttr<PragmaClangDataSectionAttr>())
463 var->addAttribute(Kind: "data-section", Val: SA->getName());
464 if (auto *SA = D.getAttr<PragmaClangRodataSectionAttr>())
465 var->addAttribute(Kind: "rodata-section", Val: SA->getName());
466 if (auto *SA = D.getAttr<PragmaClangRelroSectionAttr>())
467 var->addAttribute(Kind: "relro-section", Val: SA->getName());
468
469 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
470 var->setSection(SA->getName());
471
472 if (D.hasAttr<RetainAttr>())
473 CGM.addUsedGlobal(GV: var);
474 else if (D.hasAttr<UsedAttr>())
475 CGM.addUsedOrCompilerUsedGlobal(GV: var);
476
477 if (CGM.getCodeGenOpts().KeepPersistentStorageVariables)
478 CGM.addUsedOrCompilerUsedGlobal(GV: var);
479
480 // We may have to cast the constant because of the initializer
481 // mismatch above.
482 //
483 // FIXME: It is really dangerous to store this in the map; if anyone
484 // RAUW's the GV uses of this constant will be invalid.
485 llvm::Constant *castedAddr =
486 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(C: var, Ty: expectedType);
487 LocalDeclMap.find(Val: &D)->second = Address(castedAddr, elemTy, alignment);
488 CGM.setStaticLocalDeclAddress(D: &D, C: castedAddr);
489
490 CGM.getSanitizerMetadata()->reportGlobal(GV: var, D);
491
492 // Emit global variable debug descriptor for static vars.
493 CGDebugInfo *DI = getDebugInfo();
494 if (DI && CGM.getCodeGenOpts().hasReducedDebugInfo()) {
495 DI->setLocation(D.getLocation());
496 DI->EmitGlobalVariable(GV: var, Decl: &D);
497 }
498}
499
500namespace {
501 struct DestroyObject final : EHScopeStack::Cleanup {
502 DestroyObject(Address addr, QualType type,
503 CodeGenFunction::Destroyer *destroyer,
504 bool useEHCleanupForArray)
505 : addr(addr), type(type), destroyer(destroyer),
506 useEHCleanupForArray(useEHCleanupForArray) {}
507
508 Address addr;
509 QualType type;
510 CodeGenFunction::Destroyer *destroyer;
511 bool useEHCleanupForArray;
512
513 void Emit(CodeGenFunction &CGF, Flags flags) override {
514 // Don't use an EH cleanup recursively from an EH cleanup.
515 bool useEHCleanupForArray =
516 flags.isForNormalCleanup() && this->useEHCleanupForArray;
517
518 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
519 }
520 };
521
522 template <class Derived>
523 struct DestroyNRVOVariable : EHScopeStack::Cleanup {
524 DestroyNRVOVariable(Address addr, QualType type, llvm::Value *NRVOFlag)
525 : NRVOFlag(NRVOFlag), Loc(addr), Ty(type) {}
526
527 llvm::Value *NRVOFlag;
528 Address Loc;
529 QualType Ty;
530
531 void Emit(CodeGenFunction &CGF, Flags flags) override {
532 // Along the exceptions path we always execute the dtor.
533 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
534
535 llvm::BasicBlock *SkipDtorBB = nullptr;
536 if (NRVO) {
537 // If we exited via NRVO, we skip the destructor call.
538 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock(name: "nrvo.unused");
539 SkipDtorBB = CGF.createBasicBlock(name: "nrvo.skipdtor");
540 llvm::Value *DidNRVO =
541 CGF.Builder.CreateFlagLoad(Addr: NRVOFlag, Name: "nrvo.val");
542 CGF.Builder.CreateCondBr(Cond: DidNRVO, True: SkipDtorBB, False: RunDtorBB);
543 CGF.EmitBlock(BB: RunDtorBB);
544 }
545
546 static_cast<Derived *>(this)->emitDestructorCall(CGF);
547
548 if (NRVO) CGF.EmitBlock(BB: SkipDtorBB);
549 }
550
551 virtual ~DestroyNRVOVariable() = default;
552 };
553
554 struct DestroyNRVOVariableCXX final
555 : DestroyNRVOVariable<DestroyNRVOVariableCXX> {
556 DestroyNRVOVariableCXX(Address addr, QualType type,
557 const CXXDestructorDecl *Dtor, llvm::Value *NRVOFlag)
558 : DestroyNRVOVariable<DestroyNRVOVariableCXX>(addr, type, NRVOFlag),
559 Dtor(Dtor) {}
560
561 const CXXDestructorDecl *Dtor;
562
563 void emitDestructorCall(CodeGenFunction &CGF) {
564 CGF.EmitCXXDestructorCall(D: Dtor, Type: Dtor_Complete,
565 /*ForVirtualBase=*/false,
566 /*Delegating=*/false, This: Loc, ThisTy: Ty);
567 }
568 };
569
570 struct DestroyNRVOVariableC final
571 : DestroyNRVOVariable<DestroyNRVOVariableC> {
572 DestroyNRVOVariableC(Address addr, llvm::Value *NRVOFlag, QualType Ty)
573 : DestroyNRVOVariable<DestroyNRVOVariableC>(addr, Ty, NRVOFlag) {}
574
575 void emitDestructorCall(CodeGenFunction &CGF) {
576 CGF.destroyNonTrivialCStruct(CGF, Loc, Ty);
577 }
578 };
579
580 struct CallStackRestore final : EHScopeStack::Cleanup {
581 Address Stack;
582 CallStackRestore(Address Stack) : Stack(Stack) {}
583 void Emit(CodeGenFunction &CGF, Flags flags) override {
584 llvm::Value *V = CGF.Builder.CreateLoad(Addr: Stack);
585 CGF.Builder.CreateStackRestore(Ptr: V);
586 }
587 };
588
589 struct KmpcAllocFree final : EHScopeStack::Cleanup {
590 std::pair<llvm::Value *, llvm::Value *> AddrSizePair;
591 KmpcAllocFree(const std::pair<llvm::Value *, llvm::Value *> &AddrSizePair)
592 : AddrSizePair(AddrSizePair) {}
593 void Emit(CodeGenFunction &CGF, Flags EmissionFlags) override {
594 auto &RT = CGF.CGM.getOpenMPRuntime();
595 RT.getKmpcFreeShared(CGF, AddrSizePair);
596 }
597 };
598
599 struct ExtendGCLifetime final : EHScopeStack::Cleanup {
600 const VarDecl &Var;
601 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
602
603 void Emit(CodeGenFunction &CGF, Flags flags) override {
604 // Compute the address of the local variable, in case it's a
605 // byref or something.
606 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
607 Var.getType(), VK_LValue, SourceLocation());
608 llvm::Value *value = CGF.EmitLoadOfScalar(lvalue: CGF.EmitDeclRefLValue(E: &DRE),
609 Loc: SourceLocation());
610 CGF.EmitExtendGCLifetime(object: value);
611 }
612 };
613
614 struct CallCleanupFunction final : EHScopeStack::Cleanup {
615 llvm::Constant *CleanupFn;
616 const CGFunctionInfo &FnInfo;
617 const VarDecl &Var;
618 const CleanupAttr *Attribute;
619
620 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
621 const VarDecl *Var, const CleanupAttr *Attr)
622 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var), Attribute(Attr) {}
623
624 void Emit(CodeGenFunction &CGF, Flags flags) override {
625 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
626 Var.getType(), VK_LValue, SourceLocation());
627 // Compute the address of the local variable, in case it's a byref
628 // or something.
629 llvm::Value *Addr = CGF.EmitDeclRefLValue(E: &DRE).getPointer(CGF);
630
631 // In some cases, the type of the function argument will be different from
632 // the type of the pointer. An example of this is
633 // void f(void* arg);
634 // __attribute__((cleanup(f))) void *g;
635 //
636 // To fix this we insert a bitcast here.
637 QualType ArgTy = FnInfo.arg_begin()->type;
638 llvm::Value *Arg =
639 CGF.Builder.CreateBitCast(V: Addr, DestTy: CGF.ConvertType(T: ArgTy));
640
641 CallArgList Args;
642 Args.add(rvalue: RValue::get(V: Arg),
643 type: CGF.getContext().getPointerType(T: Var.getType()));
644 GlobalDecl GD = GlobalDecl(Attribute->getFunctionDecl());
645 auto Callee = CGCallee::forDirect(functionPtr: CleanupFn, abstractInfo: CGCalleeInfo(GD));
646 CGF.EmitCall(CallInfo: FnInfo, Callee, ReturnValue: ReturnValueSlot(), Args,
647 /*callOrInvoke*/ CallOrInvoke: nullptr, /*IsMustTail*/ false,
648 Loc: Attribute->getLoc());
649 }
650 };
651} // end anonymous namespace
652
653/// EmitAutoVarWithLifetime - Does the setup required for an automatic
654/// variable with lifetime.
655static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
656 Address addr,
657 Qualifiers::ObjCLifetime lifetime) {
658 switch (lifetime) {
659 case Qualifiers::OCL_None:
660 llvm_unreachable("present but none");
661
662 case Qualifiers::OCL_ExplicitNone:
663 // nothing to do
664 break;
665
666 case Qualifiers::OCL_Strong: {
667 CodeGenFunction::Destroyer *destroyer =
668 (var.hasAttr<ObjCPreciseLifetimeAttr>()
669 ? CodeGenFunction::destroyARCStrongPrecise
670 : CodeGenFunction::destroyARCStrongImprecise);
671
672 CleanupKind cleanupKind = CGF.getARCCleanupKind();
673 CGF.pushDestroy(kind: cleanupKind, addr, type: var.getType(), destroyer,
674 useEHCleanupForArray: cleanupKind & EHCleanup);
675 break;
676 }
677 case Qualifiers::OCL_Autoreleasing:
678 // nothing to do
679 break;
680
681 case Qualifiers::OCL_Weak:
682 // __weak objects always get EH cleanups; otherwise, exceptions
683 // could cause really nasty crashes instead of mere leaks.
684 CGF.pushDestroy(kind: NormalAndEHCleanup, addr, type: var.getType(),
685 destroyer: CodeGenFunction::destroyARCWeak,
686 /*useEHCleanup*/ useEHCleanupForArray: true);
687 break;
688 }
689}
690
691static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
692 if (const Expr *e = dyn_cast<Expr>(Val: s)) {
693 // Skip the most common kinds of expressions that make
694 // hierarchy-walking expensive.
695 s = e = e->IgnoreParenCasts();
696
697 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(Val: e))
698 return (ref->getDecl() == &var);
699 if (const BlockExpr *be = dyn_cast<BlockExpr>(Val: e)) {
700 const BlockDecl *block = be->getBlockDecl();
701 for (const auto &I : block->captures()) {
702 if (I.getVariable() == &var)
703 return true;
704 }
705 }
706 }
707
708 for (const Stmt *SubStmt : s->children())
709 // SubStmt might be null; as in missing decl or conditional of an if-stmt.
710 if (SubStmt && isAccessedBy(var, s: SubStmt))
711 return true;
712
713 return false;
714}
715
716static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
717 if (!decl) return false;
718 if (!isa<VarDecl>(Val: decl)) return false;
719 const VarDecl *var = cast<VarDecl>(Val: decl);
720 return isAccessedBy(var: *var, s: e);
721}
722
723static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
724 const LValue &destLV, const Expr *init) {
725 bool needsCast = false;
726
727 while (auto castExpr = dyn_cast<CastExpr>(Val: init->IgnoreParens())) {
728 switch (castExpr->getCastKind()) {
729 // Look through casts that don't require representation changes.
730 case CK_NoOp:
731 case CK_BitCast:
732 case CK_BlockPointerToObjCPointerCast:
733 needsCast = true;
734 break;
735
736 // If we find an l-value to r-value cast from a __weak variable,
737 // emit this operation as a copy or move.
738 case CK_LValueToRValue: {
739 const Expr *srcExpr = castExpr->getSubExpr();
740 if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
741 return false;
742
743 // Emit the source l-value.
744 LValue srcLV = CGF.EmitLValue(E: srcExpr);
745
746 // Handle a formal type change to avoid asserting.
747 auto srcAddr = srcLV.getAddress();
748 if (needsCast) {
749 srcAddr = srcAddr.withElementType(ElemTy: destLV.getAddress().getElementType());
750 }
751
752 // If it was an l-value, use objc_copyWeak.
753 if (srcExpr->isLValue()) {
754 CGF.EmitARCCopyWeak(dst: destLV.getAddress(), src: srcAddr);
755 } else {
756 assert(srcExpr->isXValue());
757 CGF.EmitARCMoveWeak(dst: destLV.getAddress(), src: srcAddr);
758 }
759 return true;
760 }
761
762 // Stop at anything else.
763 default:
764 return false;
765 }
766
767 init = castExpr->getSubExpr();
768 }
769 return false;
770}
771
772static void drillIntoBlockVariable(CodeGenFunction &CGF,
773 LValue &lvalue,
774 const VarDecl *var) {
775 lvalue.setAddress(CGF.emitBlockByrefAddress(baseAddr: lvalue.getAddress(), V: var));
776}
777
778void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS,
779 SourceLocation Loc) {
780 if (!SanOpts.has(K: SanitizerKind::NullabilityAssign))
781 return;
782
783 auto Nullability = LHS.getType()->getNullability();
784 if (!Nullability || *Nullability != NullabilityKind::NonNull)
785 return;
786
787 // Check if the right hand side of the assignment is nonnull, if the left
788 // hand side must be nonnull.
789 auto CheckOrdinal = SanitizerKind::SO_NullabilityAssign;
790 auto CheckHandler = SanitizerHandler::TypeMismatch;
791 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
792 llvm::Value *IsNotNull;
793 if (auto *MPT = LHS.getType()->getAs<MemberPointerType>())
794 IsNotNull = CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF&: *this, MemPtr: RHS, MPT);
795 else
796 IsNotNull = Builder.CreateIsNotNull(Arg: RHS);
797
798 llvm::Constant *StaticData[] = {
799 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(T: LHS.getType()),
800 llvm::ConstantInt::get(Ty: Int8Ty, V: 0), // The LogAlignment info is unused.
801 llvm::ConstantInt::get(Ty: Int8Ty, V: TCK_NonnullAssign)};
802 EmitCheck(Checked: {{IsNotNull, CheckOrdinal}}, Check: CheckHandler, StaticArgs: StaticData, DynamicArgs: RHS);
803}
804
805void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
806 LValue lvalue, bool capturedByInit) {
807 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
808 if (!lifetime) {
809 llvm::Value *Value;
810 if (PointerAuthQualifier PtrAuth = lvalue.getQuals().getPointerAuth()) {
811 Value = EmitPointerAuthQualify(Qualifier: PtrAuth, PointerExpr: init, StorageAddress: lvalue.getAddress());
812 lvalue.getQuals().removePointerAuth();
813 } else {
814 Value = EmitScalarExpr(E: init);
815 }
816 if (capturedByInit)
817 drillIntoBlockVariable(CGF&: *this, lvalue, var: cast<VarDecl>(Val: D));
818 EmitNullabilityCheck(LHS: lvalue, RHS: Value, Loc: init->getExprLoc());
819 EmitStoreThroughLValue(Src: RValue::get(V: Value), Dst: lvalue, isInit: true);
820 return;
821 }
822
823 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(Val: init))
824 init = DIE->getExpr();
825
826 // If we're emitting a value with lifetime, we have to do the
827 // initialization *before* we leave the cleanup scopes.
828 if (auto *EWC = dyn_cast<ExprWithCleanups>(Val: init)) {
829 CodeGenFunction::RunCleanupsScope Scope(*this);
830 return EmitScalarInit(init: EWC->getSubExpr(), D, lvalue, capturedByInit);
831 }
832
833 // We have to maintain the illusion that the variable is
834 // zero-initialized. If the variable might be accessed in its
835 // initializer, zero-initialize before running the initializer, then
836 // actually perform the initialization with an assign.
837 bool accessedByInit = false;
838 if (lifetime != Qualifiers::OCL_ExplicitNone)
839 accessedByInit = (capturedByInit || isAccessedBy(decl: D, e: init));
840 if (accessedByInit) {
841 LValue tempLV = lvalue;
842 // Drill down to the __block object if necessary.
843 if (capturedByInit) {
844 // We can use a simple GEP for this because it can't have been
845 // moved yet.
846 tempLV.setAddress(emitBlockByrefAddress(baseAddr: tempLV.getAddress(),
847 V: cast<VarDecl>(Val: D),
848 /*follow*/ followForward: false));
849 }
850
851 auto ty = cast<llvm::PointerType>(Val: tempLV.getAddress().getElementType());
852 llvm::Value *zero = CGM.getNullPointer(T: ty, QT: tempLV.getType());
853
854 // If __weak, we want to use a barrier under certain conditions.
855 if (lifetime == Qualifiers::OCL_Weak)
856 EmitARCInitWeak(addr: tempLV.getAddress(), value: zero);
857
858 // Otherwise just do a simple store.
859 else
860 EmitStoreOfScalar(value: zero, lvalue: tempLV, /* isInitialization */ isInit: true);
861 }
862
863 // Emit the initializer.
864 llvm::Value *value = nullptr;
865
866 switch (lifetime) {
867 case Qualifiers::OCL_None:
868 llvm_unreachable("present but none");
869
870 case Qualifiers::OCL_Strong: {
871 if (!D || !isa<VarDecl>(Val: D) || !cast<VarDecl>(Val: D)->isARCPseudoStrong()) {
872 value = EmitARCRetainScalarExpr(expr: init);
873 break;
874 }
875 // If D is pseudo-strong, treat it like __unsafe_unretained here. This means
876 // that we omit the retain, and causes non-autoreleased return values to be
877 // immediately released.
878 [[fallthrough]];
879 }
880
881 case Qualifiers::OCL_ExplicitNone:
882 value = EmitARCUnsafeUnretainedScalarExpr(expr: init);
883 break;
884
885 case Qualifiers::OCL_Weak: {
886 // If it's not accessed by the initializer, try to emit the
887 // initialization with a copy or move.
888 if (!accessedByInit && tryEmitARCCopyWeakInit(CGF&: *this, destLV: lvalue, init)) {
889 return;
890 }
891
892 // No way to optimize a producing initializer into this. It's not
893 // worth optimizing for, because the value will immediately
894 // disappear in the common case.
895 value = EmitScalarExpr(E: init);
896
897 if (capturedByInit) drillIntoBlockVariable(CGF&: *this, lvalue, var: cast<VarDecl>(Val: D));
898 if (accessedByInit)
899 EmitARCStoreWeak(addr: lvalue.getAddress(), value, /*ignored*/ true);
900 else
901 EmitARCInitWeak(addr: lvalue.getAddress(), value);
902 return;
903 }
904
905 case Qualifiers::OCL_Autoreleasing:
906 value = EmitARCRetainAutoreleaseScalarExpr(expr: init);
907 break;
908 }
909
910 if (capturedByInit) drillIntoBlockVariable(CGF&: *this, lvalue, var: cast<VarDecl>(Val: D));
911
912 EmitNullabilityCheck(LHS: lvalue, RHS: value, Loc: init->getExprLoc());
913
914 // If the variable might have been accessed by its initializer, we
915 // might have to initialize with a barrier. We have to do this for
916 // both __weak and __strong, but __weak got filtered out above.
917 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
918 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, Loc: init->getExprLoc());
919 EmitStoreOfScalar(value, lvalue, /* isInitialization */ isInit: true);
920 EmitARCRelease(value: oldValue, precise: ARCImpreciseLifetime);
921 return;
922 }
923
924 EmitStoreOfScalar(value, lvalue, /* isInitialization */ isInit: true);
925}
926
927/// Decide whether we can emit the non-zero parts of the specified initializer
928/// with equal or fewer than NumStores scalar stores.
929static bool canEmitInitWithFewStoresAfterBZero(llvm::Constant *Init,
930 unsigned &NumStores) {
931 // Zero and Undef never requires any extra stores.
932 if (isa<llvm::ConstantAggregateZero>(Val: Init) ||
933 isa<llvm::ConstantPointerNull>(Val: Init) ||
934 isa<llvm::UndefValue>(Val: Init))
935 return true;
936 if (isa<llvm::ConstantInt>(Val: Init) || isa<llvm::ConstantFP>(Val: Init) ||
937 isa<llvm::ConstantVector>(Val: Init) || isa<llvm::BlockAddress>(Val: Init) ||
938 isa<llvm::ConstantExpr>(Val: Init))
939 return Init->isNullValue() || NumStores--;
940
941 // See if we can emit each element.
942 if (isa<llvm::ConstantArray>(Val: Init) || isa<llvm::ConstantStruct>(Val: Init)) {
943 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
944 llvm::Constant *Elt = cast<llvm::Constant>(Val: Init->getOperand(i));
945 if (!canEmitInitWithFewStoresAfterBZero(Init: Elt, NumStores))
946 return false;
947 }
948 return true;
949 }
950
951 if (llvm::ConstantDataSequential *CDS =
952 dyn_cast<llvm::ConstantDataSequential>(Val: Init)) {
953 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
954 llvm::Constant *Elt = CDS->getElementAsConstant(i);
955 if (!canEmitInitWithFewStoresAfterBZero(Init: Elt, NumStores))
956 return false;
957 }
958 return true;
959 }
960
961 // Anything else is hard and scary.
962 return false;
963}
964
965/// For inits that canEmitInitWithFewStoresAfterBZero returned true for, emit
966/// the scalar stores that would be required.
967void CodeGenFunction::emitStoresForInitAfterBZero(llvm::Constant *Init,
968 Address Loc, bool isVolatile,
969 bool IsAutoInit) {
970 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
971 "called emitStoresForInitAfterBZero for zero or undef value.");
972
973 if (isa<llvm::ConstantInt>(Val: Init) || isa<llvm::ConstantFP>(Val: Init) ||
974 isa<llvm::ConstantVector>(Val: Init) || isa<llvm::BlockAddress>(Val: Init) ||
975 isa<llvm::ConstantExpr>(Val: Init)) {
976 auto *I = Builder.CreateStore(Val: Init, Addr: Loc, IsVolatile: isVolatile);
977 addInstToCurrentSourceAtom(KeyInstruction: I, Backup: nullptr);
978 if (IsAutoInit)
979 I->addAnnotationMetadata(Annotation: "auto-init");
980 return;
981 }
982
983 if (llvm::ConstantDataSequential *CDS =
984 dyn_cast<llvm::ConstantDataSequential>(Val: Init)) {
985 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
986 llvm::Constant *Elt = CDS->getElementAsConstant(i);
987
988 // If necessary, get a pointer to the element and emit it.
989 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Val: Elt))
990 emitStoresForInitAfterBZero(
991 Init: Elt, Loc: Builder.CreateConstInBoundsGEP2_32(Addr: Loc, Idx0: 0, Idx1: i), isVolatile,
992 IsAutoInit);
993 }
994 return;
995 }
996
997 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
998 "Unknown value type!");
999
1000 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
1001 llvm::Constant *Elt = cast<llvm::Constant>(Val: Init->getOperand(i));
1002
1003 // If necessary, get a pointer to the element and emit it.
1004 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Val: Elt))
1005 emitStoresForInitAfterBZero(Init: Elt,
1006 Loc: Builder.CreateConstInBoundsGEP2_32(Addr: Loc, Idx0: 0, Idx1: i),
1007 isVolatile, IsAutoInit);
1008 }
1009}
1010
1011/// Decide whether we should use bzero plus some stores to initialize a local
1012/// variable instead of using a memcpy from a constant global. It is beneficial
1013/// to use bzero if the global is all zeros, or mostly zeros and large.
1014static bool shouldUseBZeroPlusStoresToInitialize(llvm::Constant *Init,
1015 uint64_t GlobalSize) {
1016 // If a global is all zeros, always use a bzero.
1017 if (isa<llvm::ConstantAggregateZero>(Val: Init)) return true;
1018
1019 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
1020 // do it if it will require 6 or fewer scalar stores.
1021 // TODO: Should budget depends on the size? Avoiding a large global warrants
1022 // plopping in more stores.
1023 unsigned StoreBudget = 6;
1024 uint64_t SizeLimit = 32;
1025
1026 return GlobalSize > SizeLimit &&
1027 canEmitInitWithFewStoresAfterBZero(Init, NumStores&: StoreBudget);
1028}
1029
1030/// Decide whether we should use memset to initialize a local variable instead
1031/// of using a memcpy from a constant global. Assumes we've already decided to
1032/// not user bzero.
1033/// FIXME We could be more clever, as we are for bzero above, and generate
1034/// memset followed by stores. It's unclear that's worth the effort.
1035static llvm::Value *shouldUseMemSetToInitialize(llvm::Constant *Init,
1036 uint64_t GlobalSize,
1037 const llvm::DataLayout &DL) {
1038 uint64_t SizeLimit = 32;
1039 if (GlobalSize <= SizeLimit)
1040 return nullptr;
1041 return llvm::isBytewiseValue(V: Init, DL);
1042}
1043
1044/// Decide whether we want to split a constant structure or array store into a
1045/// sequence of its fields' stores. This may cost us code size and compilation
1046/// speed, but plays better with store optimizations.
1047static bool shouldSplitConstantStore(CodeGenModule &CGM,
1048 uint64_t GlobalByteSize) {
1049 // Don't break things that occupy more than one cacheline.
1050 uint64_t ByteSizeLimit = 64;
1051 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
1052 return false;
1053 if (GlobalByteSize <= ByteSizeLimit)
1054 return true;
1055 return false;
1056}
1057
1058enum class IsPattern { No, Yes };
1059
1060/// Generate a constant filled with either a pattern or zeroes.
1061static llvm::Constant *patternOrZeroFor(CodeGenModule &CGM, IsPattern isPattern,
1062 llvm::Type *Ty) {
1063 if (isPattern == IsPattern::Yes)
1064 return initializationPatternFor(CGM, Ty);
1065 else
1066 return llvm::Constant::getNullValue(Ty);
1067}
1068
1069static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
1070 llvm::Constant *constant);
1071
1072/// Helper function for constWithPadding() to deal with padding in structures.
1073static llvm::Constant *constStructWithPadding(CodeGenModule &CGM,
1074 IsPattern isPattern,
1075 llvm::StructType *STy,
1076 llvm::Constant *constant) {
1077 const llvm::DataLayout &DL = CGM.getDataLayout();
1078 const llvm::StructLayout *Layout = DL.getStructLayout(Ty: STy);
1079 llvm::Type *Int8Ty = llvm::IntegerType::getInt8Ty(C&: CGM.getLLVMContext());
1080 unsigned SizeSoFar = 0;
1081 SmallVector<llvm::Constant *, 8> Values;
1082 bool NestedIntact = true;
1083 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1084 unsigned CurOff = Layout->getElementOffset(Idx: i);
1085 if (SizeSoFar < CurOff) {
1086 assert(!STy->isPacked());
1087 auto *PadTy = llvm::ArrayType::get(ElementType: Int8Ty, NumElements: CurOff - SizeSoFar);
1088 Values.push_back(Elt: patternOrZeroFor(CGM, isPattern, Ty: PadTy));
1089 }
1090 llvm::Constant *CurOp;
1091 if (constant->isNullValue())
1092 CurOp = llvm::Constant::getNullValue(Ty: STy->getElementType(N: i));
1093 else
1094 CurOp = cast<llvm::Constant>(Val: constant->getAggregateElement(Elt: i));
1095 auto *NewOp = constWithPadding(CGM, isPattern, constant: CurOp);
1096 if (CurOp != NewOp)
1097 NestedIntact = false;
1098 Values.push_back(Elt: NewOp);
1099 SizeSoFar = CurOff + DL.getTypeAllocSize(Ty: CurOp->getType());
1100 }
1101 unsigned TotalSize = Layout->getSizeInBytes();
1102 if (SizeSoFar < TotalSize) {
1103 auto *PadTy = llvm::ArrayType::get(ElementType: Int8Ty, NumElements: TotalSize - SizeSoFar);
1104 Values.push_back(Elt: patternOrZeroFor(CGM, isPattern, Ty: PadTy));
1105 }
1106 if (NestedIntact && Values.size() == STy->getNumElements())
1107 return constant;
1108 return llvm::ConstantStruct::getAnon(V: Values, Packed: STy->isPacked());
1109}
1110
1111/// Replace all padding bytes in a given constant with either a pattern byte or
1112/// 0x00.
1113static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
1114 llvm::Constant *constant) {
1115 llvm::Type *OrigTy = constant->getType();
1116 if (const auto STy = dyn_cast<llvm::StructType>(Val: OrigTy))
1117 return constStructWithPadding(CGM, isPattern, STy, constant);
1118 if (auto *ArrayTy = dyn_cast<llvm::ArrayType>(Val: OrigTy)) {
1119 llvm::SmallVector<llvm::Constant *, 8> Values;
1120 uint64_t Size = ArrayTy->getNumElements();
1121 if (!Size)
1122 return constant;
1123 llvm::Type *ElemTy = ArrayTy->getElementType();
1124 bool ZeroInitializer = constant->isNullValue();
1125 llvm::Constant *OpValue, *PaddedOp;
1126 if (ZeroInitializer) {
1127 OpValue = llvm::Constant::getNullValue(Ty: ElemTy);
1128 PaddedOp = constWithPadding(CGM, isPattern, constant: OpValue);
1129 }
1130 for (unsigned Op = 0; Op != Size; ++Op) {
1131 if (!ZeroInitializer) {
1132 OpValue = constant->getAggregateElement(Elt: Op);
1133 PaddedOp = constWithPadding(CGM, isPattern, constant: OpValue);
1134 }
1135 Values.push_back(Elt: PaddedOp);
1136 }
1137 auto *NewElemTy = Values[0]->getType();
1138 if (NewElemTy == ElemTy)
1139 return constant;
1140 auto *NewArrayTy = llvm::ArrayType::get(ElementType: NewElemTy, NumElements: Size);
1141 return llvm::ConstantArray::get(T: NewArrayTy, V: Values);
1142 }
1143 // FIXME: Add handling for tail padding in vectors. Vectors don't
1144 // have padding between or inside elements, but the total amount of
1145 // data can be less than the allocated size.
1146 return constant;
1147}
1148
1149Address CodeGenModule::createUnnamedGlobalFrom(const VarDecl &D,
1150 llvm::Constant *Constant,
1151 CharUnits Align) {
1152 auto FunctionName = [&](const DeclContext *DC) -> std::string {
1153 if (const auto *FD = dyn_cast<FunctionDecl>(Val: DC)) {
1154 if (const auto *CC = dyn_cast<CXXConstructorDecl>(Val: FD))
1155 return CC->getNameAsString();
1156 if (const auto *CD = dyn_cast<CXXDestructorDecl>(Val: FD))
1157 return CD->getNameAsString();
1158 return std::string(getMangledName(GD: FD));
1159 } else if (const auto *OM = dyn_cast<ObjCMethodDecl>(Val: DC)) {
1160 return OM->getNameAsString();
1161 } else if (isa<BlockDecl>(Val: DC)) {
1162 return "<block>";
1163 } else if (isa<CapturedDecl>(Val: DC)) {
1164 return "<captured>";
1165 } else {
1166 llvm_unreachable("expected a function or method");
1167 }
1168 };
1169
1170 // Form a simple per-variable cache of these values in case we find we
1171 // want to reuse them.
1172 llvm::GlobalVariable *&CacheEntry = InitializerConstants[&D];
1173 if (!CacheEntry || CacheEntry->getInitializer() != Constant) {
1174 auto *Ty = Constant->getType();
1175 bool isConstant = true;
1176 llvm::GlobalVariable *InsertBefore = nullptr;
1177 unsigned AS =
1178 getContext().getTargetAddressSpace(AS: GetGlobalConstantAddressSpace());
1179 std::string Name;
1180 if (D.hasGlobalStorage())
1181 Name = getMangledName(GD: &D).str() + ".const";
1182 else if (const DeclContext *DC = D.getParentFunctionOrMethod())
1183 Name = ("__const." + FunctionName(DC) + "." + D.getName()).str();
1184 else
1185 llvm_unreachable("local variable has no parent function or method");
1186 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1187 getModule(), Ty, isConstant, llvm::GlobalValue::PrivateLinkage,
1188 Constant, Name, InsertBefore, llvm::GlobalValue::NotThreadLocal, AS);
1189 GV->setAlignment(Align.getAsAlign());
1190 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1191 CacheEntry = GV;
1192 } else if (CacheEntry->getAlign().valueOrOne() < Align.getAsAlign()) {
1193 CacheEntry->setAlignment(Align.getAsAlign());
1194 }
1195
1196 return Address(CacheEntry, CacheEntry->getValueType(), Align);
1197}
1198
1199static Address createUnnamedGlobalForMemcpyFrom(CodeGenModule &CGM,
1200 const VarDecl &D,
1201 CGBuilderTy &Builder,
1202 llvm::Constant *Constant,
1203 CharUnits Align) {
1204 Address SrcPtr = CGM.createUnnamedGlobalFrom(D, Constant, Align);
1205 return SrcPtr.withElementType(ElemTy: CGM.Int8Ty);
1206}
1207
1208void CodeGenFunction::emitStoresForConstant(const VarDecl &D, Address Loc,
1209 bool isVolatile,
1210 llvm::Constant *constant,
1211 bool IsAutoInit) {
1212 auto *Ty = constant->getType();
1213 uint64_t ConstantSize = CGM.getDataLayout().getTypeAllocSize(Ty);
1214 if (!ConstantSize)
1215 return;
1216
1217 bool canDoSingleStore = Ty->isIntOrIntVectorTy() ||
1218 Ty->isPtrOrPtrVectorTy() || Ty->isFPOrFPVectorTy();
1219 if (canDoSingleStore) {
1220 auto *I = Builder.CreateStore(Val: constant, Addr: Loc, IsVolatile: isVolatile);
1221 addInstToCurrentSourceAtom(KeyInstruction: I, Backup: nullptr);
1222 if (IsAutoInit)
1223 I->addAnnotationMetadata(Annotation: "auto-init");
1224 return;
1225 }
1226
1227 auto *SizeVal = llvm::ConstantInt::get(Ty: CGM.IntPtrTy, V: ConstantSize);
1228
1229 // If the initializer is all or mostly the same, codegen with bzero / memset
1230 // then do a few stores afterward.
1231 if (shouldUseBZeroPlusStoresToInitialize(Init: constant, GlobalSize: ConstantSize)) {
1232 auto *I = Builder.CreateMemSet(Dest: Loc, Value: llvm::ConstantInt::get(Ty: CGM.Int8Ty, V: 0),
1233 Size: SizeVal, IsVolatile: isVolatile);
1234 addInstToCurrentSourceAtom(KeyInstruction: I, Backup: nullptr);
1235
1236 if (IsAutoInit)
1237 I->addAnnotationMetadata(Annotation: "auto-init");
1238
1239 bool valueAlreadyCorrect =
1240 constant->isNullValue() || isa<llvm::UndefValue>(Val: constant);
1241 if (!valueAlreadyCorrect) {
1242 Loc = Loc.withElementType(ElemTy: Ty);
1243 emitStoresForInitAfterBZero(Init: constant, Loc, isVolatile, IsAutoInit);
1244 }
1245 return;
1246 }
1247
1248 // If the initializer is a repeated byte pattern, use memset.
1249 llvm::Value *Pattern =
1250 shouldUseMemSetToInitialize(Init: constant, GlobalSize: ConstantSize, DL: CGM.getDataLayout());
1251 if (Pattern) {
1252 uint64_t Value = 0x00;
1253 if (!isa<llvm::UndefValue>(Val: Pattern)) {
1254 const llvm::APInt &AP = cast<llvm::ConstantInt>(Val: Pattern)->getValue();
1255 assert(AP.getBitWidth() <= 8);
1256 Value = AP.getLimitedValue();
1257 }
1258 auto *I = Builder.CreateMemSet(
1259 Dest: Loc, Value: llvm::ConstantInt::get(Ty: CGM.Int8Ty, V: Value), Size: SizeVal, IsVolatile: isVolatile);
1260 addInstToCurrentSourceAtom(KeyInstruction: I, Backup: nullptr);
1261 if (IsAutoInit)
1262 I->addAnnotationMetadata(Annotation: "auto-init");
1263 return;
1264 }
1265
1266 // If the initializer is small or trivialAutoVarInit is set, use a handful of
1267 // stores.
1268 bool IsTrivialAutoVarInitPattern =
1269 CGM.getContext().getLangOpts().getTrivialAutoVarInit() ==
1270 LangOptions::TrivialAutoVarInitKind::Pattern;
1271 if (shouldSplitConstantStore(CGM, GlobalByteSize: ConstantSize)) {
1272 if (auto *STy = dyn_cast<llvm::StructType>(Val: Ty)) {
1273 if (STy == Loc.getElementType() || IsTrivialAutoVarInitPattern) {
1274 const llvm::StructLayout *Layout =
1275 CGM.getDataLayout().getStructLayout(Ty: STy);
1276 for (unsigned i = 0; i != constant->getNumOperands(); i++) {
1277 CharUnits CurOff =
1278 CharUnits::fromQuantity(Quantity: Layout->getElementOffset(Idx: i));
1279 Address EltPtr = Builder.CreateConstInBoundsByteGEP(
1280 Addr: Loc.withElementType(ElemTy: CGM.Int8Ty), Offset: CurOff);
1281 emitStoresForConstant(D, Loc: EltPtr, isVolatile,
1282 constant: constant->getAggregateElement(Elt: i), IsAutoInit);
1283 }
1284 return;
1285 }
1286 } else if (auto *ATy = dyn_cast<llvm::ArrayType>(Val: Ty)) {
1287 if (ATy == Loc.getElementType() || IsTrivialAutoVarInitPattern) {
1288 for (unsigned i = 0; i != ATy->getNumElements(); i++) {
1289 Address EltPtr = Builder.CreateConstGEP(
1290 Addr: Loc.withElementType(ElemTy: ATy->getElementType()), Index: i);
1291 emitStoresForConstant(D, Loc: EltPtr, isVolatile,
1292 constant: constant->getAggregateElement(Elt: i), IsAutoInit);
1293 }
1294 return;
1295 }
1296 }
1297 }
1298
1299 // Copy from a global.
1300 auto *I =
1301 Builder.CreateMemCpy(Dest: Loc,
1302 Src: createUnnamedGlobalForMemcpyFrom(
1303 CGM, D, Builder, Constant: constant, Align: Loc.getAlignment()),
1304 Size: SizeVal, IsVolatile: isVolatile);
1305 addInstToCurrentSourceAtom(KeyInstruction: I, Backup: nullptr);
1306
1307 if (IsAutoInit)
1308 I->addAnnotationMetadata(Annotation: "auto-init");
1309}
1310
1311void CodeGenFunction::emitStoresForZeroInit(const VarDecl &D, Address Loc,
1312 bool isVolatile) {
1313 llvm::Type *ElTy = Loc.getElementType();
1314 llvm::Constant *constant =
1315 constWithPadding(CGM, isPattern: IsPattern::No, constant: llvm::Constant::getNullValue(Ty: ElTy));
1316 emitStoresForConstant(D, Loc, isVolatile, constant,
1317 /*IsAutoInit=*/true);
1318}
1319
1320void CodeGenFunction::emitStoresForPatternInit(const VarDecl &D, Address Loc,
1321 bool isVolatile) {
1322 llvm::Type *ElTy = Loc.getElementType();
1323 llvm::Constant *constant = constWithPadding(
1324 CGM, isPattern: IsPattern::Yes, constant: initializationPatternFor(CGM, ElTy));
1325 assert(!isa<llvm::UndefValue>(constant));
1326 emitStoresForConstant(D, Loc, isVolatile, constant,
1327 /*IsAutoInit=*/true);
1328}
1329
1330static bool containsUndef(llvm::Constant *constant) {
1331 auto *Ty = constant->getType();
1332 if (isa<llvm::UndefValue>(Val: constant))
1333 return true;
1334 if (Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy())
1335 for (llvm::Use &Op : constant->operands())
1336 if (containsUndef(constant: cast<llvm::Constant>(Val&: Op)))
1337 return true;
1338 return false;
1339}
1340
1341static llvm::Constant *replaceUndef(CodeGenModule &CGM, IsPattern isPattern,
1342 llvm::Constant *constant) {
1343 auto *Ty = constant->getType();
1344 if (isa<llvm::UndefValue>(Val: constant))
1345 return patternOrZeroFor(CGM, isPattern, Ty);
1346 if (!(Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()))
1347 return constant;
1348 if (!containsUndef(constant))
1349 return constant;
1350 llvm::SmallVector<llvm::Constant *, 8> Values(constant->getNumOperands());
1351 for (unsigned Op = 0, NumOp = constant->getNumOperands(); Op != NumOp; ++Op) {
1352 auto *OpValue = cast<llvm::Constant>(Val: constant->getOperand(i: Op));
1353 Values[Op] = replaceUndef(CGM, isPattern, constant: OpValue);
1354 }
1355 if (Ty->isStructTy())
1356 return llvm::ConstantStruct::get(T: cast<llvm::StructType>(Val: Ty), V: Values);
1357 if (Ty->isArrayTy())
1358 return llvm::ConstantArray::get(T: cast<llvm::ArrayType>(Val: Ty), V: Values);
1359 assert(Ty->isVectorTy());
1360 return llvm::ConstantVector::get(V: Values);
1361}
1362
1363/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
1364/// variable declaration with auto, register, or no storage class specifier.
1365/// These turn into simple stack objects, or GlobalValues depending on target.
1366void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
1367 AutoVarEmission emission = EmitAutoVarAlloca(var: D);
1368 EmitAutoVarInit(emission);
1369 EmitAutoVarCleanups(emission);
1370}
1371
1372/// Emit a lifetime.begin marker if some criteria are satisfied.
1373/// \return whether the marker was emitted.
1374bool CodeGenFunction::EmitLifetimeStart(llvm::Value *Addr) {
1375 if (!ShouldEmitLifetimeMarkers)
1376 return false;
1377
1378 assert(Addr->getType()->getPointerAddressSpace() ==
1379 CGM.getDataLayout().getAllocaAddrSpace() &&
1380 "Pointer should be in alloca address space");
1381 Builder.CreateCall(Callee: CGM.getLLVMLifetimeStartFn(), Args: {Addr});
1382 return true;
1383}
1384
1385void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Addr) {
1386 if (!ShouldEmitLifetimeMarkers)
1387 return;
1388
1389 assert(Addr->getType()->getPointerAddressSpace() ==
1390 CGM.getDataLayout().getAllocaAddrSpace() &&
1391 "Pointer should be in alloca address space");
1392 Builder.CreateCall(Callee: CGM.getLLVMLifetimeEndFn(), Args: {Addr});
1393}
1394
1395void CodeGenFunction::EmitFakeUse(Address Addr) {
1396 auto NL = ApplyDebugLocation::CreateEmpty(CGF&: *this);
1397 llvm::Value *V = Builder.CreateLoad(Addr, Name: "fake.use");
1398 llvm::CallInst *C = Builder.CreateCall(Callee: CGM.getLLVMFakeUseFn(), Args: {V});
1399 C->setTailCallKind(llvm::CallInst::TCK_NoTail);
1400}
1401
1402void CodeGenFunction::EmitAndRegisterVariableArrayDimensions(
1403 CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo) {
1404 // For each dimension stores its QualType and corresponding
1405 // size-expression Value.
1406 SmallVector<CodeGenFunction::VlaSizePair, 4> Dimensions;
1407 SmallVector<const IdentifierInfo *, 4> VLAExprNames;
1408
1409 // Break down the array into individual dimensions.
1410 QualType Type1D = D.getType();
1411 while (getContext().getAsVariableArrayType(T: Type1D)) {
1412 auto VlaSize = getVLAElements1D(vla: Type1D);
1413 if (auto *C = dyn_cast<llvm::ConstantInt>(Val: VlaSize.NumElts))
1414 Dimensions.emplace_back(Args&: C, Args: Type1D.getUnqualifiedType());
1415 else {
1416 // Generate a locally unique name for the size expression.
1417 Twine Name = Twine("__vla_expr") + Twine(VLAExprCounter++);
1418 SmallString<12> Buffer;
1419 StringRef NameRef = Name.toStringRef(Out&: Buffer);
1420 auto &Ident = getContext().Idents.getOwn(Name: NameRef);
1421 VLAExprNames.push_back(Elt: &Ident);
1422 auto SizeExprAddr =
1423 CreateDefaultAlignTempAlloca(Ty: VlaSize.NumElts->getType(), Name: NameRef);
1424 Builder.CreateStore(Val: VlaSize.NumElts, Addr: SizeExprAddr);
1425 Dimensions.emplace_back(Args: SizeExprAddr.getPointer(),
1426 Args: Type1D.getUnqualifiedType());
1427 }
1428 Type1D = VlaSize.Type;
1429 }
1430
1431 if (!EmitDebugInfo)
1432 return;
1433
1434 // Register each dimension's size-expression with a DILocalVariable,
1435 // so that it can be used by CGDebugInfo when instantiating a DISubrange
1436 // to describe this array.
1437 unsigned NameIdx = 0;
1438 for (auto &VlaSize : Dimensions) {
1439 llvm::Metadata *MD;
1440 if (auto *C = dyn_cast<llvm::ConstantInt>(Val: VlaSize.NumElts))
1441 MD = llvm::ConstantAsMetadata::get(C);
1442 else {
1443 // Create an artificial VarDecl to generate debug info for.
1444 const IdentifierInfo *NameIdent = VLAExprNames[NameIdx++];
1445 auto QT = getContext().getIntTypeForBitwidth(
1446 DestWidth: SizeTy->getScalarSizeInBits(), Signed: false);
1447 auto *ArtificialDecl = VarDecl::Create(
1448 C&: getContext(), DC: const_cast<DeclContext *>(D.getDeclContext()),
1449 StartLoc: D.getLocation(), IdLoc: D.getLocation(), Id: NameIdent, T: QT,
1450 TInfo: getContext().CreateTypeSourceInfo(T: QT), S: SC_Auto);
1451 ArtificialDecl->setImplicit();
1452
1453 MD = DI->EmitDeclareOfAutoVariable(Decl: ArtificialDecl, AI: VlaSize.NumElts,
1454 Builder);
1455 }
1456 assert(MD && "No Size expression debug node created");
1457 DI->registerVLASizeExpression(Ty: VlaSize.Type, SizeExpr: MD);
1458 }
1459}
1460
1461/// Return the maximum size of an aggregate for which we generate a fake use
1462/// intrinsic when -fextend-variable-liveness is in effect.
1463static uint64_t maxFakeUseAggregateSize(const ASTContext &C) {
1464 return 4 * C.getTypeSize(T: C.UnsignedIntTy);
1465}
1466
1467// Helper function to determine whether a variable's or parameter's lifetime
1468// should be extended.
1469static bool shouldExtendLifetime(const ASTContext &Context,
1470 const Decl *FuncDecl, const VarDecl &D,
1471 ImplicitParamDecl *CXXABIThisDecl) {
1472 // When we're not inside a valid function it is unlikely that any
1473 // lifetime extension is useful.
1474 if (!FuncDecl)
1475 return false;
1476 if (FuncDecl->isImplicit())
1477 return false;
1478 // Do not extend compiler-created variables except for the this pointer.
1479 if (D.isImplicit() && &D != CXXABIThisDecl)
1480 return false;
1481 QualType Ty = D.getType();
1482 // No need to extend volatiles, they have a memory location.
1483 if (Ty.isVolatileQualified())
1484 return false;
1485 // Don't extend variables that exceed a certain size.
1486 if (Context.getTypeSize(T: Ty) > maxFakeUseAggregateSize(C: Context))
1487 return false;
1488 // Do not extend variables in nodebug or optnone functions.
1489 if (FuncDecl->hasAttr<NoDebugAttr>() || FuncDecl->hasAttr<OptimizeNoneAttr>())
1490 return false;
1491 return true;
1492}
1493
1494/// EmitAutoVarAlloca - Emit the alloca and debug information for a
1495/// local variable. Does not emit initialization or destruction.
1496CodeGenFunction::AutoVarEmission
1497CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
1498 QualType Ty = D.getType();
1499 assert(
1500 Ty.getAddressSpace() == LangAS::Default ||
1501 (Ty.getAddressSpace() == LangAS::opencl_private && getLangOpts().OpenCL));
1502
1503 AutoVarEmission emission(D);
1504
1505 bool isEscapingByRef = D.isEscapingByref();
1506 emission.IsEscapingByRef = isEscapingByRef;
1507
1508 CharUnits alignment = getContext().getDeclAlign(D: &D);
1509
1510 // If the type is variably-modified, emit all the VLA sizes for it.
1511 if (Ty->isVariablyModifiedType())
1512 EmitVariablyModifiedType(Ty);
1513
1514 auto *DI = getDebugInfo();
1515 bool EmitDebugInfo = DI && CGM.getCodeGenOpts().hasReducedDebugInfo();
1516
1517 Address address = Address::invalid();
1518 RawAddress AllocaAddr = RawAddress::invalid();
1519 Address OpenMPLocalAddr = Address::invalid();
1520 if (CGM.getLangOpts().OpenMPIRBuilder)
1521 OpenMPLocalAddr = OMPBuilderCBHelpers::getAddressOfLocalVariable(CGF&: *this, VD: &D);
1522 else
1523 OpenMPLocalAddr =
1524 getLangOpts().OpenMP
1525 ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(CGF&: *this, VD: &D)
1526 : Address::invalid();
1527
1528 bool NRVO = getLangOpts().ElideConstructors && D.isNRVOVariable();
1529
1530 if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
1531 address = OpenMPLocalAddr;
1532 AllocaAddr = OpenMPLocalAddr;
1533 } else if (Ty->isConstantSizeType()) {
1534 // If this value is an array or struct with a statically determinable
1535 // constant initializer, there are optimizations we can do.
1536 //
1537 // TODO: We should be able to delete most of the restrictions here; there's
1538 // no reason we specifically need a POD array/record type. But we'd need to
1539 // evaluate the performance, update regression tests, and fix a crash with
1540 // OpenMP.
1541 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
1542 (D.isConstexpr() ||
1543 ((Ty.isPODType(Context: getContext()) ||
1544 getContext().getBaseElementType(QT: Ty)->isObjCObjectPointerType())))) {
1545 emission.ConstantAggregateInitializer =
1546 ConstantEmitter(*this).tryEmitAbstractForInitializer(D);
1547 if (emission.ConstantAggregateInitializer) {
1548 // If the variable's a const type, and it's neither an NRVO
1549 // candidate nor a __block variable and has no mutable members,
1550 // emit it as a global instead.
1551 // Exception is if a variable is located in non-constant address space
1552 // in OpenCL.
1553 bool NeedsDtor =
1554 D.needsDestruction(Ctx: getContext()) == QualType::DK_cxx_destructor;
1555 if ((!getLangOpts().OpenCL ||
1556 Ty.getAddressSpace() == LangAS::opencl_constant) &&
1557 (CGM.getCodeGenOpts().MergeAllConstants && !NRVO &&
1558 !isEscapingByRef &&
1559 Ty.isConstantStorage(Ctx: getContext(), ExcludeCtor: true, ExcludeDtor: !NeedsDtor))) {
1560 EmitStaticVarDecl(D, Linkage: llvm::GlobalValue::InternalLinkage);
1561
1562 // Signal this condition to later callbacks.
1563 emission.Addr = Address::invalid();
1564 assert(emission.wasEmittedAsGlobal());
1565 return emission;
1566 }
1567 }
1568 }
1569
1570 // A normal fixed sized variable becomes an alloca in the entry block,
1571 // unless:
1572 // - it's an NRVO variable.
1573 // - we are compiling OpenMP and it's an OpenMP local variable.
1574 if (NRVO) {
1575 // The named return value optimization: allocate this variable in the
1576 // return slot, so that we can elide the copy when returning this
1577 // variable (C++0x [class.copy]p34).
1578 AllocaAddr =
1579 RawAddress(ReturnValue.emitRawPointer(CGF&: *this),
1580 ReturnValue.getElementType(), ReturnValue.getAlignment());
1581 address = MaybeCastStackAddressSpace(Alloca: AllocaAddr, DestLangAS: Ty.getAddressSpace());
1582
1583 if (const auto *RD = Ty->getAsRecordDecl()) {
1584 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD);
1585 (CXXRD && !CXXRD->hasTrivialDestructor()) ||
1586 RD->isNonTrivialToPrimitiveDestroy()) {
1587 // Create a flag that is used to indicate when the NRVO was applied
1588 // to this variable. Set it to zero to indicate that NRVO was not
1589 // applied.
1590 llvm::Value *Zero = Builder.getFalse();
1591 RawAddress NRVOFlag =
1592 CreateTempAlloca(Ty: Zero->getType(), align: CharUnits::One(), Name: "nrvo");
1593 EnsureInsertPoint();
1594 Builder.CreateStore(Val: Zero, Addr: NRVOFlag);
1595
1596 // Record the NRVO flag for this variable.
1597 NRVOFlags[&D] = NRVOFlag.getPointer();
1598 emission.NRVOFlag = NRVOFlag.getPointer();
1599 }
1600 }
1601 } else {
1602 CharUnits allocaAlignment;
1603 llvm::Type *allocaTy;
1604 if (isEscapingByRef) {
1605 auto &byrefInfo = getBlockByrefInfo(var: &D);
1606 allocaTy = byrefInfo.Type;
1607 allocaAlignment = byrefInfo.ByrefAlignment;
1608 } else {
1609 allocaTy = ConvertTypeForMem(T: Ty);
1610 allocaAlignment = alignment;
1611 }
1612
1613 // Create the alloca. Note that we set the name separately from
1614 // building the instruction so that it's there even in no-asserts
1615 // builds.
1616 address = CreateTempAlloca(Ty: allocaTy, UseAddrSpace: Ty.getAddressSpace(),
1617 align: allocaAlignment, Name: D.getName(),
1618 /*ArraySize=*/nullptr, Alloca: &AllocaAddr);
1619
1620 // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1621 // the catch parameter starts in the catchpad instruction, and we can't
1622 // insert code in those basic blocks.
1623 bool IsMSCatchParam =
1624 D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1625
1626 // Emit a lifetime intrinsic if meaningful. There's no point in doing this
1627 // if we don't have a valid insertion point (?).
1628 if (HaveInsertPoint() && !IsMSCatchParam) {
1629 // If there's a jump into the lifetime of this variable, its lifetime
1630 // gets broken up into several regions in IR, which requires more work
1631 // to handle correctly. For now, just omit the intrinsics; this is a
1632 // rare case, and it's better to just be conservatively correct.
1633 // PR28267.
1634 //
1635 // We have to do this in all language modes if there's a jump past the
1636 // declaration. We also have to do it in C if there's a jump to an
1637 // earlier point in the current block because non-VLA lifetimes begin as
1638 // soon as the containing block is entered, not when its variables
1639 // actually come into scope; suppressing the lifetime annotations
1640 // completely in this case is unnecessarily pessimistic, but again, this
1641 // is rare.
1642 if (!Bypasses.IsBypassed(D: &D) &&
1643 !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
1644 emission.UseLifetimeMarkers =
1645 EmitLifetimeStart(Addr: AllocaAddr.getPointer());
1646 }
1647 } else {
1648 assert(!emission.useLifetimeMarkers());
1649 }
1650 }
1651
1652 // A variable whose declaration is bypassed by a goto or switch is not
1653 // initialized by EmitAutoVarInit, which runs at the declaration. Emit the
1654 // trivial-auto-var-init separately.
1655 if (Bypasses.IsBypassed(D: &D) && !emission.IsEscapingByRef &&
1656 !Ty->isVariablyModifiedType() &&
1657 getAutoVarInitKind(Ty, D) !=
1658 LangOptions::TrivialAutoVarInitKind::Uninitialized) {
1659 if (!Bypasses.isAlwaysBypassed()) {
1660 // The variable's lifetime restarts on each re-entry into its scope, so
1661 // reinitialize at every bypassing jump. Backward gotos are emitted at
1662 // the jump source, which comes after this alloca; forward gotos and the
1663 // switch dispatch have already been emitted, so patch their init in
1664 // before the jump.
1665 BypassedVarInits.insert(KV: {&D, address});
1666 for (const BypassingForwardJump &FG : BypassingForwardJumps) {
1667 const auto *Vars = Bypasses.getBypassedVarsForSource(Source: FG.Source);
1668 if (!Vars || !Vars->contains(key: &D))
1669 continue;
1670 llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
1671 Builder.SetInsertPoint(FG.Block->getTerminator());
1672 emitZeroOrPatternForAutoVarInit(type: Ty, D, Loc: address);
1673 }
1674 } else {
1675 // A computed goto can jump anywhere, so we can't identify the jumps
1676 // that bypass this declaration. Fall back to initializing once, in the
1677 // function's entry block.
1678 llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
1679 Builder.SetInsertPoint(getPostAllocaInsertPoint());
1680 emitZeroOrPatternForAutoVarInit(type: Ty, D, Loc: address);
1681 }
1682 }
1683
1684 if (D.hasAttr<StackProtectorIgnoreAttr>()) {
1685 if (auto *AI = dyn_cast<llvm::AllocaInst>(Val: address.getBasePointer())) {
1686 llvm::LLVMContext &Ctx = Builder.getContext();
1687 auto *Operand = llvm::ConstantAsMetadata::get(C: Builder.getInt32(C: 0));
1688 AI->setMetadata(Kind: "stack-protector", Node: llvm::MDNode::get(Context&: Ctx, MDs: {Operand}));
1689 }
1690
1691 std::optional<llvm::Attribute::AttrKind> Attr =
1692 CGM.StackProtectorAttribute(D: &D);
1693 if (Attr && (*Attr == llvm::Attribute::StackProtectReq)) {
1694 CGM.getDiags().Report(Loc: D.getLocation(),
1695 DiagID: diag::warn_stack_protection_ignore_attribute);
1696 }
1697 }
1698 } else {
1699 EnsureInsertPoint();
1700
1701 // Delayed globalization for variable length declarations. This ensures that
1702 // the expression representing the length has been emitted and can be used
1703 // by the definition of the VLA. Since this is an escaped declaration, in
1704 // OpenMP we have to use a call to __kmpc_alloc_shared(). The matching
1705 // deallocation call to __kmpc_free_shared() is emitted later.
1706 bool VarAllocated = false;
1707 if (getLangOpts().OpenMPIsTargetDevice) {
1708 auto &RT = CGM.getOpenMPRuntime();
1709 if (RT.isDelayedVariableLengthDecl(CGF&: *this, VD: &D)) {
1710 // Emit call to __kmpc_alloc_shared() instead of the alloca.
1711 std::pair<llvm::Value *, llvm::Value *> AddrSizePair =
1712 RT.getKmpcAllocShared(CGF&: *this, VD: &D);
1713
1714 // Save the address of the allocation:
1715 LValue Base = MakeAddrLValue(V: AddrSizePair.first, T: D.getType(),
1716 Alignment: CGM.getContext().getDeclAlign(D: &D),
1717 Source: AlignmentSource::Decl);
1718 address = Base.getAddress();
1719
1720 // Push a cleanup block to emit the call to __kmpc_free_shared in the
1721 // appropriate location at the end of the scope of the
1722 // __kmpc_alloc_shared functions:
1723 pushKmpcAllocFree(Kind: NormalCleanup, AddrSizePair);
1724
1725 // Mark variable as allocated:
1726 VarAllocated = true;
1727 }
1728 }
1729
1730 if (!VarAllocated) {
1731 if (!DidCallStackSave) {
1732 // Save the stack.
1733 Address Stack =
1734 CreateDefaultAlignTempAlloca(Ty: AllocaInt8PtrTy, Name: "saved_stack");
1735
1736 llvm::Value *V = Builder.CreateStackSave();
1737 assert(V->getType() == AllocaInt8PtrTy);
1738 Builder.CreateStore(Val: V, Addr: Stack);
1739
1740 DidCallStackSave = true;
1741
1742 // Push a cleanup block and restore the stack there.
1743 // FIXME: in general circumstances, this should be an EH cleanup.
1744 pushStackRestore(kind: NormalCleanup, SPMem: Stack);
1745 }
1746
1747 auto VlaSize = getVLASize(vla: Ty);
1748 llvm::Type *llvmTy = ConvertTypeForMem(T: VlaSize.Type);
1749
1750 // Allocate memory for the array.
1751 address = CreateTempAlloca(Ty: llvmTy, align: alignment, Name: "vla", ArraySize: VlaSize.NumElts,
1752 Alloca: &AllocaAddr);
1753 }
1754
1755 // If we have debug info enabled, properly describe the VLA dimensions for
1756 // this type by registering the vla size expression for each of the
1757 // dimensions.
1758 EmitAndRegisterVariableArrayDimensions(DI, D, EmitDebugInfo);
1759 }
1760
1761 setAddrOfLocalVar(VD: &D, Addr: address);
1762 emission.Addr = address;
1763 emission.AllocaAddr = AllocaAddr;
1764
1765 // Emit debug info for local var declaration.
1766 if (EmitDebugInfo && HaveInsertPoint()) {
1767 Address DebugAddr = address;
1768 bool UsePointerValue = NRVO && ReturnValuePointer.isValid();
1769 DI->setLocation(D.getLocation());
1770
1771 // If NRVO, use a pointer to the return address.
1772 if (UsePointerValue) {
1773 DebugAddr = ReturnValuePointer;
1774 AllocaAddr = ReturnValuePointer;
1775 }
1776 (void)DI->EmitDeclareOfAutoVariable(Decl: &D, AI: AllocaAddr.getPointer(), Builder,
1777 UsePointerValue);
1778 }
1779
1780 if (D.hasAttr<AnnotateAttr>() && HaveInsertPoint())
1781 EmitVarAnnotations(D: &D, V: address.emitRawPointer(CGF&: *this));
1782
1783 // Make sure we call @llvm.lifetime.end.
1784 if (emission.useLifetimeMarkers())
1785 EHStack.pushCleanup<CallLifetimeEnd>(
1786 Kind: NormalEHLifetimeMarker, A: emission.getOriginalAllocatedAddress());
1787
1788 // Analogous to lifetime markers, we use a 'cleanup' to emit fake.use
1789 // calls for local variables. We are exempting volatile variables and
1790 // non-scalars larger than 4 times the size of an unsigned int. Larger
1791 // non-scalars are often allocated in memory and may create unnecessary
1792 // overhead.
1793 if (CGM.getCodeGenOpts().getExtendVariableLiveness() ==
1794 CodeGenOptions::ExtendVariableLivenessKind::All) {
1795 if (shouldExtendLifetime(Context: getContext(), FuncDecl: CurCodeDecl, D, CXXABIThisDecl))
1796 EHStack.pushCleanup<FakeUse>(Kind: NormalFakeUse,
1797 A: emission.getAllocatedAddress());
1798 }
1799
1800 return emission;
1801}
1802
1803static bool isCapturedBy(const VarDecl &, const Expr *);
1804
1805/// Determines whether the given __block variable is potentially
1806/// captured by the given statement.
1807static bool isCapturedBy(const VarDecl &Var, const Stmt *S) {
1808 if (const Expr *E = dyn_cast<Expr>(Val: S))
1809 return isCapturedBy(Var, E);
1810 for (const Stmt *SubStmt : S->children())
1811 if (isCapturedBy(Var, S: SubStmt))
1812 return true;
1813 return false;
1814}
1815
1816/// Determines whether the given __block variable is potentially
1817/// captured by the given expression.
1818static bool isCapturedBy(const VarDecl &Var, const Expr *E) {
1819 // Skip the most common kinds of expressions that make
1820 // hierarchy-walking expensive.
1821 E = E->IgnoreParenCasts();
1822
1823 if (const BlockExpr *BE = dyn_cast<BlockExpr>(Val: E)) {
1824 const BlockDecl *Block = BE->getBlockDecl();
1825 for (const auto &I : Block->captures()) {
1826 if (I.getVariable() == &Var)
1827 return true;
1828 }
1829
1830 // No need to walk into the subexpressions.
1831 return false;
1832 }
1833
1834 if (const StmtExpr *SE = dyn_cast<StmtExpr>(Val: E)) {
1835 const CompoundStmt *CS = SE->getSubStmt();
1836 for (const auto *BI : CS->body())
1837 if (const auto *BIE = dyn_cast<Expr>(Val: BI)) {
1838 if (isCapturedBy(Var, E: BIE))
1839 return true;
1840 }
1841 else if (const auto *DS = dyn_cast<DeclStmt>(Val: BI)) {
1842 // special case declarations
1843 for (const auto *I : DS->decls()) {
1844 if (const auto *VD = dyn_cast<VarDecl>(Val: (I))) {
1845 const Expr *Init = VD->getInit();
1846 if (Init && isCapturedBy(Var, E: Init))
1847 return true;
1848 }
1849 }
1850 }
1851 else
1852 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1853 // Later, provide code to poke into statements for capture analysis.
1854 return true;
1855 return false;
1856 }
1857
1858 for (const Stmt *SubStmt : E->children())
1859 if (isCapturedBy(Var, S: SubStmt))
1860 return true;
1861
1862 return false;
1863}
1864
1865/// Determine whether the given initializer is trivial in the sense
1866/// that it requires no code to be generated.
1867bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
1868 if (!Init)
1869 return true;
1870
1871 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Val: Init))
1872 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1873 if (Constructor->isTrivial() &&
1874 Constructor->isDefaultConstructor() &&
1875 !Construct->requiresZeroInitialization())
1876 return true;
1877
1878 return false;
1879}
1880
1881LangOptions::TrivialAutoVarInitKind
1882CodeGenFunction::getAutoVarInitKind(QualType Ty, const VarDecl &D) {
1883 auto hasNoTrivialAutoVarInitAttr = [](const Decl *D) {
1884 return D && D->hasAttr<NoTrivialAutoVarInitAttr>();
1885 };
1886 if (D.isConstexpr() || D.getAttr<UninitializedAttr>() ||
1887 hasNoTrivialAutoVarInitAttr(Ty->getAsTagDecl()) ||
1888 hasNoTrivialAutoVarInitAttr(CurFuncDecl))
1889 return LangOptions::TrivialAutoVarInitKind::Uninitialized;
1890 return getContext().getLangOpts().getTrivialAutoVarInit();
1891}
1892
1893void CodeGenFunction::emitBypassedVarInitsForSource(const Stmt *Source) {
1894 // Scope-reentry reinit is only sound when jump sources are known. With a
1895 // computed goto we can't tell whether a jump leaves a variable's scope, so
1896 // EmitAutoVarAlloca falls back to a single function-scope init and we must
1897 // not reinitialize here -- doing so could clobber a still-live variable.
1898 if (Bypasses.isAlwaysBypassed())
1899 return;
1900 const auto *Vars = Bypasses.getBypassedVarsForSource(Source);
1901 if (!Vars)
1902 return;
1903 for (const VarDecl *VD : *Vars) {
1904 auto It = BypassedVarInits.find(Val: VD);
1905 if (It != BypassedVarInits.end())
1906 emitZeroOrPatternForAutoVarInit(type: VD->getType(), D: *VD, Loc: It->second);
1907 }
1908}
1909
1910void CodeGenFunction::emitZeroOrPatternForAutoVarInit(QualType type,
1911 const VarDecl &D,
1912 Address Loc) {
1913 auto trivialAutoVarInit = getContext().getLangOpts().getTrivialAutoVarInit();
1914 auto trivialAutoVarInitMaxSize =
1915 getContext().getLangOpts().TrivialAutoVarInitMaxSize;
1916 CharUnits Size = getContext().getTypeSizeInChars(T: type);
1917 bool isVolatile = type.isVolatileQualified();
1918 if (!Size.isZero()) {
1919 // We skip auto-init variables by their alloc size. Take this as an example:
1920 // "struct Foo {int x; char buff[1024];}" Assume the max-size flag is 1023.
1921 // All Foo type variables will be skipped. Ideally, we only skip the buff
1922 // array and still auto-init X in this example.
1923 // TODO: Improve the size filtering to by member size.
1924 auto allocSize = CGM.getDataLayout().getTypeAllocSize(Ty: Loc.getElementType());
1925 switch (trivialAutoVarInit) {
1926 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
1927 llvm_unreachable("Uninitialized handled by caller");
1928 case LangOptions::TrivialAutoVarInitKind::Zero:
1929 if (CGM.stopAutoInit())
1930 return;
1931 if (trivialAutoVarInitMaxSize > 0 &&
1932 allocSize > trivialAutoVarInitMaxSize)
1933 return;
1934 emitStoresForZeroInit(D, Loc, isVolatile);
1935 break;
1936 case LangOptions::TrivialAutoVarInitKind::Pattern:
1937 if (CGM.stopAutoInit())
1938 return;
1939 if (trivialAutoVarInitMaxSize > 0 &&
1940 allocSize > trivialAutoVarInitMaxSize)
1941 return;
1942 emitStoresForPatternInit(D, Loc, isVolatile);
1943 break;
1944 }
1945 return;
1946 }
1947
1948 // VLAs look zero-sized to getTypeInfo. We can't emit constant stores to
1949 // them, so emit a memcpy with the VLA size to initialize each element.
1950 // Technically zero-sized or negative-sized VLAs are undefined, and UBSan
1951 // will catch that code, but there exists code which generates zero-sized
1952 // VLAs. Be nice and initialize whatever they requested.
1953 const auto *VlaType = getContext().getAsVariableArrayType(T: type);
1954 if (!VlaType)
1955 return;
1956 auto VlaSize = getVLASize(vla: VlaType);
1957 auto SizeVal = VlaSize.NumElts;
1958 CharUnits EltSize = getContext().getTypeSizeInChars(T: VlaSize.Type);
1959 switch (trivialAutoVarInit) {
1960 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
1961 llvm_unreachable("Uninitialized handled by caller");
1962
1963 case LangOptions::TrivialAutoVarInitKind::Zero: {
1964 if (CGM.stopAutoInit())
1965 return;
1966 if (!EltSize.isOne())
1967 SizeVal = Builder.CreateNUWMul(LHS: SizeVal, RHS: CGM.getSize(numChars: EltSize));
1968 auto *I = Builder.CreateMemSet(Dest: Loc, Value: llvm::ConstantInt::get(Ty: Int8Ty, V: 0),
1969 Size: SizeVal, IsVolatile: isVolatile);
1970 I->addAnnotationMetadata(Annotation: "auto-init");
1971 break;
1972 }
1973
1974 case LangOptions::TrivialAutoVarInitKind::Pattern: {
1975 if (CGM.stopAutoInit())
1976 return;
1977 llvm::Type *ElTy = Loc.getElementType();
1978 llvm::Constant *Constant = constWithPadding(
1979 CGM, isPattern: IsPattern::Yes, constant: initializationPatternFor(CGM, ElTy));
1980 CharUnits ConstantAlign = getContext().getTypeAlignInChars(T: VlaSize.Type);
1981 llvm::BasicBlock *SetupBB = createBasicBlock(name: "vla-setup.loop");
1982 llvm::BasicBlock *LoopBB = createBasicBlock(name: "vla-init.loop");
1983 llvm::BasicBlock *ContBB = createBasicBlock(name: "vla-init.cont");
1984 llvm::Value *IsZeroSizedVLA = Builder.CreateICmpEQ(
1985 LHS: SizeVal, RHS: llvm::ConstantInt::get(Ty: SizeVal->getType(), V: 0),
1986 Name: "vla.iszerosized");
1987 Builder.CreateCondBr(Cond: IsZeroSizedVLA, True: ContBB, False: SetupBB);
1988 EmitBlock(BB: SetupBB);
1989 if (!EltSize.isOne())
1990 SizeVal = Builder.CreateNUWMul(LHS: SizeVal, RHS: CGM.getSize(numChars: EltSize));
1991 llvm::Value *BaseSizeInChars =
1992 llvm::ConstantInt::get(Ty: IntPtrTy, V: EltSize.getQuantity());
1993 Address Begin = Loc.withElementType(ElemTy: Int8Ty);
1994 llvm::Value *End = Builder.CreateInBoundsGEP(Ty: Begin.getElementType(),
1995 Ptr: Begin.emitRawPointer(CGF&: *this),
1996 IdxList: SizeVal, Name: "vla.end");
1997 llvm::BasicBlock *OriginBB = Builder.GetInsertBlock();
1998 EmitBlock(BB: LoopBB);
1999 llvm::PHINode *Cur = Builder.CreatePHI(Ty: Begin.getType(), NumReservedValues: 2, Name: "vla.cur");
2000 Cur->addIncoming(V: Begin.emitRawPointer(CGF&: *this), BB: OriginBB);
2001 CharUnits CurAlign = Loc.getAlignment().alignmentOfArrayElement(elementSize: EltSize);
2002 auto *I =
2003 Builder.CreateMemCpy(Dest: Address(Cur, Int8Ty, CurAlign),
2004 Src: createUnnamedGlobalForMemcpyFrom(
2005 CGM, D, Builder, Constant, Align: ConstantAlign),
2006 Size: BaseSizeInChars, IsVolatile: isVolatile);
2007 I->addAnnotationMetadata(Annotation: "auto-init");
2008 llvm::Value *Next =
2009 Builder.CreateInBoundsGEP(Ty: Int8Ty, Ptr: Cur, IdxList: BaseSizeInChars, Name: "vla.next");
2010 llvm::Value *Done = Builder.CreateICmpEQ(LHS: Next, RHS: End, Name: "vla-init.isdone");
2011 Builder.CreateCondBr(Cond: Done, True: ContBB, False: LoopBB);
2012 Cur->addIncoming(V: Next, BB: LoopBB);
2013 EmitBlock(BB: ContBB);
2014 } break;
2015 }
2016}
2017
2018void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
2019 assert(emission.Variable && "emission was not valid!");
2020
2021 // If this was emitted as a global constant, we're done.
2022 if (emission.wasEmittedAsGlobal()) return;
2023
2024 const VarDecl &D = *emission.Variable;
2025 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF&: *this, TemporaryLocation: D.getLocation());
2026 ApplyAtomGroup Grp(getDebugInfo());
2027 QualType type = D.getType();
2028
2029 // If this local has an initializer, emit it now.
2030 const Expr *Init = D.getInit();
2031
2032 // If we are at an unreachable point, we don't need to emit the initializer
2033 // unless it contains a label.
2034 if (!HaveInsertPoint()) {
2035 if (!Init || !ContainsLabel(S: Init)) {
2036 PGO->markStmtMaybeUsed(S: Init);
2037 return;
2038 }
2039 EnsureInsertPoint();
2040 }
2041
2042 // Initialize the structure of a __block variable.
2043 if (emission.IsEscapingByRef)
2044 emitByrefStructureInit(emission);
2045
2046 // Initialize the variable here if it doesn't have a initializer and it is a
2047 // C struct that is non-trivial to initialize or an array containing such a
2048 // struct.
2049 if (!Init &&
2050 type.isNonTrivialToPrimitiveDefaultInitialize() ==
2051 QualType::PDIK_Struct) {
2052 LValue Dst = MakeAddrLValue(Addr: emission.getAllocatedAddress(), T: type);
2053 if (emission.IsEscapingByRef)
2054 drillIntoBlockVariable(CGF&: *this, lvalue&: Dst, var: &D);
2055 defaultInitNonTrivialCStructVar(Dst);
2056 return;
2057 }
2058
2059 // Check whether this is a byref variable that's potentially
2060 // captured and moved by its own initializer. If so, we'll need to
2061 // emit the initializer first, then copy into the variable.
2062 bool capturedByInit =
2063 Init && emission.IsEscapingByRef && isCapturedBy(Var: D, E: Init);
2064
2065 bool locIsByrefHeader = !capturedByInit;
2066 const Address Loc =
2067 locIsByrefHeader ? emission.getObjectAddress(CGF&: *this) : emission.Addr;
2068
2069 // Note: constexpr already initializes everything correctly.
2070 LangOptions::TrivialAutoVarInitKind trivialAutoVarInit =
2071 getAutoVarInitKind(Ty: type, D);
2072
2073 auto initializeWhatIsTechnicallyUninitialized = [&](Address Loc) {
2074 if (trivialAutoVarInit ==
2075 LangOptions::TrivialAutoVarInitKind::Uninitialized)
2076 return;
2077
2078 // Only initialize a __block's storage: we always initialize the header.
2079 if (emission.IsEscapingByRef && !locIsByrefHeader)
2080 Loc = emitBlockByrefAddress(baseAddr: Loc, V: &D, /*follow=*/followForward: false);
2081
2082 return emitZeroOrPatternForAutoVarInit(type, D, Loc);
2083 };
2084
2085 if (isTrivialInitializer(Init))
2086 return initializeWhatIsTechnicallyUninitialized(Loc);
2087
2088 llvm::Constant *constant = nullptr;
2089 if (emission.ConstantAggregateInitializer ||
2090 D.mightBeUsableInConstantExpressions(C: getContext())) {
2091 assert(!capturedByInit && "constant init contains a capturing block?");
2092 if (emission.ConstantAggregateInitializer)
2093 constant = emission.ConstantAggregateInitializer;
2094 else
2095 constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(D);
2096 if (constant && !constant->isNullValue() &&
2097 (trivialAutoVarInit !=
2098 LangOptions::TrivialAutoVarInitKind::Uninitialized)) {
2099 IsPattern isPattern =
2100 (trivialAutoVarInit == LangOptions::TrivialAutoVarInitKind::Pattern)
2101 ? IsPattern::Yes
2102 : IsPattern::No;
2103 // C guarantees that brace-init with fewer initializers than members in
2104 // the aggregate will initialize the rest of the aggregate as-if it were
2105 // static initialization. In turn static initialization guarantees that
2106 // padding is initialized to zero bits. We could instead pattern-init if D
2107 // has any ImplicitValueInitExpr, but that seems to be unintuitive
2108 // behavior.
2109 constant = constWithPadding(CGM, isPattern: IsPattern::No,
2110 constant: replaceUndef(CGM, isPattern, constant));
2111 }
2112
2113 if (constant && type->isBitIntType() &&
2114 CGM.getTypes().typeRequiresSplitIntoByteArray(ASTTy: type)) {
2115 // Constants for long _BitInt types are split into individual bytes.
2116 // Try to fold these back into an integer constant so it can be stored
2117 // properly.
2118 llvm::Type *LoadType =
2119 CGM.getTypes().convertTypeForLoadStore(T: type, LLVMTy: constant->getType());
2120 constant = llvm::ConstantFoldLoadFromConst(
2121 C: constant, Ty: LoadType, Offset: llvm::APInt::getZero(numBits: 32), DL: CGM.getDataLayout());
2122 }
2123 }
2124
2125 if (!constant) {
2126 if (trivialAutoVarInit !=
2127 LangOptions::TrivialAutoVarInitKind::Uninitialized) {
2128 // At this point, we know D has an Init expression, but isn't a constant.
2129 // - If D is not a scalar, auto-var-init conservatively (members may be
2130 // left uninitialized by constructor Init expressions for example).
2131 // - If D is a scalar, we only need to auto-var-init if there is a
2132 // self-reference. Otherwise, the Init expression should be sufficient.
2133 // It may be that the Init expression uses other uninitialized memory,
2134 // but auto-var-init here would not help, as auto-init would get
2135 // overwritten by Init.
2136 if (!type->isScalarType() || capturedByInit || isAccessedBy(var: D, s: Init)) {
2137 initializeWhatIsTechnicallyUninitialized(Loc);
2138 }
2139 }
2140 LValue lv = MakeAddrLValue(Addr: Loc, T: type);
2141 lv.setNonGC(true);
2142 return EmitExprAsInit(init: Init, D: &D, lvalue: lv, capturedByInit);
2143 }
2144
2145 PGO->markStmtMaybeUsed(S: Init);
2146
2147 if (!emission.ConstantAggregateInitializer) {
2148 // For simple scalar/complex initialization, store the value directly.
2149 LValue lv = MakeAddrLValue(Addr: Loc, T: type);
2150 lv.setNonGC(true);
2151 return EmitStoreThroughLValue(Src: RValue::get(V: constant), Dst: lv, isInit: true);
2152 }
2153
2154 emitStoresForConstant(D, Loc: Loc.withElementType(ElemTy: CGM.Int8Ty),
2155 isVolatile: type.isVolatileQualified(), constant,
2156 /*IsAutoInit=*/false);
2157}
2158
2159void CodeGenFunction::MaybeEmitDeferredVarDeclInit(const VarDecl *VD) {
2160 if (auto *DD = dyn_cast_if_present<DecompositionDecl>(Val: VD)) {
2161 for (auto *B : DD->flat_bindings())
2162 if (auto *HD = B->getHoldingVar())
2163 EmitVarDecl(D: *HD);
2164 }
2165}
2166
2167/// Emit an expression as an initializer for an object (variable, field, etc.)
2168/// at the given location. The expression is not necessarily the normal
2169/// initializer for the object, and the address is not necessarily
2170/// its normal location.
2171///
2172/// \param init the initializing expression
2173/// \param D the object to act as if we're initializing
2174/// \param lvalue the lvalue to initialize
2175/// \param capturedByInit true if \p D is a __block variable
2176/// whose address is potentially changed by the initializer
2177void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
2178 LValue lvalue, bool capturedByInit) {
2179 QualType type = D->getType();
2180
2181 if (type->isReferenceType()) {
2182 RValue rvalue = EmitReferenceBindingToExpr(E: init);
2183 if (capturedByInit)
2184 drillIntoBlockVariable(CGF&: *this, lvalue, var: cast<VarDecl>(Val: D));
2185 EmitStoreThroughLValue(Src: rvalue, Dst: lvalue, isInit: true);
2186 return;
2187 }
2188 switch (getEvaluationKind(T: type)) {
2189 case TEK_Scalar:
2190 EmitScalarInit(init, D, lvalue, capturedByInit);
2191 return;
2192 case TEK_Complex: {
2193 ComplexPairTy complex = EmitComplexExpr(E: init);
2194 if (capturedByInit)
2195 drillIntoBlockVariable(CGF&: *this, lvalue, var: cast<VarDecl>(Val: D));
2196 EmitStoreOfComplex(V: complex, dest: lvalue, /*init*/ isInit: true);
2197 return;
2198 }
2199 case TEK_Aggregate:
2200 if (type->isAtomicType()) {
2201 EmitAtomicInit(E: const_cast<Expr*>(init), lvalue);
2202 } else {
2203 AggValueSlot::Overlap_t Overlap = AggValueSlot::MayOverlap;
2204 if (isa<VarDecl>(Val: D))
2205 Overlap = AggValueSlot::DoesNotOverlap;
2206 else if (auto *FD = dyn_cast<FieldDecl>(Val: D))
2207 Overlap = getOverlapForFieldInit(FD);
2208 // TODO: how can we delay here if D is captured by its initializer?
2209 EmitAggExpr(E: init,
2210 AS: AggValueSlot::forLValue(LV: lvalue, isDestructed: AggValueSlot::IsDestructed,
2211 needsGC: AggValueSlot::DoesNotNeedGCBarriers,
2212 isAliased: AggValueSlot::IsNotAliased, mayOverlap: Overlap));
2213 }
2214 return;
2215 }
2216 llvm_unreachable("bad evaluation kind");
2217}
2218
2219/// Enter a destroy cleanup for the given local variable.
2220void CodeGenFunction::emitAutoVarTypeCleanup(
2221 const CodeGenFunction::AutoVarEmission &emission,
2222 QualType::DestructionKind dtorKind) {
2223 assert(dtorKind != QualType::DK_none);
2224
2225 // Note that for __block variables, we want to destroy the
2226 // original stack object, not the possibly forwarded object.
2227 Address addr = emission.getObjectAddress(CGF&: *this);
2228
2229 const VarDecl *var = emission.Variable;
2230 QualType type = var->getType();
2231
2232 CleanupKind cleanupKind = NormalAndEHCleanup;
2233 CodeGenFunction::Destroyer *destroyer = nullptr;
2234
2235 switch (dtorKind) {
2236 case QualType::DK_none:
2237 llvm_unreachable("no cleanup for trivially-destructible variable");
2238
2239 case QualType::DK_cxx_destructor:
2240 // If there's an NRVO flag on the emission, we need a different
2241 // cleanup.
2242 if (emission.NRVOFlag) {
2243 assert(!type->isArrayType());
2244 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
2245 EHStack.pushCleanup<DestroyNRVOVariableCXX>(Kind: cleanupKind, A: addr, A: type, A: dtor,
2246 A: emission.NRVOFlag);
2247 return;
2248 }
2249 break;
2250
2251 case QualType::DK_objc_strong_lifetime:
2252 // Suppress cleanups for pseudo-strong variables.
2253 if (var->isARCPseudoStrong()) return;
2254
2255 // Otherwise, consider whether to use an EH cleanup or not.
2256 cleanupKind = getARCCleanupKind();
2257
2258 // Use the imprecise destroyer by default.
2259 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
2260 destroyer = CodeGenFunction::destroyARCStrongImprecise;
2261 break;
2262
2263 case QualType::DK_objc_weak_lifetime:
2264 break;
2265
2266 case QualType::DK_nontrivial_c_struct:
2267 destroyer = CodeGenFunction::destroyNonTrivialCStruct;
2268 if (emission.NRVOFlag) {
2269 assert(!type->isArrayType());
2270 EHStack.pushCleanup<DestroyNRVOVariableC>(Kind: cleanupKind, A: addr,
2271 A: emission.NRVOFlag, A: type);
2272 return;
2273 }
2274 break;
2275 }
2276
2277 // If we haven't chosen a more specific destroyer, use the default.
2278 if (!destroyer) destroyer = getDestroyer(destructionKind: dtorKind);
2279
2280 // Use an EH cleanup in array destructors iff the destructor itself
2281 // is being pushed as an EH cleanup.
2282 bool useEHCleanup = (cleanupKind & EHCleanup);
2283 EHStack.pushCleanup<DestroyObject>(Kind: cleanupKind, A: addr, A: type, A: destroyer,
2284 A: useEHCleanup);
2285}
2286
2287void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
2288 assert(emission.Variable && "emission was not valid!");
2289
2290 // If this was emitted as a global constant, we're done.
2291 if (emission.wasEmittedAsGlobal()) return;
2292
2293 // If we don't have an insertion point, we're done. Sema prevents
2294 // us from jumping into any of these scopes anyway.
2295 if (!HaveInsertPoint()) return;
2296
2297 const VarDecl &D = *emission.Variable;
2298
2299 // Check the type for a cleanup.
2300 if (QualType::DestructionKind dtorKind = D.needsDestruction(Ctx: getContext())) {
2301 // Check if we're in a SEH block with /EH, prevent it
2302 if (getLangOpts().CXXExceptions && currentFunctionUsesSEHTry())
2303 getContext().getDiagnostics().Report(Loc: D.getLocation(),
2304 DiagID: diag::err_seh_object_unwinding);
2305 emitAutoVarTypeCleanup(emission, dtorKind);
2306 }
2307
2308 // In GC mode, honor objc_precise_lifetime.
2309 if (getLangOpts().getGC() != LangOptions::NonGC &&
2310 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
2311 EHStack.pushCleanup<ExtendGCLifetime>(Kind: NormalCleanup, A: &D);
2312 }
2313
2314 // Handle the cleanup attribute.
2315 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
2316 const FunctionDecl *FD = CA->getFunctionDecl();
2317
2318 llvm::Constant *F = CGM.GetAddrOfFunction(GD: FD);
2319 assert(F && "Could not find function!");
2320
2321 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(GD: FD);
2322 EHStack.pushCleanup<CallCleanupFunction>(Kind: NormalAndEHCleanup, A: F, A: &Info, A: &D,
2323 A: CA);
2324 }
2325
2326 // If this is a block variable, call _Block_object_destroy
2327 // (on the unforwarded address). Don't enter this cleanup if we're in pure-GC
2328 // mode.
2329 if (emission.IsEscapingByRef &&
2330 CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
2331 BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
2332 if (emission.Variable->getType().isObjCGCWeak())
2333 Flags |= BLOCK_FIELD_IS_WEAK;
2334 enterByrefCleanup(Kind: NormalAndEHCleanup, Addr: emission.Addr, Flags,
2335 /*LoadBlockVarAddr*/ false,
2336 CanThrow: cxxDestructorCanThrow(T: emission.Variable->getType()));
2337 }
2338}
2339
2340CodeGenFunction::Destroyer *
2341CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
2342 switch (kind) {
2343 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
2344 case QualType::DK_cxx_destructor:
2345 return destroyCXXObject;
2346 case QualType::DK_objc_strong_lifetime:
2347 return destroyARCStrongPrecise;
2348 case QualType::DK_objc_weak_lifetime:
2349 return destroyARCWeak;
2350 case QualType::DK_nontrivial_c_struct:
2351 return destroyNonTrivialCStruct;
2352 }
2353 llvm_unreachable("Unknown DestructionKind");
2354}
2355
2356/// pushEHDestroy - Push the standard destructor for the given type as
2357/// an EH-only cleanup.
2358void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
2359 Address addr, QualType type) {
2360 assert(dtorKind && "cannot push destructor for trivial type");
2361 assert(needsEHCleanup(dtorKind));
2362
2363 pushDestroy(kind: EHCleanup, addr, type, destroyer: getDestroyer(kind: dtorKind), useEHCleanupForArray: true);
2364}
2365
2366/// pushDestroy - Push the standard destructor for the given type as
2367/// at least a normal cleanup.
2368void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
2369 Address addr, QualType type) {
2370 assert(dtorKind && "cannot push destructor for trivial type");
2371
2372 CleanupKind cleanupKind = getCleanupKind(kind: dtorKind);
2373 pushDestroy(kind: cleanupKind, addr, type, destroyer: getDestroyer(kind: dtorKind),
2374 useEHCleanupForArray: cleanupKind & EHCleanup);
2375}
2376
2377void CodeGenFunction::pushLifetimeExtendedDestroy(
2378 QualType::DestructionKind dtorKind, Address addr, QualType type) {
2379 CleanupKind cleanupKind = getCleanupKind(kind: dtorKind);
2380 pushLifetimeExtendedDestroy(kind: cleanupKind, addr, type, destroyer: getDestroyer(kind: dtorKind),
2381 useEHCleanupForArray: cleanupKind & EHCleanup);
2382}
2383
2384void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
2385 QualType type, Destroyer *destroyer,
2386 bool useEHCleanupForArray) {
2387 pushFullExprCleanup<DestroyObject>(kind: cleanupKind, A: addr, A: type, A: destroyer,
2388 A: useEHCleanupForArray);
2389}
2390
2391// Pushes a destroy and defers its deactivation until its
2392// CleanupDeactivationScope is exited.
2393void CodeGenFunction::pushDestroyAndDeferDeactivation(
2394 QualType::DestructionKind dtorKind, Address addr, QualType type) {
2395 assert(dtorKind && "cannot push destructor for trivial type");
2396
2397 CleanupKind cleanupKind = getCleanupKind(kind: dtorKind);
2398 pushDestroyAndDeferDeactivation(
2399 cleanupKind, addr, type, destroyer: getDestroyer(kind: dtorKind), useEHCleanupForArray: cleanupKind & EHCleanup);
2400}
2401
2402void CodeGenFunction::pushDestroyAndDeferDeactivation(
2403 CleanupKind cleanupKind, Address addr, QualType type, Destroyer *destroyer,
2404 bool useEHCleanupForArray) {
2405 llvm::Instruction *DominatingIP =
2406 Builder.CreateFlagLoad(Addr: llvm::Constant::getNullValue(Ty: Int8PtrTy));
2407 pushDestroy(cleanupKind, addr, type, destroyer, useEHCleanupForArray);
2408 DeferredDeactivationCleanupStack.push_back(
2409 Elt: {.Cleanup: EHStack.stable_begin(), .DominatingIP: DominatingIP});
2410}
2411
2412void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
2413 EHStack.pushCleanup<CallStackRestore>(
2414 Kind: static_cast<CleanupKind>(Kind | StackRestore), A: SPMem);
2415}
2416
2417void CodeGenFunction::pushKmpcAllocFree(
2418 CleanupKind Kind, std::pair<llvm::Value *, llvm::Value *> AddrSizePair) {
2419 EHStack.pushCleanup<KmpcAllocFree>(Kind, A: AddrSizePair);
2420}
2421
2422void CodeGenFunction::pushLifetimeExtendedDestroy(CleanupKind cleanupKind,
2423 Address addr, QualType type,
2424 Destroyer *destroyer,
2425 bool useEHCleanupForArray) {
2426 // If we're not in a conditional branch, we don't need to bother generating a
2427 // conditional cleanup.
2428 if (!isInConditionalBranch()) {
2429 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
2430 // around in case a temporary's destructor throws an exception.
2431
2432 // Add the cleanup to the EHStack. After the full-expr, this would be
2433 // deactivated before being popped from the stack.
2434 pushDestroyAndDeferDeactivation(cleanupKind, addr, type, destroyer,
2435 useEHCleanupForArray);
2436
2437 // Since this is lifetime-extended, push it once again to the EHStack after
2438 // the full expression.
2439 return pushCleanupAfterFullExprWithActiveFlag<DestroyObject>(
2440 Kind: cleanupKind, ActiveFlag: Address::invalid(), A: addr, A: type, A: destroyer,
2441 A: useEHCleanupForArray);
2442 }
2443
2444 // Otherwise, we should only destroy the object if it's been initialized.
2445
2446 using ConditionalCleanupType =
2447 EHScopeStack::ConditionalCleanup<DestroyObject, Address, QualType,
2448 Destroyer *, bool>;
2449 DominatingValue<Address>::saved_type SavedAddr = saveValueInCond(value: addr);
2450
2451 // Remember to emit cleanup if we branch-out before end of full-expression
2452 // (eg: through stmt-expr or coro suspensions).
2453 AllocaTrackerRAII DeactivationAllocas(*this);
2454 Address ActiveFlagForDeactivation = createCleanupActiveFlag();
2455
2456 pushCleanupAndDeferDeactivation<ConditionalCleanupType>(
2457 Kind: cleanupKind, A: SavedAddr, A: type, A: destroyer, A: useEHCleanupForArray);
2458 initFullExprCleanupWithFlag(ActiveFlag: ActiveFlagForDeactivation);
2459 EHCleanupScope &cleanup = cast<EHCleanupScope>(Val&: *EHStack.begin());
2460 // Erase the active flag if the cleanup was not emitted.
2461 cleanup.AddAuxAllocas(Allocas: std::move(DeactivationAllocas).Take());
2462
2463 // Since this is lifetime-extended, push it once again to the EHStack after
2464 // the full expression.
2465 // The previous active flag would always be 'false' due to forced deferred
2466 // deactivation. Use a separate flag for lifetime-extension to correctly
2467 // remember if this branch was taken and the object was initialized.
2468 Address ActiveFlagForLifetimeExt = createCleanupActiveFlag();
2469 pushCleanupAfterFullExprWithActiveFlag<ConditionalCleanupType>(
2470 Kind: cleanupKind, ActiveFlag: ActiveFlagForLifetimeExt, A: SavedAddr, A: type, A: destroyer,
2471 A: useEHCleanupForArray);
2472}
2473
2474/// emitDestroy - Immediately perform the destruction of the given
2475/// object.
2476///
2477/// \param addr - the address of the object; a type*
2478/// \param type - the type of the object; if an array type, all
2479/// objects are destroyed in reverse order
2480/// \param destroyer - the function to call to destroy individual
2481/// elements
2482/// \param useEHCleanupForArray - whether an EH cleanup should be
2483/// used when destroying array elements, in case one of the
2484/// destructions throws an exception
2485void CodeGenFunction::emitDestroy(Address addr, QualType type,
2486 Destroyer *destroyer,
2487 bool useEHCleanupForArray) {
2488 const ArrayType *arrayType = getContext().getAsArrayType(T: type);
2489 if (!arrayType)
2490 return destroyer(*this, addr, type);
2491
2492 llvm::Value *length = emitArrayLength(arrayType, baseType&: type, addr);
2493
2494 CharUnits elementAlign =
2495 addr.getAlignment()
2496 .alignmentOfArrayElement(elementSize: getContext().getTypeSizeInChars(T: type));
2497
2498 // Normally we have to check whether the array is zero-length.
2499 bool checkZeroLength = true;
2500
2501 // But if the array length is constant, we can suppress that.
2502 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(Val: length)) {
2503 // ...and if it's constant zero, we can just skip the entire thing.
2504 if (constLength->isZero()) return;
2505 checkZeroLength = false;
2506 }
2507
2508 llvm::Value *begin = addr.emitRawPointer(CGF&: *this);
2509 llvm::Value *end =
2510 Builder.CreateInBoundsGEP(Ty: addr.getElementType(), Ptr: begin, IdxList: length);
2511 emitArrayDestroy(begin, end, elementType: type, elementAlign, destroyer,
2512 checkZeroLength, useEHCleanup: useEHCleanupForArray);
2513}
2514
2515/// emitArrayDestroy - Destroys all the elements of the given array,
2516/// beginning from last to first. The array cannot be zero-length.
2517///
2518/// \param begin - a type* denoting the first element of the array
2519/// \param end - a type* denoting one past the end of the array
2520/// \param elementType - the element type of the array
2521/// \param destroyer - the function to call to destroy elements
2522/// \param useEHCleanup - whether to push an EH cleanup to destroy
2523/// the remaining elements in case the destruction of a single
2524/// element throws
2525void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
2526 llvm::Value *end,
2527 QualType elementType,
2528 CharUnits elementAlign,
2529 Destroyer *destroyer,
2530 bool checkZeroLength,
2531 bool useEHCleanup) {
2532 assert(!elementType->isArrayType());
2533
2534 // The basic structure here is a do-while loop, because we don't
2535 // need to check for the zero-element case.
2536 llvm::BasicBlock *bodyBB = createBasicBlock(name: "arraydestroy.body");
2537 llvm::BasicBlock *doneBB = createBasicBlock(name: "arraydestroy.done");
2538
2539 if (checkZeroLength) {
2540 llvm::Value *isEmpty = Builder.CreateICmpEQ(LHS: begin, RHS: end,
2541 Name: "arraydestroy.isempty");
2542 Builder.CreateCondBr(Cond: isEmpty, True: doneBB, False: bodyBB);
2543 }
2544
2545 // Enter the loop body, making that address the current address.
2546 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
2547 EmitBlock(BB: bodyBB);
2548 llvm::PHINode *elementPast =
2549 Builder.CreatePHI(Ty: begin->getType(), NumReservedValues: 2, Name: "arraydestroy.elementPast");
2550 elementPast->addIncoming(V: end, BB: entryBB);
2551
2552 // Shift the address back by one element.
2553 llvm::Value *negativeOne = llvm::ConstantInt::get(Ty: SizeTy, V: -1, IsSigned: true);
2554 llvm::Type *llvmElementType = ConvertTypeForMem(T: elementType);
2555 llvm::Value *element = Builder.CreateInBoundsGEP(
2556 Ty: llvmElementType, Ptr: elementPast, IdxList: negativeOne, Name: "arraydestroy.element");
2557
2558 if (useEHCleanup)
2559 pushRegularPartialArrayCleanup(arrayBegin: begin, arrayEnd: element, elementType, elementAlignment: elementAlign,
2560 destroyer);
2561
2562 // Perform the actual destruction there.
2563 destroyer(*this, Address(element, llvmElementType, elementAlign),
2564 elementType);
2565
2566 if (useEHCleanup)
2567 PopCleanupBlock();
2568
2569 // Check whether we've reached the end.
2570 llvm::Value *done = Builder.CreateICmpEQ(LHS: element, RHS: begin, Name: "arraydestroy.done");
2571 Builder.CreateCondBr(Cond: done, True: doneBB, False: bodyBB);
2572 elementPast->addIncoming(V: element, BB: Builder.GetInsertBlock());
2573
2574 // Done.
2575 EmitBlock(BB: doneBB);
2576}
2577
2578/// Perform partial array destruction as if in an EH cleanup. Unlike
2579/// emitArrayDestroy, the element type here may still be an array type.
2580static void emitPartialArrayDestroy(CodeGenFunction &CGF,
2581 llvm::Value *begin, llvm::Value *end,
2582 QualType type, CharUnits elementAlign,
2583 CodeGenFunction::Destroyer *destroyer) {
2584 llvm::Type *elemTy = CGF.ConvertTypeForMem(T: type);
2585
2586 // If the element type is itself an array, drill down.
2587 unsigned arrayDepth = 0;
2588 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(T: type)) {
2589 // VLAs don't require a GEP index to walk into.
2590 if (!isa<VariableArrayType>(Val: arrayType))
2591 arrayDepth++;
2592 type = arrayType->getElementType();
2593 }
2594
2595 if (arrayDepth) {
2596 llvm::Value *zero = llvm::ConstantInt::get(Ty: CGF.SizeTy, V: 0);
2597
2598 SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
2599 begin = CGF.Builder.CreateInBoundsGEP(
2600 Ty: elemTy, Ptr: begin, IdxList: gepIndices, Name: "pad.arraybegin");
2601 end = CGF.Builder.CreateInBoundsGEP(
2602 Ty: elemTy, Ptr: end, IdxList: gepIndices, Name: "pad.arrayend");
2603 }
2604
2605 // Destroy the array. We don't ever need an EH cleanup because we
2606 // assume that we're in an EH cleanup ourselves, so a throwing
2607 // destructor causes an immediate terminate.
2608 CGF.emitArrayDestroy(begin, end, elementType: type, elementAlign, destroyer,
2609 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
2610}
2611
2612namespace {
2613 /// RegularPartialArrayDestroy - a cleanup which performs a partial
2614 /// array destroy where the end pointer is regularly determined and
2615 /// does not need to be loaded from a local.
2616 class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
2617 llvm::Value *ArrayBegin;
2618 llvm::Value *ArrayEnd;
2619 QualType ElementType;
2620 CodeGenFunction::Destroyer *Destroyer;
2621 CharUnits ElementAlign;
2622 public:
2623 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
2624 QualType elementType, CharUnits elementAlign,
2625 CodeGenFunction::Destroyer *destroyer)
2626 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
2627 ElementType(elementType), Destroyer(destroyer),
2628 ElementAlign(elementAlign) {}
2629
2630 void Emit(CodeGenFunction &CGF, Flags flags) override {
2631 emitPartialArrayDestroy(CGF, begin: ArrayBegin, end: ArrayEnd,
2632 type: ElementType, elementAlign: ElementAlign, destroyer: Destroyer);
2633 }
2634 };
2635
2636 /// IrregularPartialArrayDestroy - a cleanup which performs a
2637 /// partial array destroy where the end pointer is irregularly
2638 /// determined and must be loaded from a local.
2639 class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
2640 llvm::Value *ArrayBegin;
2641 Address ArrayEndPointer;
2642 QualType ElementType;
2643 CodeGenFunction::Destroyer *Destroyer;
2644 CharUnits ElementAlign;
2645 public:
2646 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
2647 Address arrayEndPointer,
2648 QualType elementType,
2649 CharUnits elementAlign,
2650 CodeGenFunction::Destroyer *destroyer)
2651 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
2652 ElementType(elementType), Destroyer(destroyer),
2653 ElementAlign(elementAlign) {}
2654
2655 void Emit(CodeGenFunction &CGF, Flags flags) override {
2656 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(Addr: ArrayEndPointer);
2657 emitPartialArrayDestroy(CGF, begin: ArrayBegin, end: arrayEnd,
2658 type: ElementType, elementAlign: ElementAlign, destroyer: Destroyer);
2659 }
2660 };
2661} // end anonymous namespace
2662
2663/// pushIrregularPartialArrayCleanup - Push a NormalAndEHCleanup to
2664/// destroy already-constructed elements of the given array. The cleanup may be
2665/// popped with DeactivateCleanupBlock or PopCleanupBlock.
2666///
2667/// \param elementType - the immediate element type of the array;
2668/// possibly still an array type
2669void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
2670 Address arrayEndPointer,
2671 QualType elementType,
2672 CharUnits elementAlign,
2673 Destroyer *destroyer) {
2674 pushFullExprCleanup<IrregularPartialArrayDestroy>(
2675 kind: NormalAndEHCleanup, A: arrayBegin, A: arrayEndPointer, A: elementType,
2676 A: elementAlign, A: destroyer);
2677}
2678
2679/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
2680/// already-constructed elements of the given array. The cleanup
2681/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
2682///
2683/// \param elementType - the immediate element type of the array;
2684/// possibly still an array type
2685void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
2686 llvm::Value *arrayEnd,
2687 QualType elementType,
2688 CharUnits elementAlign,
2689 Destroyer *destroyer) {
2690 pushFullExprCleanup<RegularPartialArrayDestroy>(kind: EHCleanup,
2691 A: arrayBegin, A: arrayEnd,
2692 A: elementType, A: elementAlign,
2693 A: destroyer);
2694}
2695
2696/// Lazily declare the @llvm.lifetime.start intrinsic.
2697llvm::Function *CodeGenModule::getLLVMLifetimeStartFn() {
2698 if (LifetimeStartFn)
2699 return LifetimeStartFn;
2700 LifetimeStartFn = llvm::Intrinsic::getOrInsertDeclaration(
2701 M: &getModule(), id: llvm::Intrinsic::lifetime_start, OverloadTys: AllocaInt8PtrTy);
2702 return LifetimeStartFn;
2703}
2704
2705/// Lazily declare the @llvm.lifetime.end intrinsic.
2706llvm::Function *CodeGenModule::getLLVMLifetimeEndFn() {
2707 if (LifetimeEndFn)
2708 return LifetimeEndFn;
2709 LifetimeEndFn = llvm::Intrinsic::getOrInsertDeclaration(
2710 M: &getModule(), id: llvm::Intrinsic::lifetime_end, OverloadTys: AllocaInt8PtrTy);
2711 return LifetimeEndFn;
2712}
2713
2714/// Lazily declare the @llvm.fake.use intrinsic.
2715llvm::Function *CodeGenModule::getLLVMFakeUseFn() {
2716 if (FakeUseFn)
2717 return FakeUseFn;
2718 FakeUseFn = llvm::Intrinsic::getOrInsertDeclaration(
2719 M: &getModule(), id: llvm::Intrinsic::fake_use);
2720 return FakeUseFn;
2721}
2722
2723namespace {
2724 /// A cleanup to perform a release of an object at the end of a
2725 /// function. This is used to balance out the incoming +1 of a
2726 /// ns_consumed argument when we can't reasonably do that just by
2727 /// not doing the initial retain for a __block argument.
2728 struct ConsumeARCParameter final : EHScopeStack::Cleanup {
2729 ConsumeARCParameter(llvm::Value *param,
2730 ARCPreciseLifetime_t precise)
2731 : Param(param), Precise(precise) {}
2732
2733 llvm::Value *Param;
2734 ARCPreciseLifetime_t Precise;
2735
2736 void Emit(CodeGenFunction &CGF, Flags flags) override {
2737 CGF.EmitARCRelease(value: Param, precise: Precise);
2738 }
2739 };
2740} // end anonymous namespace
2741
2742/// Emit an alloca (or GlobalValue depending on target)
2743/// for the specified parameter and set up LocalDeclMap.
2744void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
2745 unsigned ArgNo) {
2746 bool NoDebugInfo = false;
2747 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
2748 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
2749 "Invalid argument to EmitParmDecl");
2750
2751 // Set the name of the parameter's initial value to make IR easier to
2752 // read. Don't modify the names of globals.
2753 if (!isa<llvm::GlobalValue>(Val: Arg.getAnyValue()))
2754 Arg.getAnyValue()->setName(D.getName());
2755
2756 QualType Ty = D.getType();
2757 assert((getLangOpts().OpenCL || Ty.getAddressSpace() == LangAS::Default) &&
2758 "parameter has non-default address space in non-OpenCL mode");
2759
2760 // Use better IR generation for certain implicit parameters.
2761 if (auto IPD = dyn_cast<ImplicitParamDecl>(Val: &D)) {
2762 // The only implicit argument a block has is its literal.
2763 // This may be passed as an inalloca'ed value on Windows x86.
2764 if (BlockInfo) {
2765 llvm::Value *V = Arg.isIndirect()
2766 ? Builder.CreateLoad(Addr: Arg.getIndirectAddress())
2767 : Arg.getDirectValue();
2768 setBlockContextParameter(D: IPD, argNum: ArgNo, ptr: V);
2769 return;
2770 }
2771 // Suppressing debug info for ThreadPrivateVar parameters, else it hides
2772 // debug info of TLS variables.
2773 NoDebugInfo =
2774 (IPD->getParameterKind() == ImplicitParamKind::ThreadPrivateVar);
2775 }
2776
2777 Address DeclPtr = Address::invalid();
2778 RawAddress AllocaPtr = Address::invalid();
2779 bool DoStore = false;
2780 bool IsScalar = hasScalarEvaluationKind(T: Ty);
2781 bool UseIndirectDebugAddress = false;
2782
2783 // If we already have a pointer to the argument, reuse the input pointer.
2784 if (Arg.isIndirect()) {
2785 DeclPtr = Arg.getIndirectAddress();
2786 DeclPtr = DeclPtr.withElementType(ElemTy: ConvertTypeForMem(T: Ty));
2787 auto *V = DeclPtr.emitRawPointer(CGF&: *this);
2788 AllocaPtr = RawAddress(V, DeclPtr.getElementType(), DeclPtr.getAlignment());
2789
2790 // For truly ABI indirect arguments -- those that are not `byval` -- store
2791 // the address of the argument on the stack to preserve debug information.
2792 ABIArgInfo ArgInfo = CurFnInfo->arguments()[ArgNo - 1].info;
2793 if (ArgInfo.isIndirect())
2794 UseIndirectDebugAddress = !ArgInfo.getIndirectByVal();
2795 if (UseIndirectDebugAddress) {
2796 auto PtrTy = getContext().getPointerType(T: Ty);
2797 AllocaPtr = CreateMemTempWithoutCast(
2798 T: PtrTy, Align: getContext().getTypeAlignInChars(T: PtrTy),
2799 Name: D.getName() + ".indirect_addr");
2800 EmitStoreOfScalar(Value: V, Addr: AllocaPtr, /* Volatile */ false, Ty: PtrTy);
2801 }
2802
2803 LangAS DestLangAS = Ty.getAddressSpace();
2804 unsigned DestAS = getContext().getTargetAddressSpace(AS: DestLangAS);
2805 if (DeclPtr.getAddressSpace() != DestAS) {
2806 auto *T = llvm::PointerType::get(C&: getLLVMContext(), AddressSpace: DestAS);
2807 DeclPtr = DeclPtr.withPointer(NewPointer: performAddrSpaceCast(Src: V, DestTy: T),
2808 IsKnownNonNull: DeclPtr.isKnownNonNull());
2809 }
2810
2811 // Push a destructor cleanup for this parameter if the ABI requires it.
2812 // Don't push a cleanup in a thunk for a method that will also emit a
2813 // cleanup.
2814 if (Ty->isRecordType() && !CurFuncIsThunk &&
2815 Ty->castAsRecordDecl()->isParamDestroyedInCallee()) {
2816 if (QualType::DestructionKind DtorKind =
2817 D.needsDestruction(Ctx: getContext())) {
2818 assert((DtorKind == QualType::DK_cxx_destructor ||
2819 DtorKind == QualType::DK_nontrivial_c_struct) &&
2820 "unexpected destructor type");
2821 pushDestroy(dtorKind: DtorKind, addr: DeclPtr, type: Ty);
2822 CalleeDestructedParamCleanups[cast<ParmVarDecl>(Val: &D)] =
2823 EHStack.stable_begin();
2824 }
2825 }
2826 } else {
2827 // Check if the parameter address is controlled by OpenMP runtime.
2828 Address OpenMPLocalAddr =
2829 getLangOpts().OpenMP
2830 ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(CGF&: *this, VD: &D)
2831 : Address::invalid();
2832 if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
2833 DeclPtr = OpenMPLocalAddr;
2834 AllocaPtr = DeclPtr;
2835 } else {
2836 // Otherwise, create a casted temporary to hold the value.
2837 DeclPtr = CreateMemTemp(T: Ty, Align: getContext().getDeclAlign(D: &D),
2838 Name: D.getName() + ".addr", Alloca: &AllocaPtr);
2839 }
2840 DoStore = true;
2841 }
2842
2843 llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
2844
2845 LValue lv = MakeAddrLValue(Addr: DeclPtr, T: Ty);
2846 // If this is a thunk, don't bother with ARC lifetime management.
2847 // The true implementation will take care of that.
2848 if (IsScalar && !CurFuncIsThunk) {
2849 Qualifiers qs = Ty.getQualifiers();
2850 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
2851 // We honor __attribute__((ns_consumed)) for types with lifetime.
2852 // For __strong, it's handled by just skipping the initial retain;
2853 // otherwise we have to balance out the initial +1 with an extra
2854 // cleanup to do the release at the end of the function.
2855 bool isConsumed = D.hasAttr<NSConsumedAttr>();
2856
2857 // If a parameter is pseudo-strong then we can omit the implicit retain.
2858 if (D.isARCPseudoStrong()) {
2859 assert(lt == Qualifiers::OCL_Strong &&
2860 "pseudo-strong variable isn't strong?");
2861 assert(qs.hasConst() && "pseudo-strong variable should be const!");
2862 lt = Qualifiers::OCL_ExplicitNone;
2863 }
2864
2865 // Load objects passed indirectly.
2866 if (Arg.isIndirect() && !ArgVal)
2867 ArgVal = Builder.CreateLoad(Addr: DeclPtr);
2868
2869 if (lt == Qualifiers::OCL_Strong) {
2870 if (!isConsumed) {
2871 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2872 // use objc_storeStrong(&dest, value) for retaining the
2873 // object. But first, store a null into 'dest' because
2874 // objc_storeStrong attempts to release its old value.
2875 llvm::Value *Null = CGM.EmitNullConstant(T: D.getType());
2876 EmitStoreOfScalar(value: Null, lvalue: lv, /* isInitialization */ isInit: true);
2877 EmitARCStoreStrongCall(addr: lv.getAddress(), value: ArgVal, resultIgnored: true);
2878 DoStore = false;
2879 }
2880 else
2881 // Don't use objc_retainBlock for block pointers, because we
2882 // don't want to Block_copy something just because we got it
2883 // as a parameter.
2884 ArgVal = EmitARCRetainNonBlock(value: ArgVal);
2885 }
2886 } else {
2887 // Push the cleanup for a consumed parameter.
2888 if (isConsumed) {
2889 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
2890 ? ARCPreciseLifetime : ARCImpreciseLifetime);
2891 EHStack.pushCleanup<ConsumeARCParameter>(Kind: getARCCleanupKind(), A: ArgVal,
2892 A: precise);
2893 }
2894
2895 if (lt == Qualifiers::OCL_Weak) {
2896 EmitARCInitWeak(addr: DeclPtr, value: ArgVal);
2897 DoStore = false; // The weak init is a store, no need to do two.
2898 }
2899 }
2900
2901 // Enter the cleanup scope.
2902 EmitAutoVarWithLifetime(CGF&: *this, var: D, addr: DeclPtr, lifetime: lt);
2903 }
2904 }
2905
2906 // Store the initial value into the alloca.
2907 if (DoStore)
2908 EmitStoreOfScalar(value: ArgVal, lvalue: lv, /* isInitialization */ isInit: true);
2909
2910 setAddrOfLocalVar(VD: &D, Addr: DeclPtr);
2911
2912 // Push a FakeUse 'cleanup' object onto the EHStack for the parameter,
2913 // which may be the 'this' pointer. This causes the emission of a fake.use
2914 // call with the parameter as argument at the end of the function.
2915 if (CGM.getCodeGenOpts().getExtendVariableLiveness() ==
2916 CodeGenOptions::ExtendVariableLivenessKind::All ||
2917 (CGM.getCodeGenOpts().getExtendVariableLiveness() ==
2918 CodeGenOptions::ExtendVariableLivenessKind::This &&
2919 &D == CXXABIThisDecl)) {
2920 // We don't emit fake uses for coroutine parameters, other than `this`.
2921 if (auto *FnDecl = dyn_cast_or_null<FunctionDecl>(Val: CurCodeDecl);
2922 &D == CXXABIThisDecl || !FnDecl || !FnDecl->getBody() ||
2923 FnDecl->getBody()->getStmtClass() != Stmt::CoroutineBodyStmtClass) {
2924 if (shouldExtendLifetime(Context: getContext(), FuncDecl: CurCodeDecl, D, CXXABIThisDecl))
2925 EHStack.pushCleanup<FakeUse>(Kind: NormalFakeUse, A: DeclPtr);
2926 }
2927 }
2928
2929 // Emit debug info for param declarations in non-thunk functions.
2930 if (CGDebugInfo *DI = getDebugInfo()) {
2931 if (CGM.getCodeGenOpts().hasReducedDebugInfo() && !CurFuncIsThunk &&
2932 !NoDebugInfo) {
2933 llvm::DILocalVariable *DILocalVar = DI->EmitDeclareOfArgVariable(
2934 Decl: &D, AI: AllocaPtr.getPointer(), ArgNo, Builder, UsePointerValue: UseIndirectDebugAddress);
2935 if (const auto *Var = dyn_cast_or_null<ParmVarDecl>(Val: &D))
2936 DI->getParamDbgMappings().insert(KV: {Var, DILocalVar});
2937 }
2938 }
2939
2940 if (D.hasAttr<AnnotateAttr>())
2941 EmitVarAnnotations(D: &D, V: DeclPtr.emitRawPointer(CGF&: *this));
2942
2943 // We can only check return value nullability if all arguments to the
2944 // function satisfy their nullability preconditions. This makes it necessary
2945 // to emit null checks for args in the function body itself.
2946 if (requiresReturnValueNullabilityCheck()) {
2947 auto Nullability = Ty->getNullability();
2948 if (Nullability && *Nullability == NullabilityKind::NonNull) {
2949 SanitizerScope SanScope(this);
2950 RetValNullabilityPrecondition =
2951 Builder.CreateAnd(LHS: RetValNullabilityPrecondition,
2952 RHS: Builder.CreateIsNotNull(Arg: Arg.getAnyValue()));
2953 }
2954 }
2955}
2956
2957void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
2958 CodeGenFunction *CGF) {
2959 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
2960 return;
2961 getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
2962}
2963
2964void CodeGenModule::EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D,
2965 CodeGenFunction *CGF) {
2966 if (!LangOpts.OpenMP || LangOpts.OpenMPSimd ||
2967 (!LangOpts.EmitAllDecls && !D->isUsed()))
2968 return;
2969 getOpenMPRuntime().emitUserDefinedMapper(D, CGF);
2970}
2971
2972void CodeGenModule::EmitOpenACCDeclare(const OpenACCDeclareDecl *D,
2973 CodeGenFunction *CGF) {
2974 // This is a no-op, we cna just ignore these declarations.
2975}
2976
2977void CodeGenModule::EmitOpenACCRoutine(const OpenACCRoutineDecl *D,
2978 CodeGenFunction *CGF) {
2979 // This is a no-op, we cna just ignore these declarations.
2980}
2981
2982void CodeGenModule::EmitOMPRequiresDecl(const OMPRequiresDecl *D) {
2983 getOpenMPRuntime().processRequiresDirective(D);
2984}
2985
2986void CodeGenModule::EmitOMPAllocateDecl(const OMPAllocateDecl *D) {
2987 for (const Expr *E : D->varlist()) {
2988 const auto *DE = cast<DeclRefExpr>(Val: E);
2989 const auto *VD = cast<VarDecl>(Val: DE->getDecl());
2990
2991 // Skip all but globals.
2992 if (!VD->hasGlobalStorage())
2993 continue;
2994
2995 // Check if the global has been materialized yet or not. If not, we are done
2996 // as any later generation will utilize the OMPAllocateDeclAttr. However, if
2997 // we already emitted the global we might have done so before the
2998 // OMPAllocateDeclAttr was attached, leading to the wrong address space
2999 // (potentially). While not pretty, common practise is to remove the old IR
3000 // global and generate a new one, so we do that here too. Uses are replaced
3001 // properly.
3002 StringRef MangledName = getMangledName(GD: VD);
3003 llvm::GlobalValue *Entry = GetGlobalValue(Ref: MangledName);
3004 if (!Entry)
3005 continue;
3006
3007 // We can also keep the existing global if the address space is what we
3008 // expect it to be, if not, it is replaced.
3009 clang::LangAS GVAS = GetGlobalVarAddressSpace(D: VD);
3010 auto TargetAS = getContext().getTargetAddressSpace(AS: GVAS);
3011 if (Entry->getType()->getAddressSpace() == TargetAS)
3012 continue;
3013
3014 llvm::PointerType *PTy = llvm::PointerType::get(C&: getLLVMContext(), AddressSpace: TargetAS);
3015
3016 // Replace all uses of the old global with a cast. Since we mutate the type
3017 // in place we neeed an intermediate that takes the spot of the old entry
3018 // until we can create the cast.
3019 llvm::GlobalVariable *DummyGV = new llvm::GlobalVariable(
3020 getModule(), Entry->getValueType(), false,
3021 llvm::GlobalValue::CommonLinkage, nullptr, "dummy", nullptr,
3022 llvm::GlobalVariable::NotThreadLocal, Entry->getAddressSpace());
3023 Entry->replaceAllUsesWith(V: DummyGV);
3024
3025 Entry->mutateType(Ty: PTy);
3026 llvm::Constant *NewPtrForOldDecl =
3027 llvm::ConstantExpr::getAddrSpaceCast(C: Entry, Ty: DummyGV->getType());
3028
3029 // Now we have a casted version of the changed global, the dummy can be
3030 // replaced and deleted.
3031 DummyGV->replaceAllUsesWith(V: NewPtrForOldDecl);
3032 DummyGV->eraseFromParent();
3033 }
3034}
3035
3036std::optional<CharUnits>
3037CodeGenModule::getOMPAllocateAlignment(const VarDecl *VD) {
3038 if (const auto *AA = VD->getAttr<OMPAllocateDeclAttr>()) {
3039 if (Expr *Alignment = AA->getAlignment()) {
3040 unsigned UserAlign =
3041 Alignment->EvaluateKnownConstInt(Ctx: getContext()).getExtValue();
3042 CharUnits NaturalAlign =
3043 getNaturalTypeAlignment(T: VD->getType().getNonReferenceType());
3044
3045 // OpenMP5.1 pg 185 lines 7-10
3046 // Each item in the align modifier list must be aligned to the maximum
3047 // of the specified alignment and the type's natural alignment.
3048 return CharUnits::fromQuantity(
3049 Quantity: std::max<unsigned>(a: UserAlign, b: NaturalAlign.getQuantity()));
3050 }
3051 }
3052 return std::nullopt;
3053}
3054