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