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