clang 24.0.0git
CGDeclCXX.cpp
Go to the documentation of this file.
1//===--- CGDeclCXX.cpp - Emit LLVM Code for C++ 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 dealing with code generation of C++ declarations
10//
11//===----------------------------------------------------------------------===//
12
13#include "CGCXXABI.h"
14#include "CGDebugInfo.h"
15#include "CGHLSLRuntime.h"
16#include "CGObjCRuntime.h"
17#include "CGOpenMPRuntime.h"
18#include "CodeGenFunction.h"
19#include "TargetInfo.h"
20#include "clang/AST/Attr.h"
23#include "llvm/ADT/StringExtras.h"
24#include "llvm/IR/Intrinsics.h"
25#include "llvm/IR/MDBuilder.h"
26#include "llvm/Support/Path.h"
27
28using namespace clang;
29using namespace CodeGen;
30
31static void EmitDeclInit(CodeGenFunction &CGF, const VarDecl &D,
32 ConstantAddress DeclPtr) {
33 assert(
34 (D.hasGlobalStorage() ||
35 (D.hasLocalStorage() && CGF.getContext().getLangOpts().OpenCLCPlusPlus)) &&
36 "VarDecl must have global or local (in the case of OpenCL) storage!");
37 assert(!D.getType()->isReferenceType() &&
38 "Should not call EmitDeclInit on a reference!");
39
40 QualType type = D.getType();
41 LValue lv = CGF.MakeAddrLValue(DeclPtr, type);
42
43 const Expr *Init = D.getInit();
44 switch (CGF.getEvaluationKind(type)) {
45 case TEK_Scalar: {
46 CodeGenModule &CGM = CGF.CGM;
47 if (lv.isObjCStrong())
49 DeclPtr, D.getTLSKind());
50 else if (lv.isObjCWeak())
52 DeclPtr);
53 else
54 CGF.EmitScalarInit(Init, &D, lv, false);
55 return;
56 }
57 case TEK_Complex:
58 CGF.EmitComplexExprIntoLValue(Init, lv, /*isInit*/ true);
59 return;
60 case TEK_Aggregate:
61 CGF.EmitAggExpr(Init,
66 return;
67 }
68 llvm_unreachable("bad evaluation kind");
69}
70
71/// Emit code to cause the destruction of the given variable with
72/// static storage duration.
73static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D,
75 // Honor __attribute__((no_destroy)) and bail instead of attempting
76 // to emit a reference to a possibly nonexistent destructor, which
77 // in turn can cause a crash. This will result in a global constructor
78 // that isn't balanced out by a destructor call as intended by the
79 // attribute. This also checks for -fno-c++-static-destructors and
80 // bails even if the attribute is not present.
82
83 // FIXME: __attribute__((cleanup)) ?
84
85 switch (DtorKind) {
87 return;
88
90 break;
91
95 // We don't care about releasing objects during process teardown.
96 assert(!D.getTLSKind() && "should have rejected this");
97 return;
98 }
99
100 llvm::FunctionCallee Func;
101 llvm::Constant *Argument;
102
103 CodeGenModule &CGM = CGF.CGM;
104 QualType Type = D.getType();
105
106 // Special-case non-array C++ destructors, if they have the right signature.
107 // Under some ABIs, destructors return this instead of void, and cannot be
108 // passed directly to __cxa_atexit if the target does not allow this
109 // mismatch.
111 bool CanRegisterDestructor =
112 Record && (!CGM.getCXXABI().HasThisReturn(
113 GlobalDecl(Record->getDestructor(), Dtor_Complete)) ||
115 // If __cxa_atexit is disabled via a flag, a different helper function is
116 // generated elsewhere which uses atexit instead, and it takes the destructor
117 // directly.
118 bool UsingExternalHelper = !CGM.getCodeGenOpts().CXAAtExit;
119 if (Record && (CanRegisterDestructor || UsingExternalHelper)) {
120 assert(!Record->hasTrivialDestructor());
121 CXXDestructorDecl *Dtor = Record->getDestructor();
122
124 if (CGF.getContext().getLangOpts().OpenCL) {
125 auto DestAS =
127 auto DestTy = llvm::PointerType::get(
128 CGM.getLLVMContext(), CGM.getContext().getTargetAddressSpace(DestAS));
129 auto SrcAS = D.getType().getQualifiers().getAddressSpace();
130 if (DestAS == SrcAS)
131 Argument = Addr.getPointer();
132 else
133 // FIXME: On addr space mismatch we are passing NULL. The generation
134 // of the global destructor function should be adjusted accordingly.
135 Argument = llvm::ConstantPointerNull::get(DestTy);
136 } else {
137 Argument = Addr.getPointer();
138 }
139 // Otherwise, the standard logic requires a helper function.
140 } else {
141 Addr = Addr.withElementType(CGF.ConvertTypeForMem(Type));
142 Func = CodeGenFunction(CGM)
144 CGF.needsEHCleanup(DtorKind), &D);
145 Argument = llvm::Constant::getNullValue(CGF.Int8PtrTy);
146 }
147
148 CGM.getCXXABI().registerGlobalDtor(CGF, D, Func, Argument);
149}
150
151/// Emit code to cause the variable at the given address to be considered as
152/// constant from this point onwards.
153static void EmitDeclInvariant(CodeGenFunction &CGF, const VarDecl &D,
154 llvm::Constant *Addr) {
155 return CGF.EmitInvariantStart(
157}
158
160 // Do not emit the intrinsic if we're not optimizing.
161 if (!CGM.getCodeGenOpts().OptimizationLevel)
162 return;
163
164 // Grab the llvm.invariant.start intrinsic.
165 llvm::Intrinsic::ID InvStartID = llvm::Intrinsic::invariant_start;
166 // Overloaded address space type.
167 assert(Addr->getType()->isPointerTy() && "Address must be a pointer");
168 llvm::Type *ObjectPtr[1] = {Addr->getType()};
169 llvm::Function *InvariantStart = CGM.getIntrinsic(InvStartID, ObjectPtr);
170
171 // Emit a call with the size in bytes of the object.
172 uint64_t Width = Size.getQuantity();
173 llvm::Value *Args[2] = {llvm::ConstantInt::getSigned(Int64Ty, Width), Addr};
174 Builder.CreateCall(InvariantStart, Args);
175}
176
178 llvm::GlobalVariable *GV,
179 bool PerformInit) {
180
181 const Expr *Init = D.getInit();
182 QualType T = D.getType();
183
184 // The address space of a static local variable (DeclPtr) may be different
185 // from the address space of the "this" argument of the constructor. In that
186 // case, we need an addrspacecast before calling the constructor.
187 //
188 // struct StructWithCtor {
189 // __device__ StructWithCtor() {...}
190 // };
191 // __device__ void foo() {
192 // __shared__ StructWithCtor s;
193 // ...
194 // }
195 //
196 // For example, in the above CUDA code, the static local variable s has a
197 // "shared" address space qualifier, but the constructor of StructWithCtor
198 // expects "this" in the "generic" address space.
199 unsigned ExpectedAddrSpace = getTypes().getTargetAddressSpace(T);
200 unsigned ActualAddrSpace = GV->getAddressSpace();
201 llvm::Constant *DeclPtr = GV;
202 if (ActualAddrSpace != ExpectedAddrSpace) {
203 llvm::PointerType *PTy =
204 llvm::PointerType::get(getLLVMContext(), ExpectedAddrSpace);
205 DeclPtr = llvm::ConstantExpr::getAddrSpaceCast(DeclPtr, PTy);
206 }
207
208 ConstantAddress DeclAddr(
209 DeclPtr, GV->getValueType(), getContext().getDeclAlign(&D));
210
211 if (!T->isReferenceType()) {
212 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd &&
213 D.hasAttr<OMPThreadPrivateDeclAttr>()) {
214 (void)CGM.getOpenMPRuntime().emitThreadPrivateVarDefinition(
215 &D, DeclAddr, D.getAttr<OMPThreadPrivateDeclAttr>()->getLocation(),
216 PerformInit, this);
217 }
218 bool NeedsDtor =
220 if (PerformInit)
221 EmitDeclInit(*this, D, DeclAddr);
222 if (D.getType().isConstantStorage(getContext(), true, !NeedsDtor))
223 EmitDeclInvariant(*this, D, DeclPtr);
224 else
225 EmitDeclDestroy(*this, D, DeclAddr);
226 return;
227 }
228
229 assert(PerformInit && "cannot have constant initializer which needs "
230 "destruction for reference");
232 EmitStoreOfScalar(RV.getScalarVal(), DeclAddr, false, T);
233}
234
235/// Create a stub function, suitable for being passed to atexit,
236/// which passes the given address to the given destructor function.
238 llvm::FunctionCallee dtor,
239 llvm::Constant *addr) {
240 // Get the destructor function type, void(*)(void).
241 llvm::FunctionType *ty = llvm::FunctionType::get(CGM.VoidTy, false);
242 SmallString<256> FnName;
243 {
244 llvm::raw_svector_ostream Out(FnName);
245 CGM.getCXXABI().getMangleContext().mangleDynamicAtExitDestructor(&VD, Out);
246 }
247
248 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
249 llvm::Function *fn = CGM.CreateGlobalInitOrCleanUpFunction(
250 ty, FnName.str(), FI, VD.getLocation());
251
252 CodeGenFunction CGF(CGM);
253
255 CGM.getContext().VoidTy, fn, FI, FunctionArgList(),
256 VD.getLocation(), VD.getInit()->getExprLoc());
257 // Emit an artificial location for this function.
259
260 llvm::CallInst *call = CGF.Builder.CreateCall(dtor, addr);
261
262 // Make sure the call and the callee agree on calling convention.
263 if (auto *dtorFn = dyn_cast<llvm::Function>(
264 dtor.getCallee()->stripPointerCastsAndAliases()))
265 call->setCallingConv(dtorFn->getCallingConv());
266
267 CGF.FinishFunction();
268
269 // Get a proper function pointer.
270 FunctionProtoType::ExtProtoInfo EPI(getContext().getDefaultCallingConvention(
271 /*IsVariadic=*/false, /*IsCXXMethod=*/false));
273 {getContext().VoidPtrTy}, EPI);
274 return CGM.getFunctionPointer(fn, fnType);
275}
276
277/// Create a stub function, suitable for being passed to __pt_atexit_np,
278/// which passes the given address to the given destructor function.
280 const VarDecl &D, llvm::FunctionCallee Dtor, llvm::Constant *Addr,
281 llvm::FunctionCallee &AtExit) {
282 SmallString<256> FnName;
283 {
284 llvm::raw_svector_ostream Out(FnName);
285 CGM.getCXXABI().getMangleContext().mangleDynamicAtExitDestructor(&D, Out);
286 }
287
288 const CGFunctionInfo &FI = CGM.getTypes().arrangeLLVMFunctionInfo(
291 /*ABIInfoFD=*/nullptr);
292
293 // Get the stub function type, int(*)(int,...).
294 llvm::FunctionType *StubTy =
295 llvm::FunctionType::get(CGM.IntTy, {CGM.IntTy}, true);
296
297 llvm::Function *DtorStub = CGM.CreateGlobalInitOrCleanUpFunction(
298 StubTy, FnName.str(), FI, D.getLocation());
299
300 CodeGenFunction CGF(CGM);
301
302 auto *IPD = ImplicitParamDecl::Create(
303 CGM.getContext(), CGM.getContext().IntTy, ImplicitParamKind::Other);
304 QualType ResTy = CGM.getContext().IntTy;
305
306 FunctionArgList Args{IPD};
307 CGF.StartFunction(GlobalDecl(&D, DynamicInitKind::AtExit), ResTy, DtorStub,
308 FI, Args, D.getLocation(), D.getInit()->getExprLoc());
309
310 // Emit an artificial location for this function.
312
313 llvm::CallInst *call = CGF.Builder.CreateCall(Dtor, Addr);
314
315 // Make sure the call and the callee agree on calling convention.
316 if (auto *DtorFn = dyn_cast<llvm::Function>(
317 Dtor.getCallee()->stripPointerCastsAndAliases()))
318 call->setCallingConv(DtorFn->getCallingConv());
319
320 // Return 0 from function
321 CGF.Builder.CreateStore(llvm::Constant::getNullValue(CGM.IntTy),
322 CGF.ReturnValue);
323
324 CGF.FinishFunction();
325
326 return DtorStub;
327}
328
329/// Register a global destructor using the C atexit runtime function.
331 llvm::FunctionCallee dtor,
332 llvm::Constant *addr) {
333 // Create a function which calls the destructor.
334 llvm::Constant *dtorStub = createAtExitStub(VD, dtor, addr);
336}
337
338/// Register a global destructor using the LLVM 'llvm.global_dtors' global.
340 llvm::FunctionCallee Dtor,
341 llvm::Constant *Addr) {
342 // Create a function which calls the destructor.
343 llvm::Function *dtorStub =
345 CGM.AddGlobalDtor(dtorStub);
346}
347
348void CodeGenFunction::registerGlobalDtorWithAtExit(llvm::Constant *dtorStub) {
349 // extern "C" int atexit(void (*f)(void));
350 assert(dtorStub->getType()->isPointerTy() &&
351 "Argument to atexit has a wrong type.");
352
353 llvm::FunctionType *atexitTy =
354 llvm::FunctionType::get(IntTy, dtorStub->getType(), false);
355
356 llvm::FunctionCallee atexit =
357 CGM.CreateRuntimeFunction(atexitTy, "atexit", llvm::AttributeList(),
358 /*Local=*/true);
359 if (llvm::Function *atexitFn = dyn_cast<llvm::Function>(atexit.getCallee()))
360 atexitFn->setDoesNotThrow();
361
362 EmitNounwindRuntimeCall(atexit, dtorStub);
363}
364
365llvm::Value *
367 // The unatexit subroutine unregisters __dtor functions that were previously
368 // registered by the atexit subroutine. If the referenced function is found,
369 // it is removed from the list of functions that are called at normal program
370 // termination and the unatexit returns a value of 0, otherwise a non-zero
371 // value is returned.
372 //
373 // extern "C" int unatexit(void (*f)(void));
374 assert(dtorStub->getType()->isPointerTy() &&
375 "Argument to unatexit has a wrong type.");
376
377 llvm::FunctionType *unatexitTy =
378 llvm::FunctionType::get(IntTy, {dtorStub->getType()}, /*isVarArg=*/false);
379
380 llvm::FunctionCallee unatexit =
381 CGM.CreateRuntimeFunction(unatexitTy, "unatexit", llvm::AttributeList());
382
383 cast<llvm::Function>(unatexit.getCallee())->setDoesNotThrow();
384
385 return EmitNounwindRuntimeCall(unatexit, dtorStub);
386}
387
389 llvm::GlobalVariable *DeclPtr,
390 bool PerformInit) {
391 // If we've been asked to forbid guard variables, emit an error now.
392 // This diagnostic is hard-coded for Darwin's use case; we can find
393 // better phrasing if someone else needs it.
394 if (CGM.getCodeGenOpts().ForbidGuardVariables)
395 CGM.Error(D.getLocation(),
396 "this initialization requires a guard variable, which "
397 "the kernel does not support");
398
399 CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr, PerformInit);
400}
401
403 llvm::BasicBlock *InitBlock,
404 llvm::BasicBlock *NoInitBlock,
405 GuardKind Kind,
406 const VarDecl *D) {
407 assert((Kind == GuardKind::TlsGuard || D) && "no guarded variable");
408
409 // A guess at how many times we will enter the initialization of a
410 // variable, depending on the kind of variable.
411 static const uint64_t InitsPerTLSVar = 1024;
412 static const uint64_t InitsPerLocalVar = 1024 * 1024;
413
414 llvm::MDNode *Weights;
415 if (Kind == GuardKind::VariableGuard && !D->isLocalVarDecl()) {
416 // For non-local variables, don't apply any weighting for now. Due to our
417 // use of COMDATs, we expect there to be at most one initialization of the
418 // variable per DSO, but we have no way to know how many DSOs will try to
419 // initialize the variable.
420 Weights = nullptr;
421 } else {
422 uint64_t NumInits;
423 // FIXME: For the TLS case, collect and use profiling information to
424 // determine a more accurate brach weight.
425 if (Kind == GuardKind::TlsGuard || D->getTLSKind())
426 NumInits = InitsPerTLSVar;
427 else
428 NumInits = InitsPerLocalVar;
429
430 // The probability of us entering the initializer is
431 // 1 / (total number of times we attempt to initialize the variable).
432 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
433 Weights = MDHelper.createBranchWeights(1, NumInits - 1);
434 }
435
436 Builder.CreateCondBr(NeedsInit, InitBlock, NoInitBlock, Weights);
437}
438
440 llvm::FunctionType *FTy, const Twine &Name, const CGFunctionInfo &FI,
441 SourceLocation Loc, bool TLS, llvm::GlobalVariable::LinkageTypes Linkage) {
442 llvm::Function *Fn = llvm::Function::Create(FTy, Linkage, Name, &getModule());
443
444 if (!getLangOpts().AppleKext && !TLS) {
445 // Set the section if needed.
446 if (const char *Section = getTarget().getStaticInitSectionSpecifier())
447 Fn->setSection(Section);
448 }
449
450 if (Linkage == llvm::GlobalVariable::InternalLinkage)
452 else {
453 SetLLVMFunctionAttributes(GlobalDecl(), FI, Fn, false);
455 getTargetCodeGenInfo().setTargetAttributes(nullptr, Fn, *this);
456 }
457
458 Fn->setCallingConv(getRuntimeCC());
459
460 if (!getLangOpts().Exceptions)
461 Fn->setDoesNotThrow();
462
463 if (getLangOpts().Sanitize.has(SanitizerKind::Address) &&
464 !isInNoSanitizeList(SanitizerKind::Address, Fn, Loc))
465 Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
466
467 if (getLangOpts().Sanitize.has(SanitizerKind::KernelAddress) &&
468 !isInNoSanitizeList(SanitizerKind::KernelAddress, Fn, Loc))
469 Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
470
471 if (getLangOpts().Sanitize.has(SanitizerKind::HWAddress) &&
472 !isInNoSanitizeList(SanitizerKind::HWAddress, Fn, Loc))
473 Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
474
475 if (getLangOpts().Sanitize.has(SanitizerKind::KernelHWAddress) &&
476 !isInNoSanitizeList(SanitizerKind::KernelHWAddress, Fn, Loc))
477 Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
478
479 if (getLangOpts().Sanitize.has(SanitizerKind::MemtagStack) &&
480 !isInNoSanitizeList(SanitizerKind::MemtagStack, Fn, Loc))
481 Fn->addFnAttr(llvm::Attribute::SanitizeMemTag);
482
483 if (getLangOpts().Sanitize.has(SanitizerKind::Type) &&
484 !isInNoSanitizeList(SanitizerKind::Type, Fn, Loc))
485 Fn->addFnAttr(llvm::Attribute::SanitizeType);
486
487 if (getLangOpts().Sanitize.has(SanitizerKind::Thread) &&
488 !isInNoSanitizeList(SanitizerKind::Thread, Fn, Loc))
489 Fn->addFnAttr(llvm::Attribute::SanitizeThread);
490
491 if (getLangOpts().Sanitize.has(SanitizerKind::Concurrency) &&
492 !isInNoSanitizeList(SanitizerKind::Concurrency, Fn, Loc))
493 Fn->addFnAttr(llvm::Attribute::SanitizeConcurrency);
494
495 if (getLangOpts().Sanitize.has(SanitizerKind::NumericalStability) &&
496 !isInNoSanitizeList(SanitizerKind::NumericalStability, Fn, Loc))
497 Fn->addFnAttr(llvm::Attribute::SanitizeNumericalStability);
498
499 if (getLangOpts().Sanitize.has(SanitizerKind::Memory) &&
500 !isInNoSanitizeList(SanitizerKind::Memory, Fn, Loc))
501 Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
502
503 if (getLangOpts().Sanitize.has(SanitizerKind::KernelMemory) &&
504 !isInNoSanitizeList(SanitizerKind::KernelMemory, Fn, Loc))
505 Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
506
507 if (getLangOpts().Sanitize.has(SanitizerKind::SafeStack) &&
508 !isInNoSanitizeList(SanitizerKind::SafeStack, Fn, Loc))
509 Fn->addFnAttr(llvm::Attribute::SafeStack);
510
511 if (getLangOpts().Sanitize.has(SanitizerKind::ShadowCallStack) &&
512 !isInNoSanitizeList(SanitizerKind::ShadowCallStack, Fn, Loc))
513 Fn->addFnAttr(llvm::Attribute::ShadowCallStack);
514
515 return Fn;
516}
517
518/// Create a global pointer to a function that will initialize a global
519/// variable. The user has requested that this pointer be emitted in a specific
520/// section.
521void CodeGenModule::EmitPointerToInitFunc(const VarDecl *D,
522 llvm::GlobalVariable *GV,
523 llvm::Function *InitFunc,
524 InitSegAttr *ISA) {
525 llvm::GlobalVariable *PtrArray = new llvm::GlobalVariable(
526 TheModule, InitFunc->getType(), /*isConstant=*/true,
527 llvm::GlobalValue::PrivateLinkage, InitFunc, "__cxx_init_fn_ptr");
528 PtrArray->setSection(ISA->getSection());
529 addUsedGlobal(PtrArray);
530
531 // If the GV is already in a comdat group, then we have to join it.
532 if (llvm::Comdat *C = GV->getComdat())
533 PtrArray->setComdat(C);
534}
535
536void
537CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
538 llvm::GlobalVariable *Addr,
539 bool PerformInit) {
540
541 // According to E.2.3.1 in CUDA-7.5 Programming guide: __device__,
542 // __constant__ and __shared__ variables defined in namespace scope,
543 // that are of class type, cannot have a non-empty constructor. All
544 // the checks have been done in Sema by now. Whatever initializers
545 // are allowed are empty and we just need to ignore them here.
546 if (getLangOpts().CUDAIsDevice && !getLangOpts().GPUAllowDeviceInit &&
547 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
548 D->hasAttr<CUDASharedAttr>()))
549 return;
550
551 // Check if we've already initialized this decl.
552 auto I = DelayedCXXInitPosition.find(D);
553 if (I != DelayedCXXInitPosition.end() && I->second == ~0U)
554 return;
555
556 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
557 SmallString<256> FnName;
558 {
559 llvm::raw_svector_ostream Out(FnName);
561 }
562
563 // Create a variable initialization function.
564 llvm::Function *Fn = CreateGlobalInitOrCleanUpFunction(
565 FTy, FnName.str(), getTypes().arrangeNullaryFunction(), D->getLocation());
566
567 auto *ISA = D->getAttr<InitSegAttr>();
569 PerformInit);
570
571 llvm::GlobalVariable *COMDATKey =
572 supportsCOMDAT() && D->isExternallyVisible() ? Addr : nullptr;
573
574 if (D->getTLSKind()) {
575 // FIXME: Should we support init_priority for thread_local?
576 // FIXME: We only need to register one __cxa_thread_atexit function for the
577 // entire TU.
578 CXXThreadLocalInits.push_back(Fn);
579 CXXThreadLocalInitVars.push_back(D);
580 } else if (PerformInit && ISA) {
581 // Contract with backend that "init_seg(compiler)" corresponds to priority
582 // 200 and "init_seg(lib)" corresponds to priority 400.
583 int Priority = -1;
584 if (ISA->getSection() == ".CRT$XCC")
585 Priority = 200;
586 else if (ISA->getSection() == ".CRT$XCL")
587 Priority = 400;
588
589 if (Priority != -1)
590 AddGlobalCtor(Fn, Priority, ~0U, COMDATKey);
591 else
592 EmitPointerToInitFunc(D, Addr, Fn, ISA);
593 } else if (auto *IPA = D->getAttr<InitPriorityAttr>()) {
594 OrderGlobalInitsOrStermFinalizers Key(IPA->getPriority(),
595 PrioritizedCXXGlobalInits.size());
596 PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
598 !isUniqueGVALinkage(getContext().GetGVALinkageForVariable(D)) ||
599 D->hasAttr<SelectAnyAttr>()) {
600 // For vague linkage globals, put the initializer into its own global_ctors
601 // entry with the global as a comdat key. This ensures at most one
602 // initializer per DSO runs during DSO dynamic initialization.
603 //
604 // For ELF platforms, this is an important code size and startup time
605 // optimization. For dynamic, non-hidden symbols, the weak guard variable
606 // remains to ensure that other DSOs do not re-initialize the global.
607 //
608 // For PE-COFF platforms, there is no guard variable, and COMDAT
609 // associativity is the only way to ensure vauge linkage globals are
610 // initialized exactly once.
611 //
612 // MachO is the only remaining platform with no comdats that doesn't
613 // benefit from this optimization. The rest are mainly modeled on ELF
614 // behavior.
615 //
616 // C++ requires that inline global variables are initialized in source
617 // order, but this requirement does not exist for templated entities.
618 // llvm.global_ctors does not guarantee initialization order, so in
619 // general, Clang does not fully conform to the ordering requirement.
620 // However, in practice, LLVM emits global_ctors in the provided order, and
621 // users typically don't rely on ordering between inline globals in
622 // different headers which are then transitively included in varying order.
623 // Clang's current behavior is a practical tradeoff, since dropping the
624 // comdat would lead to unacceptable impact on code size and startup time.
625 //
626 // FIXME: Find a solution to guarantee source-order initialization of
627 // inline variables.
628 //
629 // C++ [basic.start.init]p2:
630 // Definitions of explicitly specialized class template static data
631 // members have ordered initialization. Other class template static data
632 // members (i.e., implicitly or explicitly instantiated specializations)
633 // have unordered initialization.
634 //
635 // CXXGlobalInits.size() is the lex order number for the next deferred
636 // VarDecl. Use it when the current VarDecl is non-deferred. Although this
637 // lex order number is shared between current VarDecl and some following
638 // VarDecls, their order of insertion into `llvm.global_ctors` is the same
639 // as the lexing order and the following stable sort would preserve such
640 // order.
641 I = DelayedCXXInitPosition.find(D);
642 unsigned LexOrder =
643 I == DelayedCXXInitPosition.end() ? CXXGlobalInits.size() : I->second;
644 AddGlobalCtor(Fn, 65535, LexOrder, COMDATKey);
645 if (COMDATKey && (getTriple().isOSBinFormatELF() ||
646 getTarget().getCXXABI().isMicrosoft())) {
647 // When COMDAT is used on ELF or in the MS C++ ABI, the key must be in
648 // llvm.used to prevent linker GC.
649 addUsedGlobal(COMDATKey);
650 }
651
652 // If we used a COMDAT key for the global ctor, the init function can be
653 // discarded if the global ctor entry is discarded.
654 // FIXME: Do we need to restrict this to ELF and Wasm?
655 llvm::Comdat *C = Addr->getComdat();
656 if (COMDATKey && C &&
657 (getTarget().getTriple().isOSBinFormatELF() ||
658 getTarget().getTriple().isOSBinFormatWasm())) {
659 Fn->setComdat(C);
660 }
661 } else {
662 I = DelayedCXXInitPosition.find(D); // Re-do lookup in case of re-hash.
663 if (I == DelayedCXXInitPosition.end()) {
664 CXXGlobalInits.push_back(Fn);
665 } else if (I->second != ~0U) {
666 assert(I->second < CXXGlobalInits.size() &&
667 CXXGlobalInits[I->second] == nullptr);
668 CXXGlobalInits[I->second] = Fn;
669 }
670 }
671
672 // Remember that we already emitted the initializer for this global.
673 DelayedCXXInitPosition[D] = ~0U;
674}
675
676void CodeGenModule::EmitCXXThreadLocalInitFunc() {
678 *this, CXXThreadLocals, CXXThreadLocalInits, CXXThreadLocalInitVars);
679
680 CXXThreadLocalInits.clear();
681 CXXThreadLocalInitVars.clear();
682 CXXThreadLocals.clear();
683}
684
685/* Build the initializer for a C++20 module:
686 This is arranged to be run only once regardless of how many times the module
687 might be included transitively. This arranged by using a guard variable.
688
689 If there are no initializers at all (and also no imported modules) we reduce
690 this to an empty function (since the Itanium ABI requires that this function
691 be available to a caller, which might be produced by a different
692 implementation).
693
694 First we call any initializers for imported modules.
695 We then call initializers for the Global Module Fragment (if present)
696 We then call initializers for the current module.
697 We then call initializers for the Private Module Fragment (if present)
698*/
699
700void CodeGenModule::EmitCXXModuleInitFunc(Module *Primary) {
701 assert(Primary->isInterfaceOrPartition() &&
702 "The function should only be called for C++20 named module interface"
703 " or partition.");
704
705 while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
706 CXXGlobalInits.pop_back();
707
708 // As noted above, we create the function, even if it is empty.
709 // Module initializers for imported modules are emitted first.
710
711 SmallVector<llvm::Function *, 8> ModuleInits;
712 for (Module *M : CodeGenUtils::importedModulesToInitialize(Primary, {})) {
713 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
714 SmallString<256> FnName;
715 {
716 llvm::raw_svector_ostream Out(FnName);
717 cast<ItaniumMangleContext>(getCXXABI().getMangleContext())
718 .mangleModuleInitializer(M, Out);
719 }
720 assert(!GetGlobalValue(FnName.str()) &&
721 "We should only have one use of the initializer call");
722 llvm::Function *Fn = llvm::Function::Create(
723 FTy, llvm::Function::ExternalLinkage, FnName.str(), &getModule());
724 ModuleInits.push_back(Fn);
725 }
726
727 // Add any initializers with specified priority; this uses the same approach
728 // as EmitCXXGlobalInitFunc().
729 if (!PrioritizedCXXGlobalInits.empty()) {
730 llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(),
731 PrioritizedCXXGlobalInits.end());
732 for (SmallVectorImpl<GlobalInitData>::iterator
733 I = PrioritizedCXXGlobalInits.begin(),
734 E = PrioritizedCXXGlobalInits.end();
735 I != E;) {
736 SmallVectorImpl<GlobalInitData>::iterator PrioE =
737 std::upper_bound(I + 1, E, *I, GlobalInitPriorityCmp());
738
739 for (; I < PrioE; ++I)
740 ModuleInits.push_back(I->second);
741 }
742 }
743
744 // Now append the ones without specified priority.
745 for (auto *F : CXXGlobalInits)
746 ModuleInits.push_back(F);
747
748 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
749 const CGFunctionInfo &FI = getTypes().arrangeNullaryFunction();
750
751 // We now build the initializer for this module, which has a mangled name
752 // as per the Itanium ABI . The action of the initializer is guarded so that
753 // each init is run just once (even though a module might be imported
754 // multiple times via nested use).
755 llvm::Function *Fn;
756 {
757 SmallString<256> InitFnName;
758 llvm::raw_svector_ostream Out(InitFnName);
759 cast<ItaniumMangleContext>(getCXXABI().getMangleContext())
760 .mangleModuleInitializer(Primary, Out);
762 FTy, llvm::Twine(InitFnName), FI, SourceLocation(), false,
763 llvm::GlobalVariable::ExternalLinkage);
764
765 // If we have a completely empty initializer then we do not want to create
766 // the guard variable.
767 ConstantAddress GuardAddr = ConstantAddress::invalid();
768 if (!ModuleInits.empty()) {
769 // Create the guard var.
770 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
771 getModule(), Int8Ty, /*isConstant=*/false,
772 llvm::GlobalVariable::InternalLinkage,
773 llvm::ConstantInt::get(Int8Ty, 0), InitFnName.str() + "__in_chrg");
774 CharUnits GuardAlign = CharUnits::One();
775 Guard->setAlignment(GuardAlign.getAsAlign());
776 GuardAddr = ConstantAddress(Guard, Int8Ty, GuardAlign);
777 }
778 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, ModuleInits,
779 GuardAddr);
780 }
781
782 // We allow for the case that a module object is added to a linked binary
783 // without a specific call to the the initializer. This also ensures that
784 // implementation partition initializers are called when the partition
785 // is not imported as an interface.
786 AddGlobalCtor(Fn);
787
788 // See the comment in EmitCXXGlobalInitFunc about OpenCL global init
789 // functions.
790 if (getLangOpts().OpenCL) {
792 Fn->setCallingConv(llvm::CallingConv::SPIR_KERNEL);
793 }
794
795 assert(!getLangOpts().CUDA || !getLangOpts().CUDAIsDevice ||
796 getLangOpts().GPUAllowDeviceInit);
797 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice) {
798 if (getTriple().isSPIRV())
799 Fn->setCallingConv(llvm::CallingConv::SPIR_KERNEL);
800 else
801 Fn->setCallingConv(llvm::CallingConv::AMDGPU_KERNEL);
802 Fn->addFnAttr("device-init");
803 }
804
805 // We are done with the inits.
806 PrioritizedCXXGlobalInits.clear();
807 CXXGlobalInits.clear();
808 ModuleInits.clear();
809}
810
812 SmallString<128> FileName = llvm::sys::path::filename(M.getName());
813
814 if (FileName.empty())
815 FileName = "<null>";
816
817 for (size_t i = 0; i < FileName.size(); ++i) {
818 // Replace everything that's not [a-zA-Z0-9._] with a _. This set happens
819 // to be the set of C preprocessing numbers.
821 FileName[i] = '_';
822 }
823
824 return FileName;
825}
826
827static std::string getPrioritySuffix(unsigned int Priority) {
828 assert(Priority <= 65535 && "Priority should always be <= 65535.");
829
830 // Compute the function suffix from priority. Prepend with zeroes to make
831 // sure the function names are also ordered as priorities.
832 std::string PrioritySuffix = llvm::utostr(Priority);
833 PrioritySuffix = std::string(6 - PrioritySuffix.size(), '0') + PrioritySuffix;
834
835 return PrioritySuffix;
836}
837
838void
839CodeGenModule::EmitCXXGlobalInitFunc() {
840 while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
841 CXXGlobalInits.pop_back();
842
843 // When we import C++20 modules, we must run their initializers first.
844 SmallVector<llvm::Function *, 8> ModuleInits;
845 if (CXX20ModuleInits)
847 getContext().getCurrentNamedModule(),
848 ImportedModules.getArrayRef())) {
849 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
850 SmallString<256> FnName;
851 {
852 llvm::raw_svector_ostream Out(FnName);
853 cast<ItaniumMangleContext>(getCXXABI().getMangleContext())
854 .mangleModuleInitializer(M, Out);
855 }
856 assert(!GetGlobalValue(FnName.str()) &&
857 "We should only have one use of the initializer call");
858 llvm::Function *Fn = llvm::Function::Create(
859 FTy, llvm::Function::ExternalLinkage, FnName.str(), &getModule());
860 ModuleInits.push_back(Fn);
861 }
862
863 if (ModuleInits.empty() && CXXGlobalInits.empty() &&
864 PrioritizedCXXGlobalInits.empty())
865 return;
866
867 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
868 const CGFunctionInfo &FI = getTypes().arrangeNullaryFunction();
869
870 // Create our global prioritized initialization function.
871 if (!PrioritizedCXXGlobalInits.empty()) {
872 SmallVector<llvm::Function *, 8> LocalCXXGlobalInits;
873 llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(),
874 PrioritizedCXXGlobalInits.end());
875 // Iterate over "chunks" of ctors with same priority and emit each chunk
876 // into separate function. Note - everything is sorted first by priority,
877 // second - by lex order, so we emit ctor functions in proper order.
878 for (SmallVectorImpl<GlobalInitData >::iterator
879 I = PrioritizedCXXGlobalInits.begin(),
880 E = PrioritizedCXXGlobalInits.end(); I != E; ) {
881 SmallVectorImpl<GlobalInitData >::iterator
882 PrioE = std::upper_bound(I + 1, E, *I, GlobalInitPriorityCmp());
883
884 LocalCXXGlobalInits.clear();
885
886 unsigned int Priority = I->first.priority;
887 llvm::Function *Fn = CreateGlobalInitOrCleanUpFunction(
888 FTy, "_GLOBAL__I_" + getPrioritySuffix(Priority), FI);
889
890 // Prepend the module inits to the highest priority set.
891 if (!ModuleInits.empty()) {
892 for (auto *F : ModuleInits)
893 LocalCXXGlobalInits.push_back(F);
894 ModuleInits.clear();
895 }
896
897 for (; I < PrioE; ++I)
898 LocalCXXGlobalInits.push_back(I->second);
899
900 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, LocalCXXGlobalInits);
901 AddGlobalCtor(Fn, Priority);
902 }
903 PrioritizedCXXGlobalInits.clear();
904 }
905
906 if (getCXXABI().useSinitAndSterm() && ModuleInits.empty() &&
907 CXXGlobalInits.empty())
908 return;
909
910 for (auto *F : CXXGlobalInits)
911 ModuleInits.push_back(F);
912 CXXGlobalInits.clear();
913
914 // Include the filename in the symbol name. Including "sub_" matches gcc
915 // and makes sure these symbols appear lexicographically behind the symbols
916 // with priority emitted above. Module implementation units behave the same
917 // way as a non-modular TU with imports.
918 llvm::Function *Fn;
919 if (CXX20ModuleInits && getContext().getCurrentNamedModule() &&
920 !getContext().getCurrentNamedModule()->isModuleImplementation()) {
921 SmallString<256> InitFnName;
922 llvm::raw_svector_ostream Out(InitFnName);
923 cast<ItaniumMangleContext>(getCXXABI().getMangleContext())
924 .mangleModuleInitializer(getContext().getCurrentNamedModule(), Out);
926 FTy, llvm::Twine(InitFnName), FI, SourceLocation(), false,
927 llvm::GlobalVariable::ExternalLinkage);
928 } else
930 FTy,
931 llvm::Twine("_GLOBAL__sub_I_", getTransformedFileName(getModule())),
932 FI);
933
934 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, ModuleInits);
935 AddGlobalCtor(Fn);
936
937 // In OpenCL global init functions must be converted to kernels in order to
938 // be able to launch them from the host.
939 // FIXME: Some more work might be needed to handle destructors correctly.
940 // Current initialization function makes use of function pointers callbacks.
941 // We can't support function pointers especially between host and device.
942 // However it seems global destruction has little meaning without any
943 // dynamic resource allocation on the device and program scope variables are
944 // destroyed by the runtime when program is released.
945 if (getLangOpts().OpenCL) {
947 Fn->setCallingConv(llvm::CallingConv::SPIR_KERNEL);
948 }
949
950 assert(!getLangOpts().CUDA || !getLangOpts().CUDAIsDevice ||
951 getLangOpts().GPUAllowDeviceInit);
952 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice) {
953 if (getTriple().isSPIRV())
954 Fn->setCallingConv(llvm::CallingConv::SPIR_KERNEL);
955 else
956 Fn->setCallingConv(llvm::CallingConv::AMDGPU_KERNEL);
957 Fn->addFnAttr("device-init");
958 }
959
960 ModuleInits.clear();
961}
962
963void CodeGenModule::EmitCXXGlobalCleanUpFunc() {
964 if (CXXGlobalDtorsOrStermFinalizers.empty() &&
965 PrioritizedCXXStermFinalizers.empty())
966 return;
967
968 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
969 const CGFunctionInfo &FI = getTypes().arrangeNullaryFunction();
970
971 // Create our global prioritized cleanup function.
972 if (!PrioritizedCXXStermFinalizers.empty()) {
973 SmallVector<CXXGlobalDtorsOrStermFinalizer_t, 8> LocalCXXStermFinalizers;
974 llvm::array_pod_sort(PrioritizedCXXStermFinalizers.begin(),
975 PrioritizedCXXStermFinalizers.end());
976 // Iterate over "chunks" of dtors with same priority and emit each chunk
977 // into separate function. Note - everything is sorted first by priority,
978 // second - by lex order, so we emit dtor functions in proper order.
979 for (SmallVectorImpl<StermFinalizerData>::iterator
980 I = PrioritizedCXXStermFinalizers.begin(),
981 E = PrioritizedCXXStermFinalizers.end();
982 I != E;) {
983 SmallVectorImpl<StermFinalizerData>::iterator PrioE =
984 std::upper_bound(I + 1, E, *I, StermFinalizerPriorityCmp());
985
986 LocalCXXStermFinalizers.clear();
987
988 unsigned int Priority = I->first.priority;
989 llvm::Function *Fn = CreateGlobalInitOrCleanUpFunction(
990 FTy, "_GLOBAL__a_" + getPrioritySuffix(Priority), FI);
991
992 for (; I < PrioE; ++I) {
993 llvm::FunctionCallee DtorFn = I->second;
994 LocalCXXStermFinalizers.emplace_back(DtorFn.getFunctionType(),
995 DtorFn.getCallee(), nullptr);
996 }
997
998 CodeGenFunction(*this).GenerateCXXGlobalCleanUpFunc(
999 Fn, LocalCXXStermFinalizers);
1000 AddGlobalDtor(Fn, Priority);
1001 }
1002 PrioritizedCXXStermFinalizers.clear();
1003 }
1004
1005 if (CXXGlobalDtorsOrStermFinalizers.empty())
1006 return;
1007
1008 // Create our global cleanup function.
1009 llvm::Function *Fn =
1010 CreateGlobalInitOrCleanUpFunction(FTy, "_GLOBAL__D_a", FI);
1011
1012 CodeGenFunction(*this).GenerateCXXGlobalCleanUpFunc(
1013 Fn, CXXGlobalDtorsOrStermFinalizers);
1014 AddGlobalDtor(Fn);
1015 CXXGlobalDtorsOrStermFinalizers.clear();
1016}
1017
1018/// Emit the code necessary to initialize the given global variable.
1020 const VarDecl *D,
1021 llvm::GlobalVariable *Addr,
1022 bool PerformInit) {
1023 // Check if we need to emit debug info for variable initializer.
1024 if (D->hasAttr<NoDebugAttr>())
1025 DebugInfo = nullptr; // disable debug info indefinitely for this function
1026
1027 CurEHLocation = D->getBeginLoc();
1028
1030 getContext().VoidTy, Fn, getTypes().arrangeNullaryFunction(),
1031 FunctionArgList());
1032 // Emit an artificial location for this function.
1033 auto AL = ApplyDebugLocation::CreateArtificial(*this);
1034
1035 // Use guarded initialization if the global variable is weak. This
1036 // occurs for, e.g., instantiated static data members and
1037 // definitions explicitly marked weak.
1038 //
1039 // Also use guarded initialization for a variable with dynamic TLS and
1040 // unordered initialization. (If the initialization is ordered, the ABI
1041 // layer will guard the whole-TU initialization for us.)
1042 if (Addr->hasWeakLinkage() || Addr->hasLinkOnceLinkage() ||
1045 EmitCXXGuardedInit(*D, Addr, PerformInit);
1046 } else {
1047 EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit);
1048 }
1049
1051}
1052
1053void
1056 ConstantAddress Guard) {
1057 {
1058 auto NL = ApplyDebugLocation::CreateEmpty(*this);
1060 getTypes().arrangeNullaryFunction(), FunctionArgList());
1061 // Emit an artificial location for this function.
1062 auto AL = ApplyDebugLocation::CreateArtificial(*this);
1063
1064 llvm::BasicBlock *ExitBlock = nullptr;
1065 if (Guard.isValid()) {
1066 // If we have a guard variable, check whether we've already performed
1067 // these initializations. This happens for TLS initialization functions.
1068 llvm::Value *GuardVal = Builder.CreateLoad(Guard);
1069 llvm::Value *Uninit = Builder.CreateIsNull(GuardVal,
1070 "guard.uninitialized");
1071 llvm::BasicBlock *InitBlock = createBasicBlock("init");
1072 ExitBlock = createBasicBlock("exit");
1073 EmitCXXGuardedInitBranch(Uninit, InitBlock, ExitBlock,
1074 GuardKind::TlsGuard, nullptr);
1075 EmitBlock(InitBlock);
1076 // Mark as initialized before initializing anything else. If the
1077 // initializers use previously-initialized thread_local vars, that's
1078 // probably supposed to be OK, but the standard doesn't say.
1079 Builder.CreateStore(llvm::ConstantInt::get(GuardVal->getType(),1), Guard);
1080
1081 // The guard variable can't ever change again.
1083 Guard.getPointer(),
1085 CGM.getDataLayout().getTypeAllocSize(GuardVal->getType())));
1086 }
1087
1088 RunCleanupsScope Scope(*this);
1089
1090 // When building in Objective-C++ ARC mode, create an autorelease pool
1091 // around the global initializers.
1092 if (getLangOpts().ObjCAutoRefCount && getLangOpts().CPlusPlus) {
1093 llvm::Value *token = EmitObjCAutoreleasePoolPush();
1095 }
1096
1097 for (llvm::Function *Decl : Decls) {
1098 if (Decl)
1099 EmitRuntimeCall(Decl, {}, "", Decl->isConvergent());
1100 }
1101
1102 Scope.ForceCleanup();
1103
1104 if (ExitBlock) {
1105 Builder.CreateBr(ExitBlock);
1106 EmitBlock(ExitBlock);
1107 }
1108 }
1109
1111}
1112
1114 llvm::Function *Fn,
1115 ArrayRef<std::tuple<llvm::FunctionType *, llvm::WeakTrackingVH,
1116 llvm::Constant *>>
1117 DtorsOrStermFinalizers) {
1118 {
1119 auto NL = ApplyDebugLocation::CreateEmpty(*this);
1121 getTypes().arrangeNullaryFunction(), FunctionArgList());
1122 // Emit an artificial location for this function.
1123 auto AL = ApplyDebugLocation::CreateArtificial(*this);
1124
1125 // Emit the cleanups, in reverse order from construction.
1126 for (unsigned i = 0, e = DtorsOrStermFinalizers.size(); i != e; ++i) {
1127 llvm::FunctionType *CalleeTy;
1128 llvm::Value *Callee;
1129 llvm::Constant *Arg;
1130 std::tie(CalleeTy, Callee, Arg) = DtorsOrStermFinalizers[e - i - 1];
1131
1132 bool IsConvergent = getLangOpts().assumeFunctionsAreConvergent();
1134 if (IsConvergent)
1135 addConvergenceControlBundle(BundleList);
1136
1137 llvm::CallBase *CI = nullptr;
1138 if (Arg == nullptr) {
1139 assert(
1140 CGM.getCXXABI().useSinitAndSterm() &&
1141 "Arg could not be nullptr unless using sinit and sterm functions.");
1142 CI = Builder.CreateCall(CalleeTy, Callee, {}, BundleList);
1143 } else {
1144 // If the object lives in a different address space, the `this` pointer
1145 // address space won't match the dtor `this` param. An addrspacecast is
1146 // required.
1147 assert(Arg->getType()->isPointerTy());
1148 assert(CalleeTy->getParamType(0)->isPointerTy());
1149 unsigned ActualAddrSpace = Arg->getType()->getPointerAddressSpace();
1150 unsigned ExpectedAddrSpace =
1151 CalleeTy->getParamType(0)->getPointerAddressSpace();
1152 if (ActualAddrSpace != ExpectedAddrSpace) {
1153 llvm::PointerType *PTy =
1154 llvm::PointerType::get(getLLVMContext(), ExpectedAddrSpace);
1155 Arg = llvm::ConstantExpr::getAddrSpaceCast(Arg, PTy);
1156 }
1157
1158 CI = Builder.CreateCall(CalleeTy, Callee, Arg, BundleList);
1159 }
1160
1161 // Make sure the call and the callee agree on calling convention.
1162 if (llvm::Function *F = dyn_cast<llvm::Function>(Callee))
1163 CI->setCallingConv(F->getCallingConv());
1164
1165 setConvergentCallSite(CI, IsConvergent);
1166 }
1167 }
1168
1170}
1171
1172/// generateDestroyHelper - Generates a helper function which, when
1173/// invoked, destroys the given object. The address of the object
1174/// should be in global memory.
1176 Address addr, QualType type, Destroyer *destroyer,
1177 bool useEHCleanupForArray, const VarDecl *VD) {
1180
1181 FunctionArgList args{Dst};
1182 const CGFunctionInfo &FI =
1183 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, args);
1184 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
1185 llvm::Function *fn = CGM.CreateGlobalInitOrCleanUpFunction(
1186 FTy, "__cxx_global_array_dtor", FI, VD->getLocation());
1187
1188 CurEHLocation = VD->getBeginLoc();
1189
1191 getContext().VoidTy, fn, FI, args);
1192 // Emit an artificial location for this function.
1193 auto AL = ApplyDebugLocation::CreateArtificial(*this);
1194
1195 emitDestroy(addr, type, destroyer, useEHCleanupForArray);
1196
1198
1199 return fn;
1200}
static void EmitDeclInit(CodeGenFunction &CGF, const VarDecl &D, ConstantAddress DeclPtr)
Definition CGDeclCXX.cpp:31
static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D, ConstantAddress Addr)
Emit code to cause the destruction of the given variable with static storage duration.
Definition CGDeclCXX.cpp:73
static void EmitDeclInvariant(CodeGenFunction &CGF, const VarDecl &D, llvm::Constant *Addr)
Emit code to cause the variable at the given address to be considered as constant from this point onw...
Defines the clang::LangOptions interface.
static std::string getPrioritySuffix(unsigned priority)
Compute the zero-padded priority suffix used to name priority-specific global init functions,...
static SmallString< 128 > getTransformedFileName(mlir::ModuleOp mlirModule)
llvm::MachO::Record Record
Definition MachO.h:31
CanQualType VoidPtrTy
const LangOptions & getLangOpts() const
CanQualType IntTy
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
unsigned getTargetAddressSpace(LangAS AS) const
Represents a C++ destructor within a class.
Definition DeclCXX.h:2915
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
llvm::Align getAsAlign() const
Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit bytes.
Definition CharUnits.h:159
static CharUnits One()
Construct a CharUnits quantity of one.
Definition CharUnits.h:55
static CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:58
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
Definition Address.h:128
static AggValueSlot forLValue(const LValue &LV, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed, IsSanitizerChecked_t isChecked=IsNotSanitizerChecked)
Definition CGValue.h:649
static ApplyDebugLocation CreateArtificial(CodeGenFunction &CGF)
Apply TemporaryLocation if it is valid.
static ApplyDebugLocation CreateEmpty(CodeGenFunction &CGF)
Set the IRBuilder to not attach debug locations.
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition CGBuilder.h:148
virtual void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D, llvm::FunctionCallee Dtor, llvm::Constant *Addr)=0
Emit code to force the execution of a destructor during global teardown.
virtual bool canCallMismatchedFunctionType() const
Returns true if the target allows calling a function through a pointer with a different signature tha...
Definition CGCXXABI.h:143
virtual void EmitThreadLocalInitFuncs(CodeGenModule &CGM, ArrayRef< const VarDecl * > CXXThreadLocals, ArrayRef< llvm::Function * > CXXThreadLocalInits, ArrayRef< const VarDecl * > CXXThreadLocalInitVars)=0
Emits ABI-required functions necessary to initialize thread_local variables in this translation unit.
MangleContext & getMangleContext()
Gets the mangle context.
Definition CGCXXABI.h:113
CGFunctionInfo - Class to encapsulate the information about a function definition.
virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, Address dest)=0
virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, Address dest, bool threadlocal=false)=0
Enters a new scope for capturing cleanups, all of which will be executed once the scope is exited.
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr, bool PerformInit)
Emit code in this function to perform a guarded variable initialization.
llvm::Constant * createAtExitStub(const VarDecl &VD, llvm::FunctionCallee Dtor, llvm::Constant *Addr)
Create a stub function, suitable for being passed to atexit, which passes the given address to the gi...
void emitDestroy(Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray)
emitDestroy - Immediately perform the destruction of the given object.
Definition CGDecl.cpp:2482
llvm::Function * createTLSAtExitStub(const VarDecl &VD, llvm::FunctionCallee Dtor, llvm::Constant *Addr, llvm::FunctionCallee &AtExit)
Create a stub function, suitable for being passed to __pt_atexit_np, which passes the given address t...
void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit)
EmitComplexExprIntoLValue - Emit the given expression of complex type and place its result into the s...
void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::FunctionCallee fn, llvm::Constant *addr)
Call atexit() with a function that passes the given argument to the given function.
void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr)
Definition CGObjC.cpp:2935
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
const LangOptions & getLangOpts() const
RValue EmitReferenceBindingToExpr(const Expr *E)
Emits a reference binding to the passed in expression.
Definition CGExpr.cpp:705
void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue, bool capturedByInit)
Definition CGDecl.cpp:799
Destroyer * getDestroyer(QualType::DestructionKind destructionKind)
Definition CGDecl.cpp:2338
void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::GlobalVariable *GV, bool PerformInit)
EmitCXXGlobalVarDeclInit - Create the initializer for a C++ variable with global storage.
void StartFunction(GlobalDecl GD, QualType RetTy, llvm::Function *Fn, const CGFunctionInfo &FnInfo, const FunctionArgList &Args, SourceLocation Loc=SourceLocation(), SourceLocation StartLoc=SourceLocation())
Emit code for the start of a function.
void GenerateCXXGlobalInitFunc(llvm::Function *Fn, ArrayRef< llvm::Function * > CXXThreadLocals, ConstantAddress Guard=ConstantAddress::invalid())
GenerateCXXGlobalInitFunc - Generates code for initializing global variables.
void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn, const VarDecl *D, llvm::GlobalVariable *Addr, bool PerformInit)
Emit the code necessary to initialize the given global variable.
void EmitCXXGuardedInitBranch(llvm::Value *NeedsInit, llvm::BasicBlock *InitBlock, llvm::BasicBlock *NoInitBlock, GuardKind Kind, const VarDecl *D)
Emit a branch to select whether or not to perform guarded initialization.
void EmitInvariantStart(llvm::Constant *Addr, CharUnits Size)
llvm::Value * unregisterGlobalDtorWithUnAtExit(llvm::Constant *dtorStub)
Call unatexit() with function dtorStub.
llvm::CallInst * EmitNounwindRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty)
void registerGlobalDtorWithLLVM(const VarDecl &D, llvm::FunctionCallee fn, llvm::Constant *addr)
Registers the dtor using 'llvm.global_dtors' for platforms that do not support an 'atexit()' function...
bool needsEHCleanup(QualType::DestructionKind kind)
Determines whether an EH cleanup is required to destroy a type with the given destruction kind.
llvm::CallInst * EmitRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
llvm::Type * ConvertTypeForMem(QualType T)
void GenerateCXXGlobalCleanUpFunc(llvm::Function *Fn, ArrayRef< std::tuple< llvm::FunctionType *, llvm::WeakTrackingVH, llvm::Constant * > > DtorsOrStermFinalizers)
GenerateCXXGlobalCleanUpFunc - Generates code for cleaning up global variables.
llvm::Value * EmitObjCAutoreleasePoolPush()
Produce the code to do a objc_autoreleasepool_push.
Definition CGObjC.cpp:2743
CodeGenTypes & getTypes() const
static TypeEvaluationKind getEvaluationKind(QualType T)
getEvaluationKind - Return the TypeEvaluationKind of QualType T.
void EmitAggExpr(const Expr *E, AggValueSlot AS)
EmitAggExpr - Emit the computation of the specified expression of aggregate type.
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type,...
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
void FinishFunction(SourceLocation EndLoc=SourceLocation())
FinishFunction - Complete IR generation of the current function.
llvm::Function * generateDestroyHelper(Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray, const VarDecl *VD)
generateDestroyHelper - Generates a helper function which, when invoked, destroys the given object.
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
llvm::LLVMContext & getLLVMContext()
void EmitStoreOfScalar(llvm::Value *Value, Address Addr, bool Volatile, QualType Ty, AlignmentSource Source=AlignmentSource::Type, bool isInit=false, bool isNontemporal=false)
EmitStoreOfScalar - Store a scalar value to an address, taking care to appropriately convert from the...
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition CGStmt.cpp:655
This class organizes the cross-function state that is used while generating LLVM code.
void SetInternalFunctionAttributes(GlobalDecl GD, llvm::Function *F, const CGFunctionInfo &FI)
Set the attributes on the LLVM function for the given decl and function info.
llvm::Module & getModule() const
llvm::FunctionCallee getAddrAndTypeOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo=nullptr, llvm::FunctionType *FnType=nullptr, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Definition CGCXX.cpp:283
bool isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn, SourceLocation Loc) const
const LangOptions & getLangOpts() const
const TargetInfo & getTarget() const
void addUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.used metadata.
const llvm::Triple & getTriple() const
void AddGlobalDtor(llvm::Function *Dtor, int Priority=65535, bool IsDtorAttrFunc=false)
AddGlobalDtor - Add a function to the list that will be called when the module is unloaded.
ASTContext & getContext() const
const TargetCodeGenInfo & getTargetCodeGenInfo()
const CodeGenOptions & getCodeGenOpts() const
llvm::LLVMContext & getLLVMContext()
llvm::GlobalValue * GetGlobalValue(StringRef Ref)
void GenKernelArgMetadata(llvm::Function *FN, const FunctionDecl *FD=nullptr, CodeGenFunction *CGF=nullptr)
OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument information in the program executab...
CGObjCRuntime & getObjCRuntime()
Return a reference to the configured Objective-C runtime.
void SetLLVMFunctionAttributes(GlobalDecl GD, const CGFunctionInfo &Info, llvm::Function *F, bool IsThunk)
Set the LLVM function attributes (sext, zext, etc).
void AddGlobalCtor(llvm::Function *Ctor, int Priority=65535, unsigned LexOrder=~0U, llvm::Constant *AssociatedData=nullptr)
AddGlobalCtor - Add a function to the list that will be called before main() runs.
void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F)
Set the LLVM function attributes which only apply to a function definition.
llvm::Function * CreateGlobalInitOrCleanUpFunction(llvm::FunctionType *ty, const Twine &name, const CGFunctionInfo &FI, SourceLocation Loc=SourceLocation(), bool TLS=false, llvm::GlobalVariable::LinkageTypes Linkage=llvm::GlobalVariable::InternalLinkage)
unsigned getTargetAddressSpace(QualType T) const
const CGFunctionInfo & arrangeNullaryFunction()
A nullary function is a freestanding function of type 'void ()'.
Definition CGCall.cpp:824
A specialization of Address that requires the address to be an LLVM Constant.
Definition Address.h:296
static ConstantAddress invalid()
Definition Address.h:304
llvm::Constant * getPointer() const
Definition Address.h:308
FunctionArgList - Type for representing both the decl and type of parameters to a function.
Definition CGCall.h:378
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
Definition CGValue.h:42
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Definition CGValue.h:72
virtual void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const
setTargetAttributes - Provides a convenient hook to handle extra target-specific attributes for the g...
Definition TargetInfo.h:113
virtual LangAS getAddrSpaceOfCxaAtexitPtrParam() const
Get address space of pointer parameter for __cxa_atexit.
Definition TargetInfo.h:359
T * getAttr() const
Definition DeclBase.h:582
SourceLocation getLocation() const
Definition DeclBase.h:448
bool hasAttr() const
Definition DeclBase.h:586
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:833
This represents one expression.
Definition Expr.h:114
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4855
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:60
static ImplicitParamDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, ImplicitParamKind ParamKind)
Create implicit parameter.
Definition Decl.cpp:5710
bool assumeFunctionsAreConvergent() const
virtual void mangleDynamicInitializer(const VarDecl *D, raw_ostream &)=0
bool isInterfaceOrPartition() const
Definition Module.h:892
bool isExternallyVisible() const
Definition Decl.h:435
A (possibly-)qualified type.
Definition TypeBase.h:938
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8618
bool isConstantStorage(const ASTContext &Ctx, bool ExcludeCtor, bool ExcludeDtor)
Definition TypeBase.h:1037
LangAS getAddressSpace() const
Definition TypeBase.h:572
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
Encodes a location in the source.
The base class of the type hierarchy.
Definition TypeBase.h:1879
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isReferenceType() const
Definition TypeBase.h:8839
QualType getType() const
Definition Decl.h:725
Represents a variable declaration or definition.
Definition Decl.h:934
TLSKind getTLSKind() const
Definition Decl.cpp:2149
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1249
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
Definition Decl.cpp:2843
const Expr * getInit() const
Definition Decl.h:1393
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1192
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition Decl.h:960
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition Decl.h:1276
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition Decl.cpp:2771
llvm::SmallVector< Module *, 8 > importedModulesToInitialize(Module *Primary, llvm::ArrayRef< Module * > Imported)
The C++20 named modules whose Itanium initializer function the global init function of a translation ...
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
Definition CGValue.h:146
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
Top level wrappers for InstallAPI frontend operations.
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition Specifiers.h:216
@ CPlusPlus
bool isUniqueGVALinkage(GVALinkage L)
Do we know that this will be the only definition of this symbol (excluding inlining-only definitions)...
Definition Linkage.h:86
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition Linkage.h:24
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
Definition Linkage.h:54
const FunctionProtoType * T
@ Dtor_Complete
Complete object dtor.
Definition ABI.h:36
LLVM_READONLY bool isPreprocessingNumberBody(unsigned char c)
Return true if this is the body character of a C preprocessing number, which is [a-zA-Z0-9_.
Definition CharInfo.h:168
U cast(CodeGen::Address addr)
Definition Address.h:327
@ Other
Other implicit parameter.
Definition Decl.h:1787
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
llvm::CallingConv::ID getRuntimeCC() const
Extra information about a function prototype.
Definition TypeBase.h:5633