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