1//===--- CodeGenModule.h - Per-Module state for LLVM CodeGen ----*- C++ -*-===//
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 is the internal per-translation-unit state used for llvm translation.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H
14#define LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H
15
16#include "CGVTables.h"
17#include "CodeGenTypeCache.h"
18#include "CodeGenTypes.h"
19#include "SanitizerMetadata.h"
20#include "TrapReasonBuilder.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclOpenMP.h"
24#include "clang/AST/GlobalDecl.h"
25#include "clang/AST/Mangle.h"
26#include "clang/Basic/ABI.h"
27#include "clang/Basic/LangOptions.h"
28#include "clang/Basic/NoSanitizeList.h"
29#include "clang/Basic/ProfileList.h"
30#include "clang/Basic/StackExhaustionHandler.h"
31#include "clang/Basic/TargetInfo.h"
32#include "clang/Basic/XRayLists.h"
33#include "clang/Lex/PreprocessorOptions.h"
34#include "llvm/ADT/DenseMap.h"
35#include "llvm/ADT/MapVector.h"
36#include "llvm/ADT/SetVector.h"
37#include "llvm/ADT/SmallPtrSet.h"
38#include "llvm/ADT/StringMap.h"
39#include "llvm/IR/Module.h"
40#include "llvm/IR/ValueHandle.h"
41#include "llvm/Transforms/Utils/SanitizerStats.h"
42#include <optional>
43
44namespace llvm {
45class Module;
46class Constant;
47class ConstantInt;
48class Function;
49class GlobalValue;
50class DataLayout;
51class FunctionType;
52class LLVMContext;
53class IndexedInstrProfReader;
54
55namespace vfs {
56class FileSystem;
57}
58}
59
60namespace clang {
61class ASTContext;
62class AtomicType;
63class FunctionDecl;
64class IdentifierInfo;
65class ObjCImplementationDecl;
66class ObjCEncodeExpr;
67class BlockExpr;
68class CharUnits;
69class Decl;
70class Expr;
71class Stmt;
72class StringLiteral;
73class NamedDecl;
74class PointerAuthSchema;
75class ValueDecl;
76class VarDecl;
77class LangOptions;
78class CodeGenOptions;
79class HeaderSearchOptions;
80class DiagnosticsEngine;
81class AnnotateAttr;
82class CXXDestructorDecl;
83class Module;
84class CoverageSourceInfo;
85class InitSegAttr;
86
87namespace CodeGen {
88
89class CodeGenFunction;
90class CodeGenTBAA;
91class CGCXXABI;
92class CGDebugInfo;
93class CGObjCRuntime;
94class CGOpenCLRuntime;
95class CGOpenMPRuntime;
96class CGCUDARuntime;
97class CGHLSLRuntime;
98class CoverageMappingModuleGen;
99class TargetCodeGenInfo;
100
101enum ForDefinition_t : bool {
102 NotForDefinition = false,
103 ForDefinition = true
104};
105
106/// The Counter with an optional additional Counter for
107/// branches. `Skipped` counter can be calculated with `Executed` and
108/// a common Counter (like `Parent`) as `(Parent-Executed)`.
109///
110/// In SingleByte mode, Counters are binary. Subtraction is not
111/// applicable (but addition is capable). In this case, both
112/// `Executed` and `Skipped` counters are required. `Skipped` is
113/// `None` by default. It is allocated in the coverage mapping.
114///
115/// There might be cases that `Parent` could be induced with
116/// `(Executed+Skipped)`. This is not always applicable.
117class CounterPair {
118public:
119 /// Optional value.
120 class ValueOpt {
121 private:
122 static constexpr uint32_t None = (1u << 31); /// None is allocated.
123 static constexpr uint32_t Mask = None - 1;
124
125 uint32_t Val;
126
127 public:
128 ValueOpt() : Val(None) {}
129
130 ValueOpt(unsigned InitVal) {
131 assert(!(InitVal & ~Mask));
132 Val = InitVal;
133 }
134
135 bool hasValue() const { return !(Val & None); }
136
137 operator uint32_t() const { return Val; }
138 };
139
140 ValueOpt Executed;
141 ValueOpt Skipped; /// May be None.
142
143 /// Initialized with Skipped=None.
144 CounterPair(unsigned Val) : Executed(Val) {}
145
146 // FIXME: Should work with {None, None}
147 CounterPair() : Executed(0) {}
148};
149
150struct OrderGlobalInitsOrStermFinalizers {
151 unsigned int priority;
152 unsigned int lex_order;
153 OrderGlobalInitsOrStermFinalizers(unsigned int p, unsigned int l)
154 : priority(p), lex_order(l) {}
155
156 bool operator==(const OrderGlobalInitsOrStermFinalizers &RHS) const {
157 return priority == RHS.priority && lex_order == RHS.lex_order;
158 }
159
160 bool operator<(const OrderGlobalInitsOrStermFinalizers &RHS) const {
161 return std::tie(args: priority, args: lex_order) <
162 std::tie(args: RHS.priority, args: RHS.lex_order);
163 }
164};
165
166struct ObjCEntrypoints {
167 ObjCEntrypoints() { memset(s: this, c: 0, n: sizeof(*this)); }
168
169 /// void objc_alloc(id);
170 llvm::FunctionCallee objc_alloc;
171
172 /// void objc_allocWithZone(id);
173 llvm::FunctionCallee objc_allocWithZone;
174
175 /// void objc_alloc_init(id);
176 llvm::FunctionCallee objc_alloc_init;
177
178 /// void objc_autoreleasePoolPop(void*);
179 llvm::FunctionCallee objc_autoreleasePoolPop;
180
181 /// void objc_autoreleasePoolPop(void*);
182 /// Note this method is used when we are using exception handling
183 llvm::FunctionCallee objc_autoreleasePoolPopInvoke;
184
185 /// void *objc_autoreleasePoolPush(void);
186 llvm::Function *objc_autoreleasePoolPush;
187
188 /// id objc_autorelease(id);
189 llvm::Function *objc_autorelease;
190
191 /// id objc_autorelease(id);
192 /// Note this is the runtime method not the intrinsic.
193 llvm::FunctionCallee objc_autoreleaseRuntimeFunction;
194
195 /// id objc_autoreleaseReturnValue(id);
196 llvm::Function *objc_autoreleaseReturnValue;
197
198 /// void objc_copyWeak(id *dest, id *src);
199 llvm::Function *objc_copyWeak;
200
201 /// void objc_destroyWeak(id*);
202 llvm::Function *objc_destroyWeak;
203
204 /// id objc_initWeak(id*, id);
205 llvm::Function *objc_initWeak;
206
207 /// id objc_loadWeak(id*);
208 llvm::Function *objc_loadWeak;
209
210 /// id objc_loadWeakRetained(id*);
211 llvm::Function *objc_loadWeakRetained;
212
213 /// void objc_moveWeak(id *dest, id *src);
214 llvm::Function *objc_moveWeak;
215
216 /// id objc_retain(id);
217 llvm::Function *objc_retain;
218
219 /// id objc_retain(id);
220 /// Note this is the runtime method not the intrinsic.
221 llvm::FunctionCallee objc_retainRuntimeFunction;
222
223 /// id objc_retainAutorelease(id);
224 llvm::Function *objc_retainAutorelease;
225
226 /// id objc_retainAutoreleaseReturnValue(id);
227 llvm::Function *objc_retainAutoreleaseReturnValue;
228
229 /// id objc_retainAutoreleasedReturnValue(id);
230 llvm::Function *objc_retainAutoreleasedReturnValue;
231
232 /// id objc_retainBlock(id);
233 llvm::Function *objc_retainBlock;
234
235 /// void objc_release(id);
236 llvm::Function *objc_release;
237
238 /// void objc_release(id);
239 /// Note this is the runtime method not the intrinsic.
240 llvm::FunctionCallee objc_releaseRuntimeFunction;
241
242 /// void objc_storeStrong(id*, id);
243 llvm::Function *objc_storeStrong;
244
245 /// id objc_storeWeak(id*, id);
246 llvm::Function *objc_storeWeak;
247
248 /// id objc_unsafeClaimAutoreleasedReturnValue(id);
249 llvm::Function *objc_unsafeClaimAutoreleasedReturnValue;
250
251 /// A void(void) inline asm to use to mark that the return value of
252 /// a call will be immediately retain.
253 llvm::InlineAsm *retainAutoreleasedReturnValueMarker;
254
255 /// void clang.arc.use(...);
256 llvm::Function *clang_arc_use;
257
258 /// void clang.arc.noop.use(...);
259 llvm::Function *clang_arc_noop_use;
260};
261
262/// This class records statistics on instrumentation based profiling.
263class InstrProfStats {
264 uint32_t VisitedInMainFile = 0;
265 uint32_t MissingInMainFile = 0;
266 uint32_t Visited = 0;
267 uint32_t Missing = 0;
268 uint32_t Mismatched = 0;
269
270public:
271 InstrProfStats() = default;
272 /// Record that we've visited a function and whether or not that function was
273 /// in the main source file.
274 void addVisited(bool MainFile) {
275 if (MainFile)
276 ++VisitedInMainFile;
277 ++Visited;
278 }
279 /// Record that a function we've visited has no profile data.
280 void addMissing(bool MainFile) {
281 if (MainFile)
282 ++MissingInMainFile;
283 ++Missing;
284 }
285 /// Record that a function we've visited has mismatched profile data.
286 void addMismatched(bool MainFile) { ++Mismatched; }
287 /// Whether or not the stats we've gathered indicate any potential problems.
288 bool hasDiagnostics() { return Missing || Mismatched; }
289 /// Report potential problems we've found to \c Diags.
290 void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile);
291};
292
293/// A pair of helper functions for a __block variable.
294class BlockByrefHelpers : public llvm::FoldingSetNode {
295 // MSVC requires this type to be complete in order to process this
296 // header.
297public:
298 llvm::Constant *CopyHelper;
299 llvm::Constant *DisposeHelper;
300
301 /// The alignment of the field. This is important because
302 /// different offsets to the field within the byref struct need to
303 /// have different helper functions.
304 CharUnits Alignment;
305
306 BlockByrefHelpers(CharUnits alignment)
307 : CopyHelper(nullptr), DisposeHelper(nullptr), Alignment(alignment) {}
308 BlockByrefHelpers(const BlockByrefHelpers &) = default;
309 virtual ~BlockByrefHelpers();
310
311 void Profile(llvm::FoldingSetNodeID &id) const {
312 id.AddInteger(I: Alignment.getQuantity());
313 profileImpl(id);
314 }
315 virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0;
316
317 virtual bool needsCopy() const { return true; }
318 virtual void emitCopy(CodeGenFunction &CGF, Address dest, Address src) = 0;
319
320 virtual bool needsDispose() const { return true; }
321 virtual void emitDispose(CodeGenFunction &CGF, Address field) = 0;
322};
323
324/// This class organizes the cross-function state that is used while generating
325/// LLVM code.
326class CodeGenModule : public CodeGenTypeCache {
327 CodeGenModule(const CodeGenModule &) = delete;
328 void operator=(const CodeGenModule &) = delete;
329
330public:
331 struct Structor {
332 Structor()
333 : Priority(0), LexOrder(~0u), Initializer(nullptr),
334 AssociatedData(nullptr) {}
335 Structor(int Priority, unsigned LexOrder, llvm::Constant *Initializer,
336 llvm::Constant *AssociatedData)
337 : Priority(Priority), LexOrder(LexOrder), Initializer(Initializer),
338 AssociatedData(AssociatedData) {}
339 int Priority;
340 unsigned LexOrder;
341 llvm::Constant *Initializer;
342 llvm::Constant *AssociatedData;
343 };
344
345 typedef std::vector<Structor> CtorList;
346
347private:
348 ASTContext &Context;
349 const LangOptions &LangOpts;
350 IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS; // Only used for debug info.
351 const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
352 const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
353 const CodeGenOptions &CodeGenOpts;
354 unsigned NumAutoVarInit = 0;
355 llvm::Module &TheModule;
356 DiagnosticsEngine &Diags;
357 const TargetInfo &Target;
358 std::unique_ptr<CGCXXABI> ABI;
359 llvm::LLVMContext &VMContext;
360 std::string ModuleNameHash;
361 bool CXX20ModuleInits = false;
362 std::unique_ptr<CodeGenTBAA> TBAA;
363
364 mutable std::unique_ptr<TargetCodeGenInfo> TheTargetCodeGenInfo;
365
366 // This should not be moved earlier, since its initialization depends on some
367 // of the previous reference members being already initialized and also checks
368 // if TheTargetCodeGenInfo is NULL
369 std::unique_ptr<CodeGenTypes> Types;
370
371 /// Holds information about C++ vtables.
372 CodeGenVTables VTables;
373
374 std::unique_ptr<CGObjCRuntime> ObjCRuntime;
375 std::unique_ptr<CGOpenCLRuntime> OpenCLRuntime;
376 std::unique_ptr<CGOpenMPRuntime> OpenMPRuntime;
377 std::unique_ptr<CGCUDARuntime> CUDARuntime;
378 std::unique_ptr<CGHLSLRuntime> HLSLRuntime;
379 std::unique_ptr<CGDebugInfo> DebugInfo;
380 std::unique_ptr<ObjCEntrypoints> ObjCData;
381 llvm::MDNode *NoObjCARCExceptionsMetadata = nullptr;
382 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader;
383 InstrProfStats PGOStats;
384 std::unique_ptr<llvm::SanitizerStatReport> SanStats;
385 StackExhaustionHandler StackHandler;
386
387 // A set of references that have only been seen via a weakref so far. This is
388 // used to remove the weak of the reference if we ever see a direct reference
389 // or a definition.
390 llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences;
391
392 /// This contains all the decls which have definitions but/ which are deferred
393 /// for emission and therefore should only be output if they are actually
394 /// used. If a decl is in this, then it is known to have not been referenced
395 /// yet.
396 llvm::DenseMap<StringRef, GlobalDecl> DeferredDecls;
397
398 llvm::StringSet<llvm::BumpPtrAllocator> DeferredResolversToEmit;
399
400 /// This is a list of deferred decls which we have seen that *are* actually
401 /// referenced. These get code generated when the module is done.
402 std::vector<GlobalDecl> DeferredDeclsToEmit;
403 void addDeferredDeclToEmit(GlobalDecl GD) {
404 DeferredDeclsToEmit.emplace_back(args&: GD);
405 addEmittedDeferredDecl(GD);
406 }
407
408 /// Decls that were DeferredDecls and have now been emitted.
409 llvm::DenseMap<llvm::StringRef, GlobalDecl> EmittedDeferredDecls;
410
411 void addEmittedDeferredDecl(GlobalDecl GD) {
412 // Reemission is only needed in incremental mode.
413 if (!Context.getLangOpts().IncrementalExtensions)
414 return;
415
416 // Assume a linkage by default that does not need reemission.
417 auto L = llvm::GlobalValue::ExternalLinkage;
418 if (llvm::isa<FunctionDecl>(Val: GD.getDecl()))
419 L = getFunctionLinkage(GD);
420 else if (auto *VD = llvm::dyn_cast<VarDecl>(Val: GD.getDecl()))
421 L = getLLVMLinkageVarDefinition(VD);
422
423 if (llvm::GlobalValue::isInternalLinkage(Linkage: L) ||
424 llvm::GlobalValue::isLinkOnceLinkage(Linkage: L) ||
425 llvm::GlobalValue::isWeakLinkage(Linkage: L)) {
426 EmittedDeferredDecls[getMangledName(GD)] = GD;
427 }
428 }
429
430 /// List of alias we have emitted. Used to make sure that what they point to
431 /// is defined once we get to the end of the of the translation unit.
432 std::vector<GlobalDecl> Aliases;
433
434 /// List of multiversion functions to be emitted. This list is processed in
435 /// conjunction with other deferred symbols and is used to ensure that
436 /// multiversion function resolvers and ifuncs are defined and emitted.
437 std::vector<GlobalDecl> MultiVersionFuncs;
438
439 llvm::MapVector<StringRef, llvm::TrackingVH<llvm::Constant>> Replacements;
440
441 /// List of global values to be replaced with something else. Used when we
442 /// want to replace a GlobalValue but can't identify it by its mangled name
443 /// anymore (because the name is already taken).
444 llvm::SmallVector<std::pair<llvm::GlobalValue *, llvm::Constant *>, 8>
445 GlobalValReplacements;
446
447 /// Variables for which we've emitted globals containing their constant
448 /// values along with the corresponding globals, for opportunistic reuse.
449 llvm::DenseMap<const VarDecl*, llvm::GlobalVariable*> InitializerConstants;
450
451 /// Set of global decls for which we already diagnosed mangled name conflict.
452 /// Required to not issue a warning (on a mangling conflict) multiple times
453 /// for the same decl.
454 llvm::DenseSet<GlobalDecl> DiagnosedConflictingDefinitions;
455
456 /// A queue of (optional) vtables to consider emitting.
457 std::vector<const CXXRecordDecl*> DeferredVTables;
458
459 /// A queue of (optional) vtables that may be emitted opportunistically.
460 std::vector<const CXXRecordDecl *> OpportunisticVTables;
461
462 /// List of global values which are required to be present in the object file;
463 /// bitcast to i8*. This is used for forcing visibility of symbols which may
464 /// otherwise be optimized out.
465 std::vector<llvm::WeakTrackingVH> LLVMUsed;
466 std::vector<llvm::WeakTrackingVH> LLVMCompilerUsed;
467
468 /// Store the list of global constructors and their respective priorities to
469 /// be emitted when the translation unit is complete.
470 CtorList GlobalCtors;
471
472 /// Store the list of global destructors and their respective priorities to be
473 /// emitted when the translation unit is complete.
474 CtorList GlobalDtors;
475
476 /// An ordered map of canonical GlobalDecls to their mangled names.
477 llvm::MapVector<GlobalDecl, StringRef> MangledDeclNames;
478 llvm::StringMap<GlobalDecl, llvm::BumpPtrAllocator> Manglings;
479
480 /// Global annotations.
481 std::vector<llvm::Constant*> Annotations;
482
483 // Store deferred function annotations so they can be emitted at the end with
484 // most up to date ValueDecl that will have all the inherited annotations.
485 llvm::MapVector<StringRef, const ValueDecl *> DeferredAnnotations;
486
487 /// Map used to get unique annotation strings.
488 llvm::StringMap<llvm::Constant*> AnnotationStrings;
489
490 /// Used for uniquing of annotation arguments.
491 llvm::DenseMap<unsigned, llvm::Constant *> AnnotationArgs;
492
493 llvm::StringMap<llvm::GlobalVariable *> CFConstantStringMap;
494
495 llvm::DenseMap<llvm::Constant *, llvm::GlobalVariable *> ConstantStringMap;
496 llvm::DenseMap<const UnnamedGlobalConstantDecl *, llvm::GlobalVariable *>
497 UnnamedGlobalConstantDeclMap;
498 llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap;
499 llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardMap;
500 llvm::DenseMap<const Expr*, llvm::Constant *> MaterializedGlobalTemporaryMap;
501
502 llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap;
503 llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap;
504
505 /// Map used to get unique type descriptor constants for sanitizers.
506 llvm::DenseMap<QualType, llvm::Constant *> TypeDescriptorMap;
507
508 /// Map used to track internal linkage functions declared within
509 /// extern "C" regions.
510 typedef llvm::MapVector<IdentifierInfo *,
511 llvm::GlobalValue *> StaticExternCMap;
512 StaticExternCMap StaticExternCValues;
513
514 /// thread_local variables defined or used in this TU.
515 std::vector<const VarDecl *> CXXThreadLocals;
516
517 /// thread_local variables with initializers that need to run
518 /// before any thread_local variable in this TU is odr-used.
519 std::vector<llvm::Function *> CXXThreadLocalInits;
520 std::vector<const VarDecl *> CXXThreadLocalInitVars;
521
522 /// Global variables with initializers that need to run before main.
523 std::vector<llvm::Function *> CXXGlobalInits;
524
525 /// When a C++ decl with an initializer is deferred, null is
526 /// appended to CXXGlobalInits, and the index of that null is placed
527 /// here so that the initializer will be performed in the correct
528 /// order. Once the decl is emitted, the index is replaced with ~0U to ensure
529 /// that we don't re-emit the initializer.
530 llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition;
531
532 /// To remember which types did require a vector deleting destructor body.
533 /// This set basically contains classes that have virtual destructor and new[]
534 /// was emitted for the class.
535 llvm::SmallPtrSet<const CXXRecordDecl *, 16> RequireVectorDeletingDtor;
536
537 typedef std::pair<OrderGlobalInitsOrStermFinalizers, llvm::Function *>
538 GlobalInitData;
539
540 // When a tail call is performed on an "undefined" symbol, on PPC without pc
541 // relative feature, the tail call is not allowed. In "EmitCall" for such
542 // tail calls, the "undefined" symbols may be forward declarations, their
543 // definitions are provided in the module after the callsites. For such tail
544 // calls, diagnose message should not be emitted.
545 llvm::SmallSetVector<std::pair<const FunctionDecl *, SourceLocation>, 4>
546 MustTailCallUndefinedGlobals;
547
548 struct GlobalInitPriorityCmp {
549 bool operator()(const GlobalInitData &LHS,
550 const GlobalInitData &RHS) const {
551 return LHS.first.priority < RHS.first.priority;
552 }
553 };
554
555 /// Global variables with initializers whose order of initialization is set by
556 /// init_priority attribute.
557 SmallVector<GlobalInitData, 8> PrioritizedCXXGlobalInits;
558
559 /// Global destructor functions and arguments that need to run on termination.
560 /// When UseSinitAndSterm is set, it instead contains sterm finalizer
561 /// functions, which also run on unloading a shared library.
562 typedef std::tuple<llvm::FunctionType *, llvm::WeakTrackingVH,
563 llvm::Constant *>
564 CXXGlobalDtorsOrStermFinalizer_t;
565 SmallVector<CXXGlobalDtorsOrStermFinalizer_t, 8>
566 CXXGlobalDtorsOrStermFinalizers;
567
568 typedef std::pair<OrderGlobalInitsOrStermFinalizers, llvm::Function *>
569 StermFinalizerData;
570
571 struct StermFinalizerPriorityCmp {
572 bool operator()(const StermFinalizerData &LHS,
573 const StermFinalizerData &RHS) const {
574 return LHS.first.priority < RHS.first.priority;
575 }
576 };
577
578 /// Global variables with sterm finalizers whose order of initialization is
579 /// set by init_priority attribute.
580 SmallVector<StermFinalizerData, 8> PrioritizedCXXStermFinalizers;
581
582 /// The complete set of modules that has been imported.
583 llvm::SetVector<clang::Module *> ImportedModules;
584
585 /// The set of modules for which the module initializers
586 /// have been emitted.
587 llvm::SmallPtrSet<clang::Module *, 16> EmittedModuleInitializers;
588
589 /// A vector of metadata strings for linker options.
590 SmallVector<llvm::MDNode *, 16> LinkerOptionsMetadata;
591
592 /// A vector of metadata strings for dependent libraries for ELF.
593 SmallVector<llvm::MDNode *, 16> ELFDependentLibraries;
594
595 /// @name Cache for Objective-C runtime types
596 /// @{
597
598 /// Cached reference to the class for constant strings. This value has type
599 /// int * but is actually an Obj-C class pointer.
600 llvm::WeakTrackingVH CFConstantStringClassRef;
601
602 /// The type used to describe the state of a fast enumeration in
603 /// Objective-C's for..in loop.
604 QualType ObjCFastEnumerationStateType;
605
606 /// @}
607
608 /// Lazily create the Objective-C runtime
609 void createObjCRuntime();
610
611 void createOpenCLRuntime();
612 void createOpenMPRuntime();
613 void createCUDARuntime();
614 void createHLSLRuntime();
615
616 bool isTriviallyRecursive(const FunctionDecl *F);
617 bool shouldEmitFunction(GlobalDecl GD);
618 // Whether a global variable should be emitted by CUDA/HIP host/device
619 // related attributes.
620 bool shouldEmitCUDAGlobalVar(const VarDecl *VD) const;
621 bool shouldOpportunisticallyEmitVTables();
622 /// Map used to be sure we don't emit the same CompoundLiteral twice.
623 llvm::DenseMap<const CompoundLiteralExpr *, llvm::GlobalVariable *>
624 EmittedCompoundLiterals;
625
626 /// Map of the global blocks we've emitted, so that we don't have to re-emit
627 /// them if the constexpr evaluator gets aggressive.
628 llvm::DenseMap<const BlockExpr *, llvm::Constant *> EmittedGlobalBlocks;
629
630 /// @name Cache for Blocks Runtime Globals
631 /// @{
632
633 llvm::Constant *NSConcreteGlobalBlock = nullptr;
634 llvm::Constant *NSConcreteStackBlock = nullptr;
635
636 llvm::FunctionCallee BlockObjectAssign = nullptr;
637 llvm::FunctionCallee BlockObjectDispose = nullptr;
638
639 llvm::Type *BlockDescriptorType = nullptr;
640 llvm::Type *GenericBlockLiteralType = nullptr;
641
642 struct {
643 int GlobalUniqueCount;
644 } Block;
645
646 GlobalDecl initializedGlobalDecl;
647
648 /// @}
649
650 /// void @llvm.lifetime.start(i64 %size, i8* nocapture <ptr>)
651 llvm::Function *LifetimeStartFn = nullptr;
652
653 /// void @llvm.lifetime.end(i64 %size, i8* nocapture <ptr>)
654 llvm::Function *LifetimeEndFn = nullptr;
655
656 /// void @llvm.fake.use(...)
657 llvm::Function *FakeUseFn = nullptr;
658
659 std::unique_ptr<SanitizerMetadata> SanitizerMD;
660
661 llvm::MapVector<const Decl *, bool> DeferredEmptyCoverageMappingDecls;
662
663 std::unique_ptr<CoverageMappingModuleGen> CoverageMapping;
664
665 /// Mapping from canonical types to their metadata identifiers. We need to
666 /// maintain this mapping because identifiers may be formed from distinct
667 /// MDNodes.
668 typedef llvm::DenseMap<QualType, llvm::Metadata *> MetadataTypeMap;
669 MetadataTypeMap MetadataIdMap;
670 MetadataTypeMap VirtualMetadataIdMap;
671 MetadataTypeMap GeneralizedMetadataIdMap;
672
673 // Helps squashing blocks of TopLevelStmtDecl into a single llvm::Function
674 // when used with -fincremental-extensions.
675 std::pair<std::unique_ptr<CodeGenFunction>, const TopLevelStmtDecl *>
676 GlobalTopLevelStmtBlockInFlight;
677
678 llvm::DenseMap<GlobalDecl, uint16_t> PtrAuthDiscriminatorHashes;
679
680 llvm::DenseMap<const CXXRecordDecl *, std::optional<PointerAuthQualifier>>
681 VTablePtrAuthInfos;
682 std::optional<PointerAuthQualifier>
683 computeVTPointerAuthentication(const CXXRecordDecl *ThisClass);
684
685 AtomicOptions AtomicOpts;
686
687 // A set of functions which should be hot-patched; see
688 // -fms-hotpatch-functions-file (and -list). This will nearly always be empty.
689 // The list is sorted for binary-searching.
690 std::vector<std::string> MSHotPatchFunctions;
691
692public:
693 CodeGenModule(ASTContext &C, IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
694 const HeaderSearchOptions &headersearchopts,
695 const PreprocessorOptions &ppopts,
696 const CodeGenOptions &CodeGenOpts, llvm::Module &M,
697 DiagnosticsEngine &Diags,
698 CoverageSourceInfo *CoverageInfo = nullptr);
699
700 ~CodeGenModule();
701
702 void clear();
703
704 /// Finalize LLVM code generation.
705 void Release();
706
707 /// Get the current Atomic options.
708 AtomicOptions getAtomicOpts() { return AtomicOpts; }
709
710 /// Set the current Atomic options.
711 void setAtomicOpts(AtomicOptions AO) { AtomicOpts = AO; }
712
713 /// Return true if we should emit location information for expressions.
714 bool getExpressionLocationsEnabled() const;
715
716 /// Return a reference to the configured Objective-C runtime.
717 CGObjCRuntime &getObjCRuntime() {
718 if (!ObjCRuntime) createObjCRuntime();
719 return *ObjCRuntime;
720 }
721
722 /// Return true iff an Objective-C runtime has been configured.
723 bool hasObjCRuntime() { return !!ObjCRuntime; }
724
725 /// Check if a direct method should use precondition thunks (exposed symbols).
726 /// This applies to ALL direct methods (including variadic).
727 /// Returns false if OMD is null or not a direct method.
728 ///
729 /// Also checks the runtime family, currently we only support NeXT.
730 /// TODO: Add support for GNUStep as well.
731 bool usePreconditionThunk(const ObjCMethodDecl *OMD) const {
732 return OMD && OMD->isDirectMethod() &&
733 getLangOpts().ObjCRuntime.allowsDirectDispatch() &&
734 getLangOpts().ObjCRuntime.isNeXTFamily() &&
735 getCodeGenOpts().ObjCDirectPreconditionThunk;
736 }
737
738 /// Check if a direct method should use precondition thunks at call sites.
739 /// This applies only to non-variadic direct methods.
740 /// Returns false if OMD is null or not eligible for thunks (variadic
741 /// methods).
742 bool shouldHavePreconditionThunk(const ObjCMethodDecl *OMD) const {
743 return OMD && usePreconditionThunk(OMD) && !OMD->isVariadic();
744 }
745
746 /// Check if a direct method should have inline precondition checks at call
747 /// sites. This applies to direct methods that cannot use thunks (variadic
748 /// methods). These methods get exposed symbols but need inline precondition
749 /// checks instead of thunks. Returns false if OMD is null or not eligible.
750 bool shouldHavePreconditionInline(const ObjCMethodDecl *OMD) const {
751 return OMD && usePreconditionThunk(OMD) && OMD->isVariadic();
752 }
753
754 const std::string &getModuleNameHash() const { return ModuleNameHash; }
755
756 /// Return a reference to the configured OpenCL runtime.
757 CGOpenCLRuntime &getOpenCLRuntime() {
758 assert(OpenCLRuntime != nullptr);
759 return *OpenCLRuntime;
760 }
761
762 /// Return a reference to the configured OpenMP runtime.
763 CGOpenMPRuntime &getOpenMPRuntime() {
764 assert(OpenMPRuntime != nullptr);
765 return *OpenMPRuntime;
766 }
767
768 /// Return a reference to the configured CUDA runtime.
769 CGCUDARuntime &getCUDARuntime() {
770 assert(CUDARuntime != nullptr);
771 return *CUDARuntime;
772 }
773
774 /// Return a reference to the configured HLSL runtime.
775 CGHLSLRuntime &getHLSLRuntime() {
776 assert(HLSLRuntime != nullptr);
777 return *HLSLRuntime;
778 }
779
780 ObjCEntrypoints &getObjCEntrypoints() const {
781 assert(ObjCData != nullptr);
782 return *ObjCData;
783 }
784
785 // Version checking functions, used to implement ObjC's @available:
786 // i32 @__isOSVersionAtLeast(i32, i32, i32)
787 llvm::FunctionCallee IsOSVersionAtLeastFn = nullptr;
788 // i32 @__isPlatformVersionAtLeast(i32, i32, i32, i32)
789 llvm::FunctionCallee IsPlatformVersionAtLeastFn = nullptr;
790
791 InstrProfStats &getPGOStats() { return PGOStats; }
792 llvm::IndexedInstrProfReader *getPGOReader() const { return PGOReader.get(); }
793
794 CoverageMappingModuleGen *getCoverageMapping() const {
795 return CoverageMapping.get();
796 }
797
798 llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) {
799 return StaticLocalDeclMap[D];
800 }
801 void setStaticLocalDeclAddress(const VarDecl *D,
802 llvm::Constant *C) {
803 StaticLocalDeclMap[D] = C;
804 }
805
806 llvm::Constant *
807 getOrCreateStaticVarDecl(const VarDecl &D,
808 llvm::GlobalValue::LinkageTypes Linkage);
809
810 llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) {
811 return StaticLocalDeclGuardMap[D];
812 }
813 void setStaticLocalDeclGuardAddress(const VarDecl *D,
814 llvm::GlobalVariable *C) {
815 StaticLocalDeclGuardMap[D] = C;
816 }
817
818 Address createUnnamedGlobalFrom(const VarDecl &D, llvm::Constant *Constant,
819 CharUnits Align);
820
821 bool lookupRepresentativeDecl(StringRef MangledName,
822 GlobalDecl &Result) const;
823
824 llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) {
825 return AtomicSetterHelperFnMap[Ty];
826 }
827 void setAtomicSetterHelperFnMap(QualType Ty,
828 llvm::Constant *Fn) {
829 AtomicSetterHelperFnMap[Ty] = Fn;
830 }
831
832 llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) {
833 return AtomicGetterHelperFnMap[Ty];
834 }
835 void setAtomicGetterHelperFnMap(QualType Ty,
836 llvm::Constant *Fn) {
837 AtomicGetterHelperFnMap[Ty] = Fn;
838 }
839
840 llvm::Constant *getTypeDescriptorFromMap(QualType Ty) {
841 return TypeDescriptorMap[Ty];
842 }
843 void setTypeDescriptorInMap(QualType Ty, llvm::Constant *C) {
844 TypeDescriptorMap[Ty] = C;
845 }
846
847 CGDebugInfo *getModuleDebugInfo() { return DebugInfo.get(); }
848
849 llvm::MDNode *getNoObjCARCExceptionsMetadata() {
850 if (!NoObjCARCExceptionsMetadata)
851 NoObjCARCExceptionsMetadata = llvm::MDNode::get(Context&: getLLVMContext(), MDs: {});
852 return NoObjCARCExceptionsMetadata;
853 }
854
855 ASTContext &getContext() const { return Context; }
856 const LangOptions &getLangOpts() const { return LangOpts; }
857 const IntrusiveRefCntPtr<llvm::vfs::FileSystem> &getFileSystem() const {
858 return FS;
859 }
860 const HeaderSearchOptions &getHeaderSearchOpts()
861 const { return HeaderSearchOpts; }
862 const PreprocessorOptions &getPreprocessorOpts()
863 const { return PreprocessorOpts; }
864 const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
865 llvm::Module &getModule() const { return TheModule; }
866 DiagnosticsEngine &getDiags() const { return Diags; }
867 const llvm::DataLayout &getDataLayout() const {
868 return TheModule.getDataLayout();
869 }
870 const TargetInfo &getTarget() const { return Target; }
871 const llvm::Triple &getTriple() const { return Target.getTriple(); }
872 bool supportsCOMDAT() const;
873 void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO);
874
875 const ABIInfo &getABIInfo();
876 CGCXXABI &getCXXABI() const { return *ABI; }
877 llvm::LLVMContext &getLLVMContext() { return VMContext; }
878
879 bool shouldUseTBAA() const { return TBAA != nullptr; }
880
881 const TargetCodeGenInfo &getTargetCodeGenInfo();
882
883 CodeGenTypes &getTypes() { return *Types; }
884
885 CodeGenVTables &getVTables() { return VTables; }
886
887 ItaniumVTableContext &getItaniumVTableContext() {
888 return VTables.getItaniumVTableContext();
889 }
890
891 const ItaniumVTableContext &getItaniumVTableContext() const {
892 return VTables.getItaniumVTableContext();
893 }
894
895 MicrosoftVTableContext &getMicrosoftVTableContext() {
896 return VTables.getMicrosoftVTableContext();
897 }
898
899 CtorList &getGlobalCtors() { return GlobalCtors; }
900 CtorList &getGlobalDtors() { return GlobalDtors; }
901
902 /// getTBAATypeInfo - Get metadata used to describe accesses to objects of
903 /// the given type.
904 llvm::MDNode *getTBAATypeInfo(QualType QTy);
905
906 /// getTBAAAccessInfo - Get TBAA information that describes an access to
907 /// an object of the given type.
908 TBAAAccessInfo getTBAAAccessInfo(QualType AccessType);
909
910 /// getTBAAVTablePtrAccessInfo - Get the TBAA information that describes an
911 /// access to a virtual table pointer.
912 TBAAAccessInfo getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType);
913
914 llvm::MDNode *getTBAAStructInfo(QualType QTy);
915
916 /// getTBAABaseTypeInfo - Get metadata that describes the given base access
917 /// type. Return null if the type is not suitable for use in TBAA access tags.
918 llvm::MDNode *getTBAABaseTypeInfo(QualType QTy);
919
920 /// getTBAAAccessTagInfo - Get TBAA tag for a given memory access.
921 llvm::MDNode *getTBAAAccessTagInfo(TBAAAccessInfo Info);
922
923 /// mergeTBAAInfoForCast - Get merged TBAA information for the purposes of
924 /// type casts.
925 TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
926 TBAAAccessInfo TargetInfo);
927
928 /// mergeTBAAInfoForConditionalOperator - Get merged TBAA information for the
929 /// purposes of conditional operator.
930 TBAAAccessInfo mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
931 TBAAAccessInfo InfoB);
932
933 /// mergeTBAAInfoForMemoryTransfer - Get merged TBAA information for the
934 /// purposes of memory transfer calls.
935 TBAAAccessInfo mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
936 TBAAAccessInfo SrcInfo);
937
938 /// getTBAAInfoForSubobject - Get TBAA information for an access with a given
939 /// base lvalue.
940 TBAAAccessInfo getTBAAInfoForSubobject(LValue Base, QualType AccessType) {
941 if (Base.getTBAAInfo().isMayAlias())
942 return TBAAAccessInfo::getMayAliasInfo();
943 return getTBAAAccessInfo(AccessType);
944 }
945
946 bool isPaddedAtomicType(QualType type);
947 bool isPaddedAtomicType(const AtomicType *type);
948
949 /// DecorateInstructionWithTBAA - Decorate the instruction with a TBAA tag.
950 void DecorateInstructionWithTBAA(llvm::Instruction *Inst,
951 TBAAAccessInfo TBAAInfo);
952
953 /// Adds !invariant.barrier !tag to instruction
954 void DecorateInstructionWithInvariantGroup(llvm::Instruction *I,
955 const CXXRecordDecl *RD);
956
957 /// Emit the given number of characters as a value of type size_t.
958 llvm::ConstantInt *getSize(CharUnits numChars);
959
960 /// Set the visibility for the given LLVM GlobalValue.
961 void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const;
962
963 void setDSOLocal(llvm::GlobalValue *GV) const;
964
965 bool shouldMapVisibilityToDLLExport(const NamedDecl *D) const {
966 return getLangOpts().hasDefaultVisibilityExportMapping() && D &&
967 (D->getLinkageAndVisibility().getVisibility() ==
968 DefaultVisibility) &&
969 (getLangOpts().isAllDefaultVisibilityExportMapping() ||
970 (getLangOpts().isExplicitDefaultVisibilityExportMapping() &&
971 D->getLinkageAndVisibility().isVisibilityExplicit()));
972 }
973 void setDLLImportDLLExport(llvm::GlobalValue *GV, GlobalDecl D) const;
974 void setDLLImportDLLExport(llvm::GlobalValue *GV, const NamedDecl *D) const;
975 /// Set visibility, dllimport/dllexport and dso_local.
976 /// This must be called after dllimport/dllexport is set.
977 void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const;
978 void setGVProperties(llvm::GlobalValue *GV, const NamedDecl *D) const;
979
980 void setGVPropertiesAux(llvm::GlobalValue *GV, const NamedDecl *D) const;
981
982 /// Set the TLS mode for the given LLVM GlobalValue for the thread-local
983 /// variable declaration D.
984 void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const;
985
986 /// Get LLVM TLS mode from CodeGenOptions.
987 llvm::GlobalVariable::ThreadLocalMode GetDefaultLLVMTLSModel() const;
988
989 static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
990 switch (V) {
991 case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility;
992 case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility;
993 case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
994 }
995 llvm_unreachable("unknown visibility!");
996 }
997
998 llvm::Constant *GetAddrOfGlobal(GlobalDecl GD,
999 ForDefinition_t IsForDefinition
1000 = NotForDefinition);
1001
1002 /// Will return a global variable of the given type. If a variable with a
1003 /// different type already exists then a new variable with the right type
1004 /// will be created and all uses of the old variable will be replaced with a
1005 /// bitcast to the new variable.
1006 llvm::GlobalVariable *
1007 CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty,
1008 llvm::GlobalValue::LinkageTypes Linkage,
1009 llvm::Align Alignment);
1010
1011 llvm::Function *CreateGlobalInitOrCleanUpFunction(
1012 llvm::FunctionType *ty, const Twine &name, const CGFunctionInfo &FI,
1013 SourceLocation Loc = SourceLocation(), bool TLS = false,
1014 llvm::GlobalVariable::LinkageTypes Linkage =
1015 llvm::GlobalVariable::InternalLinkage);
1016
1017 /// Return the AST address space of the underlying global variable for D, as
1018 /// determined by its declaration. Normally this is the same as the address
1019 /// space of D's type, but in CUDA, address spaces are associated with
1020 /// declarations, not types. If D is nullptr, return the default address
1021 /// space for global variable.
1022 ///
1023 /// For languages without explicit address spaces, if D has default address
1024 /// space, target-specific global or constant address space may be returned.
1025 LangAS GetGlobalVarAddressSpace(const VarDecl *D);
1026
1027 /// Return the AST address space of constant literal, which is used to emit
1028 /// the constant literal as global variable in LLVM IR.
1029 /// Note: This is not necessarily the address space of the constant literal
1030 /// in AST. For address space agnostic language, e.g. C++, constant literal
1031 /// in AST is always in default address space.
1032 LangAS GetGlobalConstantAddressSpace() const;
1033
1034 /// Return the llvm::Constant for the address of the given global variable.
1035 /// If Ty is non-null and if the global doesn't exist, then it will be created
1036 /// with the specified type instead of whatever the normal requested type
1037 /// would be. If IsForDefinition is true, it is guaranteed that an actual
1038 /// global with type Ty will be returned, not conversion of a variable with
1039 /// the same mangled name but some other type.
1040 llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
1041 llvm::Type *Ty = nullptr,
1042 ForDefinition_t IsForDefinition
1043 = NotForDefinition);
1044
1045 /// Return the address of the given function. If Ty is non-null, then this
1046 /// function will use the specified type if it has to create it.
1047 llvm::Constant *GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty = nullptr,
1048 bool ForVTable = false,
1049 bool DontDefer = false,
1050 ForDefinition_t IsForDefinition
1051 = NotForDefinition);
1052
1053 // Return the function body address of the given function.
1054 llvm::Constant *GetFunctionStart(const ValueDecl *Decl);
1055
1056 /// Return a function pointer for a reference to the given function.
1057 /// This correctly handles weak references, but does not apply a
1058 /// pointer signature.
1059 llvm::Constant *getRawFunctionPointer(GlobalDecl GD,
1060 llvm::Type *Ty = nullptr);
1061
1062 /// Return the ABI-correct function pointer value for a reference
1063 /// to the given function. This will apply a pointer signature if
1064 /// necessary, caching the result for the given function.
1065 llvm::Constant *getFunctionPointer(GlobalDecl GD, llvm::Type *Ty = nullptr);
1066
1067 /// Return the ABI-correct function pointer value for a reference
1068 /// to the given function. This will apply a pointer signature if
1069 /// necessary.
1070 llvm::Constant *getFunctionPointer(llvm::Constant *Pointer,
1071 QualType FunctionType);
1072
1073 llvm::Constant *getMemberFunctionPointer(const FunctionDecl *FD,
1074 llvm::Type *Ty = nullptr);
1075
1076 llvm::Constant *getMemberFunctionPointer(llvm::Constant *Pointer,
1077 QualType FT);
1078
1079 CGPointerAuthInfo getFunctionPointerAuthInfo(QualType T);
1080
1081 CGPointerAuthInfo getMemberFunctionPointerAuthInfo(QualType FT);
1082
1083 CGPointerAuthInfo getPointerAuthInfoForPointeeType(QualType type);
1084
1085 CGPointerAuthInfo getPointerAuthInfoForType(QualType type);
1086
1087 bool shouldSignPointer(const PointerAuthSchema &Schema);
1088 llvm::Constant *getConstantSignedPointer(llvm::Constant *Pointer,
1089 const PointerAuthSchema &Schema,
1090 llvm::Constant *StorageAddress,
1091 GlobalDecl SchemaDecl,
1092 QualType SchemaType);
1093
1094 llvm::Constant *
1095 getConstantSignedPointer(llvm::Constant *Pointer, unsigned Key,
1096 llvm::Constant *StorageAddress,
1097 llvm::ConstantInt *OtherDiscriminator);
1098
1099 llvm::ConstantInt *
1100 getPointerAuthOtherDiscriminator(const PointerAuthSchema &Schema,
1101 GlobalDecl SchemaDecl, QualType SchemaType);
1102
1103 uint16_t getPointerAuthDeclDiscriminator(GlobalDecl GD);
1104 std::optional<CGPointerAuthInfo>
1105 getVTablePointerAuthInfo(CodeGenFunction *Context,
1106 const CXXRecordDecl *Record,
1107 llvm::Value *StorageAddress);
1108
1109 std::optional<PointerAuthQualifier>
1110 getVTablePointerAuthentication(const CXXRecordDecl *thisClass);
1111
1112 CGPointerAuthInfo EmitPointerAuthInfo(const RecordDecl *RD);
1113
1114 // Return whether RTTI information should be emitted for this target.
1115 bool shouldEmitRTTI(bool ForEH = false) {
1116 return (ForEH || getLangOpts().RTTI) &&
1117 (!getLangOpts().isTargetDevice() || !getTriple().isGPU());
1118 }
1119
1120 /// Get the address of the RTTI descriptor for the given type.
1121 llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
1122
1123 /// Get the address of a GUID.
1124 ConstantAddress GetAddrOfMSGuidDecl(const MSGuidDecl *GD);
1125
1126 /// Get the address of a UnnamedGlobalConstant
1127 ConstantAddress
1128 GetAddrOfUnnamedGlobalConstantDecl(const UnnamedGlobalConstantDecl *GCD);
1129
1130 /// Get the address of a template parameter object.
1131 ConstantAddress
1132 GetAddrOfTemplateParamObject(const TemplateParamObjectDecl *TPO);
1133
1134 /// Get the address of the thunk for the given global decl.
1135 llvm::Constant *GetAddrOfThunk(StringRef Name, llvm::Type *FnTy,
1136 GlobalDecl GD);
1137
1138 /// Get a reference to the target of VD.
1139 ConstantAddress GetWeakRefReference(const ValueDecl *VD);
1140
1141 /// Returns the assumed alignment of an opaque pointer to the given class.
1142 CharUnits getClassPointerAlignment(const CXXRecordDecl *CD);
1143
1144 /// Returns the minimum object size for an object of the given class type
1145 /// (or a class derived from it).
1146 CharUnits getMinimumClassObjectSize(const CXXRecordDecl *CD);
1147
1148 /// Returns the minimum object size for an object of the given type.
1149 CharUnits getMinimumObjectSize(QualType Ty) {
1150 if (CXXRecordDecl *RD = Ty->getAsCXXRecordDecl())
1151 return getMinimumClassObjectSize(CD: RD);
1152 return getContext().getTypeSizeInChars(T: Ty);
1153 }
1154
1155 /// Returns the assumed alignment of a virtual base of a class.
1156 CharUnits getVBaseAlignment(CharUnits DerivedAlign,
1157 const CXXRecordDecl *Derived,
1158 const CXXRecordDecl *VBase);
1159
1160 /// Given a class pointer with an actual known alignment, and the
1161 /// expected alignment of an object at a dynamic offset w.r.t that
1162 /// pointer, return the alignment to assume at the offset.
1163 CharUnits getDynamicOffsetAlignment(CharUnits ActualAlign,
1164 const CXXRecordDecl *Class,
1165 CharUnits ExpectedTargetAlign);
1166
1167 CharUnits
1168 computeNonVirtualBaseClassOffset(const CXXRecordDecl *DerivedClass,
1169 CastExpr::path_const_iterator Start,
1170 CastExpr::path_const_iterator End);
1171
1172 /// Returns the offset from a derived class to a class. Returns null if the
1173 /// offset is 0.
1174 llvm::Constant *
1175 GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
1176 CastExpr::path_const_iterator PathBegin,
1177 CastExpr::path_const_iterator PathEnd);
1178
1179 llvm::FoldingSet<BlockByrefHelpers> ByrefHelpersCache;
1180
1181 /// Fetches the global unique block count.
1182 int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; }
1183
1184 /// Fetches the type of a generic block descriptor.
1185 llvm::Type *getBlockDescriptorType();
1186
1187 /// The type of a generic block literal.
1188 llvm::Type *getGenericBlockLiteralType();
1189
1190 /// Gets the address of a block which requires no captures.
1191 llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, StringRef Name);
1192
1193 /// Returns the address of a block which requires no caputres, or null if
1194 /// we've yet to emit the block for BE.
1195 llvm::Constant *getAddrOfGlobalBlockIfEmitted(const BlockExpr *BE) {
1196 return EmittedGlobalBlocks.lookup(Val: BE);
1197 }
1198
1199 /// Notes that BE's global block is available via Addr. Asserts that BE
1200 /// isn't already emitted.
1201 void setAddrOfGlobalBlock(const BlockExpr *BE, llvm::Constant *Addr);
1202
1203 /// Return a pointer to a constant CFString object for the given string.
1204 ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal);
1205
1206 /// Return a constant array for the given string.
1207 llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E);
1208
1209 /// Return a pointer to a constant array for the given string literal.
1210 ConstantAddress
1211 GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
1212 StringRef Name = ".str");
1213
1214 /// Return a pointer to a constant array for the given ObjCEncodeExpr node.
1215 ConstantAddress
1216 GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
1217
1218 /// Returns a pointer to a character array containing the literal and a
1219 /// terminating '\0' character. The result has pointer to array type.
1220 ///
1221 /// \param GlobalName If provided, the name to use for the global (if one is
1222 /// created).
1223 ConstantAddress GetAddrOfConstantCString(const std::string &Str,
1224 StringRef GlobalName = ".str");
1225
1226 /// Returns a pointer to a constant global variable for the given file-scope
1227 /// compound literal expression.
1228 ConstantAddress GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E);
1229
1230 /// If it's been emitted already, returns the GlobalVariable corresponding to
1231 /// a compound literal. Otherwise, returns null.
1232 llvm::GlobalVariable *
1233 getAddrOfConstantCompoundLiteralIfEmitted(const CompoundLiteralExpr *E);
1234
1235 /// Notes that CLE's GlobalVariable is GV. Asserts that CLE isn't already
1236 /// emitted.
1237 void setAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *CLE,
1238 llvm::GlobalVariable *GV);
1239
1240 /// Returns a pointer to a global variable representing a temporary
1241 /// with static or thread storage duration.
1242 ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E,
1243 const Expr *Inner);
1244
1245 /// Retrieve the record type that describes the state of an
1246 /// Objective-C fast enumeration loop (for..in).
1247 QualType getObjCFastEnumerationStateType();
1248
1249 // Produce code for this constructor/destructor. This method doesn't try
1250 // to apply any ABI rules about which other constructors/destructors
1251 // are needed or if they are alias to each other.
1252 llvm::Function *codegenCXXStructor(GlobalDecl GD);
1253
1254 /// Return the address of the constructor/destructor of the given type.
1255 llvm::Constant *
1256 getAddrOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo = nullptr,
1257 llvm::FunctionType *FnType = nullptr,
1258 bool DontDefer = false,
1259 ForDefinition_t IsForDefinition = NotForDefinition) {
1260 return cast<llvm::Constant>(Val: getAddrAndTypeOfCXXStructor(GD, FnInfo, FnType,
1261 DontDefer,
1262 IsForDefinition)
1263 .getCallee());
1264 }
1265
1266 llvm::FunctionCallee getAddrAndTypeOfCXXStructor(
1267 GlobalDecl GD, const CGFunctionInfo *FnInfo = nullptr,
1268 llvm::FunctionType *FnType = nullptr, bool DontDefer = false,
1269 ForDefinition_t IsForDefinition = NotForDefinition);
1270
1271 /// Given a builtin id for a function like "__builtin_fabsf", return a
1272 /// Function* for "fabsf".
1273 llvm::Constant *getBuiltinLibFunction(const FunctionDecl *FD,
1274 unsigned BuiltinID);
1275
1276 llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type *> Tys = {});
1277
1278 void AddCXXGlobalInit(llvm::Function *F) { CXXGlobalInits.push_back(x: F); }
1279
1280 /// Emit code for a single top level declaration.
1281 void EmitTopLevelDecl(Decl *D);
1282
1283 /// Stored a deferred empty coverage mapping for an unused
1284 /// and thus uninstrumented top level declaration.
1285 void AddDeferredUnusedCoverageMapping(Decl *D);
1286
1287 /// Remove the deferred empty coverage mapping as this
1288 /// declaration is actually instrumented.
1289 void ClearUnusedCoverageMapping(const Decl *D);
1290
1291 /// Emit all the deferred coverage mappings
1292 /// for the uninstrumented functions.
1293 void EmitDeferredUnusedCoverageMappings();
1294
1295 /// Emit an alias for "main" if it has no arguments (needed for wasm).
1296 void EmitMainVoidAlias();
1297
1298 /// Tell the consumer that this variable has been instantiated.
1299 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD);
1300
1301 /// If the declaration has internal linkage but is inside an
1302 /// extern "C" linkage specification, prepare to emit an alias for it
1303 /// to the expected name.
1304 template<typename SomeDecl>
1305 void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV);
1306
1307 /// Add a global to a list to be added to the llvm.used metadata.
1308 void addUsedGlobal(llvm::GlobalValue *GV);
1309
1310 /// Add a global to a list to be added to the llvm.compiler.used metadata.
1311 void addCompilerUsedGlobal(llvm::GlobalValue *GV);
1312
1313 /// Add a global to a list to be added to the llvm.compiler.used metadata.
1314 void addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV);
1315
1316 /// Add a destructor and object to add to the C++ global destructor function.
1317 void AddCXXDtorEntry(llvm::FunctionCallee DtorFn, llvm::Constant *Object) {
1318 CXXGlobalDtorsOrStermFinalizers.emplace_back(Args: DtorFn.getFunctionType(),
1319 Args: DtorFn.getCallee(), Args&: Object);
1320 }
1321
1322 /// Add an sterm finalizer to the C++ global cleanup function.
1323 void AddCXXStermFinalizerEntry(llvm::FunctionCallee DtorFn) {
1324 CXXGlobalDtorsOrStermFinalizers.emplace_back(Args: DtorFn.getFunctionType(),
1325 Args: DtorFn.getCallee(), Args: nullptr);
1326 }
1327
1328 /// Add an sterm finalizer to its own llvm.global_dtors entry.
1329 void AddCXXStermFinalizerToGlobalDtor(llvm::Function *StermFinalizer,
1330 int Priority) {
1331 AddGlobalDtor(Dtor: StermFinalizer, Priority);
1332 }
1333
1334 void AddCXXPrioritizedStermFinalizerEntry(llvm::Function *StermFinalizer,
1335 int Priority) {
1336 OrderGlobalInitsOrStermFinalizers Key(Priority,
1337 PrioritizedCXXStermFinalizers.size());
1338 PrioritizedCXXStermFinalizers.push_back(
1339 Elt: std::make_pair(x&: Key, y&: StermFinalizer));
1340 }
1341
1342 /// Create or return a runtime function declaration with the specified type
1343 /// and name. If \p AssumeConvergent is true, the call will have the
1344 /// convergent attribute added.
1345 ///
1346 /// For new code, please use the overload that takes a QualType; it sets
1347 /// function attributes more accurately.
1348 llvm::FunctionCallee
1349 CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name,
1350 llvm::AttributeList ExtraAttrs = llvm::AttributeList(),
1351 bool Local = false, bool AssumeConvergent = false);
1352
1353 /// Create or return a runtime function declaration with the specified type
1354 /// and name. If \p AssumeConvergent is true, the call will have the
1355 /// convergent attribute added.
1356 llvm::FunctionCallee
1357 CreateRuntimeFunction(QualType ReturnTy, ArrayRef<QualType> ArgTys,
1358 StringRef Name,
1359 llvm::AttributeList ExtraAttrs = llvm::AttributeList(),
1360 bool Local = false, bool AssumeConvergent = false);
1361
1362 /// Create a new runtime global variable with the specified type and name.
1363 llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty,
1364 StringRef Name);
1365
1366 ///@name Custom Blocks Runtime Interfaces
1367 ///@{
1368
1369 llvm::Constant *getNSConcreteGlobalBlock();
1370 llvm::Constant *getNSConcreteStackBlock();
1371 llvm::FunctionCallee getBlockObjectAssign();
1372 llvm::FunctionCallee getBlockObjectDispose();
1373
1374 ///@}
1375
1376 llvm::Function *getLLVMLifetimeStartFn();
1377 llvm::Function *getLLVMLifetimeEndFn();
1378 llvm::Function *getLLVMFakeUseFn();
1379
1380 // Make sure that this type is translated.
1381 void UpdateCompletedType(const TagDecl *TD);
1382
1383 llvm::Constant *getMemberPointerConstant(const UnaryOperator *e);
1384
1385 /// Emit type info if type of an expression is a variably modified
1386 /// type. Also emit proper debug info for cast types.
1387 void EmitExplicitCastExprType(const ExplicitCastExpr *E,
1388 CodeGenFunction *CGF = nullptr);
1389
1390 /// Return the result of value-initializing the given type, i.e. a null
1391 /// expression of the given type. This is usually, but not always, an LLVM
1392 /// null constant.
1393 llvm::Constant *EmitNullConstant(QualType T);
1394
1395 /// Return a null constant appropriate for zero-initializing a base class with
1396 /// the given type. This is usually, but not always, an LLVM null constant.
1397 llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record);
1398
1399 /// Emit a general error that something can't be done.
1400 void Error(SourceLocation loc, StringRef error);
1401
1402 /// Print out an error that codegen doesn't support the specified stmt yet.
1403 void ErrorUnsupported(const Stmt *S, const char *Type);
1404
1405 /// Print out an error that codegen doesn't support the specified stmt yet.
1406 void ErrorUnsupported(const Stmt *S, llvm::StringRef Type);
1407
1408 /// Print out an error that codegen doesn't support the specified decl yet.
1409 void ErrorUnsupported(const Decl *D, const char *Type);
1410
1411 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1412 /// guaranteed). Produces a warning if we're low on stack space and allocates
1413 /// more in that case. Use this in code that may recurse deeply to avoid stack
1414 /// overflow.
1415 void runWithSufficientStackSpace(SourceLocation Loc,
1416 llvm::function_ref<void()> Fn);
1417
1418 /// Set the attributes on the LLVM function for the given decl and function
1419 /// info. This applies attributes necessary for handling the ABI as well as
1420 /// user specified attributes like section.
1421 void SetInternalFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1422 const CGFunctionInfo &FI);
1423
1424 /// Set the LLVM function attributes (sext, zext, etc).
1425 void SetLLVMFunctionAttributes(GlobalDecl GD, const CGFunctionInfo &Info,
1426 llvm::Function *F, bool IsThunk);
1427
1428 /// Set the LLVM function attributes which only apply to a function
1429 /// definition.
1430 void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
1431
1432 /// Set the LLVM function attributes that represent floating point
1433 /// environment.
1434 void setLLVMFunctionFEnvAttributes(const FunctionDecl *D, llvm::Function *F);
1435
1436 /// Return true iff the given type uses 'sret' when used as a return type.
1437 bool ReturnTypeUsesSRet(const CGFunctionInfo &FI);
1438
1439 /// Return true iff the given type has `inreg` set.
1440 bool ReturnTypeHasInReg(const CGFunctionInfo &FI);
1441
1442 /// Return true iff the given type uses an argument slot when 'sret' is used
1443 /// as a return type.
1444 bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI);
1445
1446 /// Return true iff the given type uses 'fpret' when used as a return type.
1447 bool ReturnTypeUsesFPRet(QualType ResultType);
1448
1449 /// Return true iff the given type uses 'fp2ret' when used as a return type.
1450 bool ReturnTypeUsesFP2Ret(QualType ResultType);
1451
1452 /// Get the LLVM attributes and calling convention to use for a particular
1453 /// function type.
1454 ///
1455 /// \param Name - The function name.
1456 /// \param Info - The function type information.
1457 /// \param CalleeInfo - The callee information these attributes are being
1458 /// constructed for. If valid, the attributes applied to this decl may
1459 /// contribute to the function attributes and calling convention.
1460 /// \param Attrs [out] - On return, the attribute list to use.
1461 /// \param CallingConv [out] - On return, the LLVM calling convention to use.
1462 void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info,
1463 CGCalleeInfo CalleeInfo,
1464 llvm::AttributeList &Attrs, unsigned &CallingConv,
1465 bool AttrOnCallSite, bool IsThunk);
1466
1467 /// Adjust Memory attribute to ensure that the BE gets the right attribute
1468 // in order to generate the library call or the intrinsic for the function
1469 // name 'Name'.
1470 void AdjustMemoryAttribute(StringRef Name, CGCalleeInfo CalleeInfo,
1471 llvm::AttributeList &Attrs);
1472
1473 /// Like the overload taking a `Function &`, but intended specifically
1474 /// for frontends that want to build on Clang's target-configuration logic.
1475 void addDefaultFunctionDefinitionAttributes(llvm::AttrBuilder &attrs);
1476
1477 StringRef getMangledName(GlobalDecl GD);
1478 StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD);
1479 const GlobalDecl getMangledNameDecl(StringRef);
1480
1481 void EmitTentativeDefinition(const VarDecl *D);
1482
1483 void EmitExternalDeclaration(const DeclaratorDecl *D);
1484
1485 void EmitVTable(CXXRecordDecl *Class);
1486
1487 void RefreshTypeCacheForClass(const CXXRecordDecl *Class);
1488
1489 /// Appends Opts to the "llvm.linker.options" metadata value.
1490 void AppendLinkerOptions(StringRef Opts);
1491
1492 /// Appends a detect mismatch command to the linker options.
1493 void AddDetectMismatch(StringRef Name, StringRef Value);
1494
1495 /// Appends a dependent lib to the appropriate metadata value.
1496 void AddDependentLib(StringRef Lib);
1497
1498
1499 llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD);
1500
1501 void setFunctionLinkage(GlobalDecl GD, llvm::Function *F) {
1502 F->setLinkage(getFunctionLinkage(GD));
1503 }
1504
1505 /// Return the appropriate linkage for the vtable, VTT, and type information
1506 /// of the given class.
1507 llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD);
1508
1509 /// Return the store size, in character units, of the given LLVM type.
1510 CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const;
1511
1512 /// Returns LLVM linkage for a declarator.
1513 llvm::GlobalValue::LinkageTypes
1514 getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage);
1515
1516 /// Returns LLVM linkage for a declarator.
1517 llvm::GlobalValue::LinkageTypes
1518 getLLVMLinkageVarDefinition(const VarDecl *VD);
1519
1520 /// Emit all the global annotations.
1521 void EmitGlobalAnnotations();
1522
1523 /// Emit an annotation string.
1524 llvm::Constant *EmitAnnotationString(StringRef Str);
1525
1526 /// Emit the annotation's translation unit.
1527 llvm::Constant *EmitAnnotationUnit(SourceLocation Loc);
1528
1529 /// Emit the annotation line number.
1530 llvm::Constant *EmitAnnotationLineNo(SourceLocation L);
1531
1532 /// Emit additional args of the annotation.
1533 llvm::Constant *EmitAnnotationArgs(const AnnotateAttr *Attr);
1534
1535 /// Generate the llvm::ConstantStruct which contains the annotation
1536 /// information for a given GlobalValue. The annotation struct is
1537 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
1538 /// GlobalValue being annotated. The second field is the constant string
1539 /// created from the AnnotateAttr's annotation. The third field is a constant
1540 /// string containing the name of the translation unit. The fourth field is
1541 /// the line number in the file of the annotated value declaration.
1542 llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
1543 const AnnotateAttr *AA,
1544 SourceLocation L);
1545
1546 /// Add global annotations that are set on D, for the global GV. Those
1547 /// annotations are emitted during finalization of the LLVM code.
1548 void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV);
1549
1550 bool isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn,
1551 SourceLocation Loc) const;
1552
1553 bool isInNoSanitizeList(SanitizerMask Kind, llvm::GlobalVariable *GV,
1554 SourceLocation Loc, QualType Ty,
1555 StringRef Category = StringRef()) const;
1556
1557 /// Imbue XRay attributes to a function, applying the always/never attribute
1558 /// lists in the process. Returns true if we did imbue attributes this way,
1559 /// false otherwise.
1560 bool imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
1561 StringRef Category = StringRef()) const;
1562
1563 /// \returns true if \p Fn at \p Loc should be excluded from profile
1564 /// instrumentation by the SCL passed by \p -fprofile-list.
1565 ProfileList::ExclusionType
1566 isFunctionBlockedByProfileList(llvm::Function *Fn, SourceLocation Loc) const;
1567
1568 /// \returns true if \p Fn at \p Loc should be excluded from profile
1569 /// instrumentation.
1570 ProfileList::ExclusionType
1571 isFunctionBlockedFromProfileInstr(llvm::Function *Fn,
1572 SourceLocation Loc) const;
1573
1574 SanitizerMetadata *getSanitizerMetadata() {
1575 return SanitizerMD.get();
1576 }
1577
1578 void addDeferredVTable(const CXXRecordDecl *RD) {
1579 DeferredVTables.push_back(x: RD);
1580 }
1581
1582 /// Emit code for a single global function or var decl. Forward declarations
1583 /// are emitted lazily.
1584 void EmitGlobal(GlobalDecl D);
1585
1586 /// Record that new[] was called for the class, transform vector deleting
1587 /// destructor definition in a form of alias to the actual definition.
1588 void requireVectorDestructorDefinition(const CXXRecordDecl *RD);
1589
1590 /// Check that class need vector deleting destructor body.
1591 bool classNeedsVectorDestructor(const CXXRecordDecl *RD);
1592
1593 bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D);
1594 void EmitDefinitionAsAlias(GlobalDecl Alias, GlobalDecl Target);
1595
1596 llvm::GlobalValue *GetGlobalValue(StringRef Ref);
1597
1598 /// Set attributes which are common to any form of a global definition (alias,
1599 /// Objective-C method, function, global variable).
1600 ///
1601 /// NOTE: This should only be called for definitions.
1602 void SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV);
1603
1604 void addReplacement(StringRef Name, llvm::Constant *C);
1605
1606 void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C);
1607
1608 /// Emit a code for threadprivate directive.
1609 /// \param D Threadprivate declaration.
1610 void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D);
1611
1612 /// Emit a code for declare reduction construct.
1613 void EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
1614 CodeGenFunction *CGF = nullptr);
1615
1616 /// Emit a code for declare mapper construct.
1617 void EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D,
1618 CodeGenFunction *CGF = nullptr);
1619
1620 // Emit code for the OpenACC Declare declaration.
1621 void EmitOpenACCDeclare(const OpenACCDeclareDecl *D,
1622 CodeGenFunction *CGF = nullptr);
1623 // Emit code for the OpenACC Routine declaration.
1624 void EmitOpenACCRoutine(const OpenACCRoutineDecl *D,
1625 CodeGenFunction *CGF = nullptr);
1626
1627 /// Emit a code for requires directive.
1628 /// \param D Requires declaration
1629 void EmitOMPRequiresDecl(const OMPRequiresDecl *D);
1630
1631 /// Emit a code for the allocate directive.
1632 /// \param D The allocate declaration
1633 void EmitOMPAllocateDecl(const OMPAllocateDecl *D);
1634
1635 /// Return the alignment specified in an allocate directive, if present.
1636 std::optional<CharUnits> getOMPAllocateAlignment(const VarDecl *VD);
1637
1638 /// Returns whether the given record has hidden LTO visibility and therefore
1639 /// may participate in (single-module) CFI and whole-program vtable
1640 /// optimization.
1641 bool HasHiddenLTOVisibility(const CXXRecordDecl *RD);
1642
1643 /// Returns whether the given record has public LTO visibility (regardless of
1644 /// -lto-whole-program-visibility) and therefore may not participate in
1645 /// (single-module) CFI and whole-program vtable optimization.
1646 bool AlwaysHasLTOVisibilityPublic(const CXXRecordDecl *RD);
1647
1648 /// Returns the vcall visibility of the given type. This is the scope in which
1649 /// a virtual function call could be made which ends up being dispatched to a
1650 /// member function of this class. This scope can be wider than the visibility
1651 /// of the class itself when the class has a more-visible dynamic base class.
1652 /// The client should pass in an empty Visited set, which is used to prevent
1653 /// redundant recursive processing.
1654 llvm::GlobalObject::VCallVisibility
1655 GetVCallVisibilityLevel(const CXXRecordDecl *RD,
1656 llvm::DenseSet<const CXXRecordDecl *> &Visited);
1657
1658 /// Emit type metadata for the given vtable using the given layout.
1659 void EmitVTableTypeMetadata(const CXXRecordDecl *RD,
1660 llvm::GlobalVariable *VTable,
1661 const VTableLayout &VTLayout);
1662
1663 llvm::Type *getVTableComponentType() const;
1664
1665 /// Generate a cross-DSO type identifier for MD.
1666 llvm::ConstantInt *CreateCrossDsoCfiTypeId(llvm::Metadata *MD);
1667
1668 /// Generate a KCFI type identifier for T.
1669 llvm::ConstantInt *CreateKCFITypeId(QualType T, StringRef Salt);
1670
1671 /// Create a metadata identifier for the given function type.
1672 llvm::Metadata *CreateMetadataIdentifierForFnType(QualType T);
1673
1674 /// Create a metadata identifier for the given type. This may either be an
1675 /// MDString (for external identifiers) or a distinct unnamed MDNode (for
1676 /// internal identifiers).
1677 llvm::Metadata *CreateMetadataIdentifierForType(QualType T);
1678
1679 /// Create a metadata identifier that is intended to be used to check virtual
1680 /// calls via a member function pointer.
1681 llvm::Metadata *CreateMetadataIdentifierForVirtualMemPtrType(QualType T);
1682
1683 /// Create a metadata identifier for the generalization of the given type.
1684 /// This may either be an MDString (for external identifiers) or a distinct
1685 /// unnamed MDNode (for internal identifiers).
1686 llvm::Metadata *CreateMetadataIdentifierGeneralized(QualType T);
1687
1688 /// Create and attach type metadata to the given function.
1689 void createFunctionTypeMetadataForIcall(const FunctionDecl *FD,
1690 llvm::Function *F);
1691
1692 /// Create and attach type metadata if the function is a potential indirect
1693 /// call target to support call graph section.
1694 void createIndirectFunctionTypeMD(const FunctionDecl *FD, llvm::Function *F);
1695
1696 /// Create and attach type metadata to the given call.
1697 void createCalleeTypeMetadataForIcall(const QualType &QT, llvm::CallBase *CB);
1698
1699 /// Set type metadata to the given function.
1700 void setKCFIType(const FunctionDecl *FD, llvm::Function *F);
1701
1702 /// Emit KCFI type identifier constants and remove unused identifiers.
1703 void finalizeKCFITypes();
1704
1705 /// Whether this function's return type has no side effects, and thus may
1706 /// be trivially discarded if it is unused.
1707 bool MayDropFunctionReturn(const ASTContext &Context,
1708 QualType ReturnType) const;
1709
1710 /// Returns whether this module needs the "all-vtables" type identifier.
1711 bool NeedAllVtablesTypeId() const;
1712
1713 /// Create and attach type metadata for the given vtable.
1714 void AddVTableTypeMetadata(llvm::GlobalVariable *VTable, CharUnits Offset,
1715 const CXXRecordDecl *RD);
1716
1717 /// Return a vector of most-base classes for RD. This is used to implement
1718 /// control flow integrity checks for member function pointers.
1719 ///
1720 /// A most-base class of a class C is defined as a recursive base class of C,
1721 /// including C itself, that does not have any bases.
1722 SmallVector<const CXXRecordDecl *, 0>
1723 getMostBaseClasses(const CXXRecordDecl *RD);
1724
1725 /// Get the declaration of std::terminate for the platform.
1726 llvm::FunctionCallee getTerminateFn();
1727
1728 llvm::SanitizerStatReport &getSanStats();
1729
1730 llvm::Value *
1731 createOpenCLIntToSamplerConversion(const Expr *E, CodeGenFunction &CGF);
1732
1733 /// OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
1734 /// information in the program executable. The argument information stored
1735 /// includes the argument name, its type, the address and access qualifiers
1736 /// used. This helper can be used to generate metadata for source code kernel
1737 /// function as well as generated implicitly kernels. If a kernel is generated
1738 /// implicitly null value has to be passed to the last two parameters,
1739 /// otherwise all parameters must have valid non-null values.
1740 /// \param FN is a pointer to IR function being generated.
1741 /// \param FD is a pointer to function declaration if any.
1742 /// \param CGF is a pointer to CodeGenFunction that generates this function.
1743 void GenKernelArgMetadata(llvm::Function *FN,
1744 const FunctionDecl *FD = nullptr,
1745 CodeGenFunction *CGF = nullptr);
1746
1747 /// Get target specific null pointer.
1748 /// \param T is the LLVM type of the null pointer.
1749 /// \param QT is the clang QualType of the null pointer.
1750 llvm::Constant *getNullPointer(llvm::PointerType *T, QualType QT);
1751
1752 CharUnits getNaturalTypeAlignment(QualType T,
1753 LValueBaseInfo *BaseInfo = nullptr,
1754 TBAAAccessInfo *TBAAInfo = nullptr,
1755 bool forPointeeType = false);
1756 CharUnits getNaturalPointeeTypeAlignment(QualType T,
1757 LValueBaseInfo *BaseInfo = nullptr,
1758 TBAAAccessInfo *TBAAInfo = nullptr);
1759 bool stopAutoInit();
1760
1761 /// Print the postfix for externalized static variable or kernels for single
1762 /// source offloading languages CUDA and HIP. The unique postfix is created
1763 /// using either the CUID argument, or the file's UniqueID and active macros.
1764 /// The fallback method without a CUID requires that the offloading toolchain
1765 /// does not define separate macros via the -cc1 options.
1766 void printPostfixForExternalizedDecl(llvm::raw_ostream &OS,
1767 const Decl *D) const;
1768
1769 /// Move some lazily-emitted states to the NewBuilder. This is especially
1770 /// essential for the incremental parsing environment like Clang Interpreter,
1771 /// because we'll lose all important information after each repl.
1772 void moveLazyEmissionStates(CodeGenModule *NewBuilder);
1773
1774 /// Emit the IR encoding to attach the CUDA launch bounds attribute to \p F.
1775 /// If \p MaxThreadsVal is not nullptr, the max threads value is stored in it,
1776 /// if a valid one was found.
1777 void handleCUDALaunchBoundsAttr(llvm::Function *F,
1778 const CUDALaunchBoundsAttr *A,
1779 int32_t *MaxThreadsVal = nullptr,
1780 int32_t *MinBlocksVal = nullptr,
1781 int32_t *MaxClusterRankVal = nullptr);
1782
1783 /// Emit the IR encoding to attach the AMD GPU flat-work-group-size attribute
1784 /// to \p F. Alternatively, the work group size can be taken from a \p
1785 /// ReqdWGS. If \p MinThreadsVal is not nullptr, the min threads value is
1786 /// stored in it, if a valid one was found. If \p MaxThreadsVal is not
1787 /// nullptr, the max threads value is stored in it, if a valid one was found.
1788 void handleAMDGPUFlatWorkGroupSizeAttr(
1789 llvm::Function *F, const AMDGPUFlatWorkGroupSizeAttr *A,
1790 const ReqdWorkGroupSizeAttr *ReqdWGS = nullptr,
1791 int32_t *MinThreadsVal = nullptr, int32_t *MaxThreadsVal = nullptr);
1792
1793 /// Emit the IR encoding to attach the AMD GPU waves-per-eu attribute to \p F.
1794 void handleAMDGPUWavesPerEUAttr(llvm::Function *F,
1795 const AMDGPUWavesPerEUAttr *A);
1796
1797 llvm::Constant *
1798 GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty, LangAS AddrSpace,
1799 const VarDecl *D,
1800 ForDefinition_t IsForDefinition = NotForDefinition);
1801
1802 // FIXME: Hardcoding priority here is gross.
1803 void AddGlobalCtor(llvm::Function *Ctor, int Priority = 65535,
1804 unsigned LexOrder = ~0U,
1805 llvm::Constant *AssociatedData = nullptr);
1806 void AddGlobalDtor(llvm::Function *Dtor, int Priority = 65535,
1807 bool IsDtorAttrFunc = false);
1808
1809 // Return whether structured convergence intrinsics should be generated for
1810 // this target.
1811 bool shouldEmitConvergenceTokens() const {
1812 // TODO: this should probably become unconditional once the controlled
1813 // convergence becomes the norm.
1814 return getTriple().isSPIRVLogical();
1815 }
1816
1817 void addUndefinedGlobalForTailCall(
1818 std::pair<const FunctionDecl *, SourceLocation> Global) {
1819 MustTailCallUndefinedGlobals.insert(X: Global);
1820 }
1821
1822 bool shouldZeroInitPadding() const {
1823 // In C23 (N3096) $6.7.10:
1824 // """
1825 // If any object is initialized with an empty iniitializer, then it is
1826 // subject to default initialization:
1827 // - if it is an aggregate, every member is initialized (recursively)
1828 // according to these rules, and any padding is initialized to zero bits;
1829 // - if it is a union, the first named member is initialized (recursively)
1830 // according to these rules, and any padding is initialized to zero bits.
1831 //
1832 // If the aggregate or union contains elements or members that are
1833 // aggregates or unions, these rules apply recursively to the subaggregates
1834 // or contained unions.
1835 //
1836 // If there are fewer initializers in a brace-enclosed list than there are
1837 // elements or members of an aggregate, or fewer characters in a string
1838 // literal used to initialize an array of known size than there are elements
1839 // in the array, the remainder of the aggregate is subject to default
1840 // initialization.
1841 // """
1842 //
1843 // From my understanding, the standard is ambiguous in the following two
1844 // areas:
1845 // 1. For a union type with empty initializer, if the first named member is
1846 // not the largest member, then the bytes comes after the first named member
1847 // but before padding are left unspecified. An example is:
1848 // union U { int a; long long b;};
1849 // union U u = {}; // The first 4 bytes are 0, but 4-8 bytes are left
1850 // unspecified.
1851 //
1852 // 2. It only mentions padding for empty initializer, but doesn't mention
1853 // padding for a non empty initialization list. And if the aggregation or
1854 // union contains elements or members that are aggregates or unions, and
1855 // some are non empty initializers, while others are empty initiailizers,
1856 // the padding initialization is unclear. An example is:
1857 // struct S1 { int a; long long b; };
1858 // struct S2 { char c; struct S1 s1; };
1859 // // The values for paddings between s2.c and s2.s1.a, between s2.s1.a
1860 // and s2.s1.b are unclear.
1861 // struct S2 s2 = { 'c' };
1862 //
1863 // Here we choose to zero initiailize left bytes of a union type. Because
1864 // projects like the Linux kernel are relying on this behavior. If we don't
1865 // explicitly zero initialize them, the undef values can be optimized to
1866 // return gabage data. We also choose to zero initialize paddings for
1867 // aggregates and unions, no matter they are initialized by empty
1868 // initializers or non empty initializers. This can provide a consistent
1869 // behavior. So projects like the Linux kernel can rely on it.
1870 return !getLangOpts().CPlusPlus;
1871 }
1872
1873 // Helper to get the alignment for a variable.
1874 unsigned getVtableGlobalVarAlignment(const VarDecl *D = nullptr) {
1875 LangAS AS = GetGlobalVarAddressSpace(D);
1876 unsigned PAlign = getItaniumVTableContext().isRelativeLayout()
1877 ? 32
1878 : getTarget().getPointerAlign(AddrSpace: AS);
1879 return PAlign;
1880 }
1881
1882 /// Helper function to construct a TrapReasonBuilder
1883 TrapReasonBuilder BuildTrapReason(unsigned DiagID, TrapReason &TR) {
1884 return TrapReasonBuilder(&getDiags(), DiagID, TR);
1885 }
1886
1887 llvm::Constant *performAddrSpaceCast(llvm::Constant *Src,
1888 llvm::Type *DestTy) {
1889 // Since target may map different address spaces in AST to the same address
1890 // space, an address space conversion may end up as a bitcast.
1891 return llvm::ConstantExpr::getPointerCast(C: Src, Ty: DestTy);
1892 }
1893
1894 std::optional<llvm::Attribute::AttrKind>
1895 StackProtectorAttribute(const Decl *D) const;
1896
1897 std::string getPFPFieldName(const FieldDecl *FD);
1898 llvm::GlobalValue *getPFPDeactivationSymbol(const FieldDecl *FD);
1899
1900private:
1901 bool shouldDropDLLAttribute(const Decl *D, const llvm::GlobalValue *GV) const;
1902
1903 llvm::Constant *GetOrCreateLLVMFunction(
1904 StringRef MangledName, llvm::Type *Ty, GlobalDecl D, bool ForVTable,
1905 bool DontDefer = false, bool IsThunk = false,
1906 llvm::AttributeList ExtraAttrs = llvm::AttributeList(),
1907 ForDefinition_t IsForDefinition = NotForDefinition);
1908
1909 // Adds a declaration to the list of multi version functions if not present.
1910 void AddDeferredMultiVersionResolverToEmit(GlobalDecl GD);
1911
1912 // References to multiversion functions are resolved through an implicitly
1913 // defined resolver function. This function is responsible for creating
1914 // the resolver symbol for the provided declaration. The value returned
1915 // will be for an ifunc (llvm::GlobalIFunc) if the current target supports
1916 // that feature and for a regular function (llvm::GlobalValue) otherwise.
1917 llvm::Constant *GetOrCreateMultiVersionResolver(GlobalDecl GD);
1918
1919 // Set attributes to a resolver function generated by Clang.
1920 // GD is either the cpu_dispatch declaration or an arbitrarily chosen
1921 // function declaration that triggered the implicit generation of this
1922 // resolver function.
1923 //
1924 /// NOTE: This should only be called for definitions.
1925 void setMultiVersionResolverAttributes(llvm::Function *Resolver,
1926 GlobalDecl GD);
1927
1928 // In scenarios where a function is not known to be a multiversion function
1929 // until a later declaration, it is sometimes necessary to change the
1930 // previously created mangled name to align with requirements of whatever
1931 // multiversion function kind the function is now known to be. This function
1932 // is responsible for performing such mangled name updates.
1933 void UpdateMultiVersionNames(GlobalDecl GD, const FunctionDecl *FD,
1934 StringRef &CurName);
1935
1936 bool GetCPUAndFeaturesAttributes(GlobalDecl GD,
1937 llvm::AttrBuilder &AttrBuilder,
1938 bool SetTargetFeatures = true);
1939 void setNonAliasAttributes(GlobalDecl GD, llvm::GlobalObject *GO);
1940
1941 /// Set function attributes for a function declaration.
1942 void SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1943 bool IsIncompleteFunction, bool IsThunk);
1944
1945 void EmitGlobalDefinition(GlobalDecl D, llvm::GlobalValue *GV = nullptr);
1946
1947 void EmitGlobalFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
1948 void EmitMultiVersionFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
1949
1950 void EmitGlobalVarDefinition(const VarDecl *D, bool IsTentative = false);
1951 void EmitAliasDefinition(GlobalDecl GD);
1952 void emitIFuncDefinition(GlobalDecl GD);
1953 void emitCPUDispatchDefinition(GlobalDecl GD);
1954 void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
1955 void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
1956
1957 // C++ related functions.
1958
1959 void EmitDeclContext(const DeclContext *DC);
1960 void EmitLinkageSpec(const LinkageSpecDecl *D);
1961 void EmitTopLevelStmt(const TopLevelStmtDecl *D);
1962
1963 /// Emit the function that initializes C++ thread_local variables.
1964 void EmitCXXThreadLocalInitFunc();
1965
1966 /// Emit the function that initializes global variables for a C++ Module.
1967 void EmitCXXModuleInitFunc(clang::Module *Primary);
1968
1969 /// Emit the function that initializes C++ globals.
1970 void EmitCXXGlobalInitFunc();
1971
1972 /// Emit the function that performs cleanup associated with C++ globals.
1973 void EmitCXXGlobalCleanUpFunc();
1974
1975 /// Emit the function that initializes the specified global (if PerformInit is
1976 /// true) and registers its destructor.
1977 void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
1978 llvm::GlobalVariable *Addr,
1979 bool PerformInit);
1980
1981 void EmitPointerToInitFunc(const VarDecl *VD, llvm::GlobalVariable *Addr,
1982 llvm::Function *InitFunc, InitSegAttr *ISA);
1983
1984 /// EmitCtorList - Generates a global array of functions and priorities using
1985 /// the given list and name. This array will have appending linkage and is
1986 /// suitable for use as a LLVM constructor or destructor array. Clears Fns.
1987 void EmitCtorList(CtorList &Fns, const char *GlobalName);
1988
1989 /// Emit any needed decls for which code generation was deferred.
1990 void EmitDeferred();
1991
1992 /// Try to emit external vtables as available_externally if they have emitted
1993 /// all inlined virtual functions. It runs after EmitDeferred() and therefore
1994 /// is not allowed to create new references to things that need to be emitted
1995 /// lazily.
1996 void EmitVTablesOpportunistically();
1997
1998 /// Call replaceAllUsesWith on all pairs in Replacements.
1999 void applyReplacements();
2000
2001 /// Call replaceAllUsesWith on all pairs in GlobalValReplacements.
2002 void applyGlobalValReplacements();
2003
2004 void checkAliases();
2005
2006 std::map<int, llvm::TinyPtrVector<llvm::Function *>> DtorsUsingAtExit;
2007
2008 /// Register functions annotated with __attribute__((destructor)) using
2009 /// __cxa_atexit, if it is available, or atexit otherwise.
2010 void registerGlobalDtorsWithAtExit();
2011
2012 // When using sinit and sterm functions, unregister
2013 // __attribute__((destructor)) annotated functions which were previously
2014 // registered by the atexit subroutine using unatexit.
2015 void unregisterGlobalDtorsWithUnAtExit();
2016
2017 /// Emit deferred multiversion function resolvers and associated variants.
2018 void emitMultiVersionFunctions();
2019
2020 /// Emit any vtables which we deferred and still have a use for.
2021 void EmitDeferredVTables();
2022
2023 /// Emit a dummy function that reference a CoreFoundation symbol when
2024 /// @available is used on Darwin.
2025 void emitAtAvailableLinkGuard();
2026
2027 /// Emit the llvm.used and llvm.compiler.used metadata.
2028 void emitLLVMUsed();
2029
2030 /// For C++20 Itanium ABI, emit the initializers for the module.
2031 void EmitModuleInitializers(clang::Module *Primary);
2032
2033 /// Emit the link options introduced by imported modules.
2034 void EmitModuleLinkOptions();
2035
2036 /// Helper function for EmitStaticExternCAliases() to redirect ifuncs that
2037 /// have a resolver name that matches 'Elem' to instead resolve to the name of
2038 /// 'CppFunc'. This redirection is necessary in cases where 'Elem' has a name
2039 /// that will be emitted as an alias of the name bound to 'CppFunc'; ifuncs
2040 /// may not reference aliases. Redirection is only performed if 'Elem' is only
2041 /// used by ifuncs in which case, 'Elem' is destroyed. 'true' is returned if
2042 /// redirection is successful, and 'false' is returned otherwise.
2043 bool CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem,
2044 llvm::GlobalValue *CppFunc);
2045
2046 /// Emit aliases for internal-linkage declarations inside "C" language
2047 /// linkage specifications, giving them the "expected" name where possible.
2048 void EmitStaticExternCAliases();
2049
2050 void EmitDeclMetadata();
2051
2052 /// Emit the Clang version as llvm.ident metadata.
2053 void EmitVersionIdentMetadata();
2054
2055 /// Emit the Clang commandline as llvm.commandline metadata.
2056 void EmitCommandLineMetadata();
2057
2058 /// Emit the module flag metadata used to pass options controlling the
2059 /// the backend to LLVM.
2060 void EmitBackendOptionsMetadata(const CodeGenOptions &CodeGenOpts);
2061
2062 /// Emits OpenCL specific Metadata e.g. OpenCL version.
2063 void EmitOpenCLMetadata();
2064
2065 /// Emit the llvm.gcov metadata used to tell LLVM where to emit the .gcno and
2066 /// .gcda files in a way that persists in .bc files.
2067 void EmitCoverageFile();
2068
2069 /// Given a sycl_kernel_entry_point attributed function, emit the
2070 /// corresponding SYCL kernel caller offload entry point function.
2071 void EmitSYCLKernelCaller(const FunctionDecl *KernelEntryPointFn,
2072 ASTContext &Ctx);
2073
2074 /// Determine whether the definition must be emitted; if this returns \c
2075 /// false, the definition can be emitted lazily if it's used.
2076 bool MustBeEmitted(const ValueDecl *D);
2077
2078 /// Determine whether the definition can be emitted eagerly, or should be
2079 /// delayed until the end of the translation unit. This is relevant for
2080 /// definitions whose linkage can change, e.g. implicit function instantions
2081 /// which may later be explicitly instantiated.
2082 bool MayBeEmittedEagerly(const ValueDecl *D);
2083
2084 /// Check whether we can use a "simpler", more core exceptions personality
2085 /// function.
2086 void SimplifyPersonality();
2087
2088 /// Helper function for getDefaultFunctionAttributes. Builds a set of function
2089 /// attributes which can be simply added to a function.
2090 void getTrivialDefaultFunctionAttributes(StringRef Name, bool HasOptnone,
2091 bool AttrOnCallSite,
2092 llvm::AttrBuilder &FuncAttrs);
2093
2094 /// Helper function for ConstructAttributeList and
2095 /// addDefaultFunctionDefinitionAttributes. Builds a set of function
2096 /// attributes to add to a function with the given properties.
2097 void getDefaultFunctionAttributes(StringRef Name, bool HasOptnone,
2098 bool AttrOnCallSite,
2099 llvm::AttrBuilder &FuncAttrs);
2100
2101 llvm::Metadata *CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
2102 StringRef Suffix);
2103
2104 /// Emit deactivation symbols for any PFP fields whose offset is taken with
2105 /// offsetof.
2106 void emitPFPFieldsWithEvaluatedOffset();
2107};
2108
2109} // end namespace CodeGen
2110} // end namespace clang
2111
2112#endif // LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H
2113