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