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