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