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