]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/CodeGen/CodeGenModule.h
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r304149, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / CodeGen / CodeGenModule.h
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   typedef llvm::StringMap<llvm::TrackingVH<llvm::Constant> > ReplacementsTy;
328   ReplacementsTy Replacements;
329
330   /// List of global values to be replaced with something else. Used when we
331   /// want to replace a GlobalValue but can't identify it by its mangled name
332   /// anymore (because the name is already taken).
333   llvm::SmallVector<std::pair<llvm::GlobalValue *, llvm::Constant *>, 8>
334     GlobalValReplacements;
335
336   /// Set of global decls for which we already diagnosed mangled name conflict.
337   /// Required to not issue a warning (on a mangling conflict) multiple times
338   /// for the same decl.
339   llvm::DenseSet<GlobalDecl> DiagnosedConflictingDefinitions;
340
341   /// A queue of (optional) vtables to consider emitting.
342   std::vector<const CXXRecordDecl*> DeferredVTables;
343
344   /// List of global values which are required to be present in the object file;
345   /// bitcast to i8*. This is used for forcing visibility of symbols which may
346   /// otherwise be optimized out.
347   std::vector<llvm::WeakTrackingVH> LLVMUsed;
348   std::vector<llvm::WeakTrackingVH> LLVMCompilerUsed;
349
350   /// Store the list of global constructors and their respective priorities to
351   /// be emitted when the translation unit is complete.
352   CtorList GlobalCtors;
353
354   /// Store the list of global destructors and their respective priorities to be
355   /// emitted when the translation unit is complete.
356   CtorList GlobalDtors;
357
358   /// An ordered map of canonical GlobalDecls to their mangled names.
359   llvm::MapVector<GlobalDecl, StringRef> MangledDeclNames;
360   llvm::StringMap<GlobalDecl, llvm::BumpPtrAllocator> Manglings;
361
362   /// Global annotations.
363   std::vector<llvm::Constant*> Annotations;
364
365   /// Map used to get unique annotation strings.
366   llvm::StringMap<llvm::Constant*> AnnotationStrings;
367
368   llvm::StringMap<llvm::GlobalVariable *> CFConstantStringMap;
369
370   llvm::DenseMap<llvm::Constant *, llvm::GlobalVariable *> ConstantStringMap;
371   llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap;
372   llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardMap;
373   llvm::DenseMap<const Expr*, llvm::Constant *> MaterializedGlobalTemporaryMap;
374
375   llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap;
376   llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap;
377
378   /// Map used to get unique type descriptor constants for sanitizers.
379   llvm::DenseMap<QualType, llvm::Constant *> TypeDescriptorMap;
380
381   /// Map used to track internal linkage functions declared within
382   /// extern "C" regions.
383   typedef llvm::MapVector<IdentifierInfo *,
384                           llvm::GlobalValue *> StaticExternCMap;
385   StaticExternCMap StaticExternCValues;
386
387   /// \brief thread_local variables defined or used in this TU.
388   std::vector<const VarDecl *> CXXThreadLocals;
389
390   /// \brief thread_local variables with initializers that need to run
391   /// before any thread_local variable in this TU is odr-used.
392   std::vector<llvm::Function *> CXXThreadLocalInits;
393   std::vector<const VarDecl *> CXXThreadLocalInitVars;
394
395   /// Global variables with initializers that need to run before main.
396   std::vector<llvm::Function *> CXXGlobalInits;
397
398   /// When a C++ decl with an initializer is deferred, null is
399   /// appended to CXXGlobalInits, and the index of that null is placed
400   /// here so that the initializer will be performed in the correct
401   /// order. Once the decl is emitted, the index is replaced with ~0U to ensure
402   /// that we don't re-emit the initializer.
403   llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition;
404   
405   typedef std::pair<OrderGlobalInits, llvm::Function*> GlobalInitData;
406
407   struct GlobalInitPriorityCmp {
408     bool operator()(const GlobalInitData &LHS,
409                     const GlobalInitData &RHS) const {
410       return LHS.first.priority < RHS.first.priority;
411     }
412   };
413
414   /// Global variables with initializers whose order of initialization is set by
415   /// init_priority attribute.
416   SmallVector<GlobalInitData, 8> PrioritizedCXXGlobalInits;
417
418   /// Global destructor functions and arguments that need to run on termination.
419   std::vector<std::pair<llvm::WeakTrackingVH, llvm::Constant *>> CXXGlobalDtors;
420
421   /// \brief The complete set of modules that has been imported.
422   llvm::SetVector<clang::Module *> ImportedModules;
423
424   /// \brief The set of modules for which the module initializers
425   /// have been emitted.
426   llvm::SmallPtrSet<clang::Module *, 16> EmittedModuleInitializers;
427
428   /// \brief A vector of metadata strings.
429   SmallVector<llvm::Metadata *, 16> LinkerOptionsMetadata;
430
431   /// @name Cache for Objective-C runtime types
432   /// @{
433
434   /// Cached reference to the class for constant strings. This value has type
435   /// int * but is actually an Obj-C class pointer.
436   llvm::WeakTrackingVH CFConstantStringClassRef;
437
438   /// \brief The type used to describe the state of a fast enumeration in
439   /// Objective-C's for..in loop.
440   QualType ObjCFastEnumerationStateType;
441   
442   /// @}
443
444   /// Lazily create the Objective-C runtime
445   void createObjCRuntime();
446
447   void createOpenCLRuntime();
448   void createOpenMPRuntime();
449   void createCUDARuntime();
450
451   bool isTriviallyRecursive(const FunctionDecl *F);
452   bool shouldEmitFunction(GlobalDecl GD);
453
454   /// Map used to be sure we don't emit the same CompoundLiteral twice.
455   llvm::DenseMap<const CompoundLiteralExpr *, llvm::GlobalVariable *>
456       EmittedCompoundLiterals;
457
458   /// Map of the global blocks we've emitted, so that we don't have to re-emit
459   /// them if the constexpr evaluator gets aggressive.
460   llvm::DenseMap<const BlockExpr *, llvm::Constant *> EmittedGlobalBlocks;
461
462   /// @name Cache for Blocks Runtime Globals
463   /// @{
464
465   llvm::Constant *NSConcreteGlobalBlock = nullptr;
466   llvm::Constant *NSConcreteStackBlock = nullptr;
467
468   llvm::Constant *BlockObjectAssign = nullptr;
469   llvm::Constant *BlockObjectDispose = nullptr;
470
471   llvm::Type *BlockDescriptorType = nullptr;
472   llvm::Type *GenericBlockLiteralType = nullptr;
473
474   struct {
475     int GlobalUniqueCount;
476   } Block;
477
478   /// void @llvm.lifetime.start(i64 %size, i8* nocapture <ptr>)
479   llvm::Constant *LifetimeStartFn = nullptr;
480
481   /// void @llvm.lifetime.end(i64 %size, i8* nocapture <ptr>)
482   llvm::Constant *LifetimeEndFn = nullptr;
483
484   GlobalDecl initializedGlobalDecl;
485
486   std::unique_ptr<SanitizerMetadata> SanitizerMD;
487
488   /// @}
489
490   llvm::DenseMap<const Decl *, bool> DeferredEmptyCoverageMappingDecls;
491
492   std::unique_ptr<CoverageMappingModuleGen> CoverageMapping;
493
494   /// Mapping from canonical types to their metadata identifiers. We need to
495   /// maintain this mapping because identifiers may be formed from distinct
496   /// MDNodes.
497   llvm::DenseMap<QualType, llvm::Metadata *> MetadataIdMap;
498
499 public:
500   CodeGenModule(ASTContext &C, const HeaderSearchOptions &headersearchopts,
501                 const PreprocessorOptions &ppopts,
502                 const CodeGenOptions &CodeGenOpts, llvm::Module &M,
503                 DiagnosticsEngine &Diags,
504                 CoverageSourceInfo *CoverageInfo = nullptr);
505
506   ~CodeGenModule();
507
508   void clear();
509
510   /// Finalize LLVM code generation.
511   void Release();
512
513   /// Return a reference to the configured Objective-C runtime.
514   CGObjCRuntime &getObjCRuntime() {
515     if (!ObjCRuntime) createObjCRuntime();
516     return *ObjCRuntime;
517   }
518
519   /// Return true iff an Objective-C runtime has been configured.
520   bool hasObjCRuntime() { return !!ObjCRuntime; }
521
522   /// Return a reference to the configured OpenCL runtime.
523   CGOpenCLRuntime &getOpenCLRuntime() {
524     assert(OpenCLRuntime != nullptr);
525     return *OpenCLRuntime;
526   }
527
528   /// Return a reference to the configured OpenMP runtime.
529   CGOpenMPRuntime &getOpenMPRuntime() {
530     assert(OpenMPRuntime != nullptr);
531     return *OpenMPRuntime;
532   }
533
534   /// Return a reference to the configured CUDA runtime.
535   CGCUDARuntime &getCUDARuntime() {
536     assert(CUDARuntime != nullptr);
537     return *CUDARuntime;
538   }
539
540   ObjCEntrypoints &getObjCEntrypoints() const {
541     assert(ObjCData != nullptr);
542     return *ObjCData;
543   }
544
545   // Version checking function, used to implement ObjC's @available:
546   // i32 @__isOSVersionAtLeast(i32, i32, i32)
547   llvm::Constant *IsOSVersionAtLeastFn = nullptr;
548
549   InstrProfStats &getPGOStats() { return PGOStats; }
550   llvm::IndexedInstrProfReader *getPGOReader() const { return PGOReader.get(); }
551
552   CoverageMappingModuleGen *getCoverageMapping() const {
553     return CoverageMapping.get();
554   }
555
556   llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) {
557     return StaticLocalDeclMap[D];
558   }
559   void setStaticLocalDeclAddress(const VarDecl *D, 
560                                  llvm::Constant *C) {
561     StaticLocalDeclMap[D] = C;
562   }
563
564   llvm::Constant *
565   getOrCreateStaticVarDecl(const VarDecl &D,
566                            llvm::GlobalValue::LinkageTypes Linkage);
567
568   llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) {
569     return StaticLocalDeclGuardMap[D];
570   }
571   void setStaticLocalDeclGuardAddress(const VarDecl *D, 
572                                       llvm::GlobalVariable *C) {
573     StaticLocalDeclGuardMap[D] = C;
574   }
575
576   bool lookupRepresentativeDecl(StringRef MangledName,
577                                 GlobalDecl &Result) const;
578
579   llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) {
580     return AtomicSetterHelperFnMap[Ty];
581   }
582   void setAtomicSetterHelperFnMap(QualType Ty,
583                             llvm::Constant *Fn) {
584     AtomicSetterHelperFnMap[Ty] = Fn;
585   }
586
587   llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) {
588     return AtomicGetterHelperFnMap[Ty];
589   }
590   void setAtomicGetterHelperFnMap(QualType Ty,
591                             llvm::Constant *Fn) {
592     AtomicGetterHelperFnMap[Ty] = Fn;
593   }
594
595   llvm::Constant *getTypeDescriptorFromMap(QualType Ty) {
596     return TypeDescriptorMap[Ty];
597   }
598   void setTypeDescriptorInMap(QualType Ty, llvm::Constant *C) {
599     TypeDescriptorMap[Ty] = C;
600   }
601
602   CGDebugInfo *getModuleDebugInfo() { return DebugInfo.get(); }
603
604   llvm::MDNode *getNoObjCARCExceptionsMetadata() {
605     if (!NoObjCARCExceptionsMetadata)
606       NoObjCARCExceptionsMetadata = llvm::MDNode::get(getLLVMContext(), None);
607     return NoObjCARCExceptionsMetadata;
608   }
609
610   ASTContext &getContext() const { return Context; }
611   const LangOptions &getLangOpts() const { return LangOpts; }
612   const HeaderSearchOptions &getHeaderSearchOpts()
613     const { return HeaderSearchOpts; }
614   const PreprocessorOptions &getPreprocessorOpts()
615     const { return PreprocessorOpts; }
616   const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
617   llvm::Module &getModule() const { return TheModule; }
618   DiagnosticsEngine &getDiags() const { return Diags; }
619   const llvm::DataLayout &getDataLayout() const {
620     return TheModule.getDataLayout();
621   }
622   const TargetInfo &getTarget() const { return Target; }
623   const llvm::Triple &getTriple() const { return Target.getTriple(); }
624   bool supportsCOMDAT() const;
625   void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO);
626
627   CGCXXABI &getCXXABI() const { return *ABI; }
628   llvm::LLVMContext &getLLVMContext() { return VMContext; }
629
630   bool shouldUseTBAA() const { return TBAA != nullptr; }
631
632   const TargetCodeGenInfo &getTargetCodeGenInfo(); 
633   
634   CodeGenTypes &getTypes() { return Types; }
635  
636   CodeGenVTables &getVTables() { return VTables; }
637
638   ItaniumVTableContext &getItaniumVTableContext() {
639     return VTables.getItaniumVTableContext();
640   }
641
642   MicrosoftVTableContext &getMicrosoftVTableContext() {
643     return VTables.getMicrosoftVTableContext();
644   }
645
646   CtorList &getGlobalCtors() { return GlobalCtors; }
647   CtorList &getGlobalDtors() { return GlobalDtors; }
648
649   llvm::MDNode *getTBAAInfo(QualType QTy);
650   llvm::MDNode *getTBAAInfoForVTablePtr();
651   llvm::MDNode *getTBAAStructInfo(QualType QTy);
652   /// Return the path-aware tag for given base type, access node and offset.
653   llvm::MDNode *getTBAAStructTagInfo(QualType BaseTy, llvm::MDNode *AccessN,
654                                      uint64_t O);
655
656   bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor);
657
658   bool isPaddedAtomicType(QualType type);
659   bool isPaddedAtomicType(const AtomicType *type);
660
661   /// Decorate the instruction with a TBAA tag. For scalar TBAA, the tag
662   /// is the same as the type. For struct-path aware TBAA, the tag
663   /// is different from the type: base type, access type and offset.
664   /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
665   void DecorateInstructionWithTBAA(llvm::Instruction *Inst,
666                                    llvm::MDNode *TBAAInfo,
667                                    bool ConvertTypeToTag = true);
668
669   /// Adds !invariant.barrier !tag to instruction
670   void DecorateInstructionWithInvariantGroup(llvm::Instruction *I,
671                                              const CXXRecordDecl *RD);
672
673   /// Emit the given number of characters as a value of type size_t.
674   llvm::ConstantInt *getSize(CharUnits numChars);
675
676   /// Set the visibility for the given LLVM GlobalValue.
677   void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const;
678
679   /// Set the TLS mode for the given LLVM GlobalValue for the thread-local
680   /// variable declaration D.
681   void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const;
682
683   static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
684     switch (V) {
685     case DefaultVisibility:   return llvm::GlobalValue::DefaultVisibility;
686     case HiddenVisibility:    return llvm::GlobalValue::HiddenVisibility;
687     case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
688     }
689     llvm_unreachable("unknown visibility!");
690   }
691
692   llvm::Constant *GetAddrOfGlobal(GlobalDecl GD,
693                                   ForDefinition_t IsForDefinition
694                                     = NotForDefinition);
695
696   /// Will return a global variable of the given type. If a variable with a
697   /// different type already exists then a new  variable with the right type
698   /// will be created and all uses of the old variable will be replaced with a
699   /// bitcast to the new variable.
700   llvm::GlobalVariable *
701   CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty,
702                                     llvm::GlobalValue::LinkageTypes Linkage);
703
704   llvm::Function *
705   CreateGlobalInitOrDestructFunction(llvm::FunctionType *ty, const Twine &name,
706                                      const CGFunctionInfo &FI,
707                                      SourceLocation Loc = SourceLocation(),
708                                      bool TLS = false);
709
710   /// Return the address space of the underlying global variable for D, as
711   /// determined by its declaration. Normally this is the same as the address
712   /// space of D's type, but in CUDA, address spaces are associated with
713   /// declarations, not types.
714   unsigned GetGlobalVarAddressSpace(const VarDecl *D, unsigned AddrSpace);
715
716   /// Return the llvm::Constant for the address of the given global variable.
717   /// If Ty is non-null and if the global doesn't exist, then it will be created
718   /// with the specified type instead of whatever the normal requested type
719   /// would be. If IsForDefinition is true, it is guranteed that an actual
720   /// global with type Ty will be returned, not conversion of a variable with
721   /// the same mangled name but some other type.
722   llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
723                                      llvm::Type *Ty = nullptr,
724                                      ForDefinition_t IsForDefinition
725                                        = NotForDefinition);
726
727   /// Return the address of the given function. If Ty is non-null, then this
728   /// function will use the specified type if it has to create it.
729   llvm::Constant *GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty = nullptr,
730                                     bool ForVTable = false,
731                                     bool DontDefer = false,
732                                     ForDefinition_t IsForDefinition
733                                       = NotForDefinition);
734
735   /// Get the address of the RTTI descriptor for the given type.
736   llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
737
738   /// Get the address of a uuid descriptor .
739   ConstantAddress GetAddrOfUuidDescriptor(const CXXUuidofExpr* E);
740
741   /// Get the address of the thunk for the given global decl.
742   llvm::Constant *GetAddrOfThunk(GlobalDecl GD, const ThunkInfo &Thunk);
743
744   /// Get a reference to the target of VD.
745   ConstantAddress GetWeakRefReference(const ValueDecl *VD);
746
747   /// Returns the assumed alignment of an opaque pointer to the given class.
748   CharUnits getClassPointerAlignment(const CXXRecordDecl *CD);
749
750   /// Returns the assumed alignment of a virtual base of a class.
751   CharUnits getVBaseAlignment(CharUnits DerivedAlign,
752                               const CXXRecordDecl *Derived,
753                               const CXXRecordDecl *VBase);
754
755   /// Given a class pointer with an actual known alignment, and the
756   /// expected alignment of an object at a dynamic offset w.r.t that
757   /// pointer, return the alignment to assume at the offset.
758   CharUnits getDynamicOffsetAlignment(CharUnits ActualAlign,
759                                       const CXXRecordDecl *Class,
760                                       CharUnits ExpectedTargetAlign);
761
762   CharUnits
763   computeNonVirtualBaseClassOffset(const CXXRecordDecl *DerivedClass,
764                                    CastExpr::path_const_iterator Start,
765                                    CastExpr::path_const_iterator End);
766
767   /// Returns the offset from a derived class to  a class. Returns null if the
768   /// offset is 0.
769   llvm::Constant *
770   GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
771                                CastExpr::path_const_iterator PathBegin,
772                                CastExpr::path_const_iterator PathEnd);
773
774   llvm::FoldingSet<BlockByrefHelpers> ByrefHelpersCache;
775
776   /// Fetches the global unique block count.
777   int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; }
778   
779   /// Fetches the type of a generic block descriptor.
780   llvm::Type *getBlockDescriptorType();
781
782   /// The type of a generic block literal.
783   llvm::Type *getGenericBlockLiteralType();
784
785   /// Gets the address of a block which requires no captures.
786   llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, StringRef Name);
787
788   /// Returns the address of a block which requires no caputres, or null if
789   /// we've yet to emit the block for BE.
790   llvm::Constant *getAddrOfGlobalBlockIfEmitted(const BlockExpr *BE) {
791     return EmittedGlobalBlocks.lookup(BE);
792   }
793
794   /// Notes that BE's global block is available via Addr. Asserts that BE
795   /// isn't already emitted.
796   void setAddrOfGlobalBlock(const BlockExpr *BE, llvm::Constant *Addr);
797   
798   /// Return a pointer to a constant CFString object for the given string.
799   ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal);
800
801   /// Return a pointer to a constant NSString object for the given string. Or a
802   /// user defined String object as defined via
803   /// -fconstant-string-class=class_name option.
804   ConstantAddress GetAddrOfConstantString(const StringLiteral *Literal);
805
806   /// Return a constant array for the given string.
807   llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E);
808
809   /// Return a pointer to a constant array for the given string literal.
810   ConstantAddress
811   GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
812                                      StringRef Name = ".str");
813
814   /// Return a pointer to a constant array for the given ObjCEncodeExpr node.
815   ConstantAddress
816   GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
817
818   /// Returns a pointer to a character array containing the literal and a
819   /// terminating '\0' character. The result has pointer to array type.
820   ///
821   /// \param GlobalName If provided, the name to use for the global (if one is
822   /// created).
823   ConstantAddress
824   GetAddrOfConstantCString(const std::string &Str,
825                            const char *GlobalName = nullptr);
826
827   /// Returns a pointer to a constant global variable for the given file-scope
828   /// compound literal expression.
829   ConstantAddress GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E);
830
831   /// If it's been emitted already, returns the GlobalVariable corresponding to
832   /// a compound literal. Otherwise, returns null.
833   llvm::GlobalVariable *
834   getAddrOfConstantCompoundLiteralIfEmitted(const CompoundLiteralExpr *E);
835
836   /// Notes that CLE's GlobalVariable is GV. Asserts that CLE isn't already
837   /// emitted.
838   void setAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *CLE,
839                                         llvm::GlobalVariable *GV);
840
841   /// \brief Returns a pointer to a global variable representing a temporary
842   /// with static or thread storage duration.
843   ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E,
844                                            const Expr *Inner);
845
846   /// \brief Retrieve the record type that describes the state of an
847   /// Objective-C fast enumeration loop (for..in).
848   QualType getObjCFastEnumerationStateType();
849
850   // Produce code for this constructor/destructor. This method doesn't try
851   // to apply any ABI rules about which other constructors/destructors
852   // are needed or if they are alias to each other.
853   llvm::Function *codegenCXXStructor(const CXXMethodDecl *MD,
854                                      StructorType Type);
855
856   /// Return the address of the constructor/destructor of the given type.
857   llvm::Constant *
858   getAddrOfCXXStructor(const CXXMethodDecl *MD, StructorType Type,
859                        const CGFunctionInfo *FnInfo = nullptr,
860                        llvm::FunctionType *FnType = nullptr,
861                        bool DontDefer = false,
862                        ForDefinition_t IsForDefinition = NotForDefinition);
863
864   /// Given a builtin id for a function like "__builtin_fabsf", return a
865   /// Function* for "fabsf".
866   llvm::Constant *getBuiltinLibFunction(const FunctionDecl *FD,
867                                         unsigned BuiltinID);
868
869   llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys = None);
870
871   /// Emit code for a single top level declaration.
872   void EmitTopLevelDecl(Decl *D);
873
874   /// \brief Stored a deferred empty coverage mapping for an unused
875   /// and thus uninstrumented top level declaration.
876   void AddDeferredUnusedCoverageMapping(Decl *D);
877
878   /// \brief Remove the deferred empty coverage mapping as this
879   /// declaration is actually instrumented.
880   void ClearUnusedCoverageMapping(const Decl *D);
881
882   /// \brief Emit all the deferred coverage mappings
883   /// for the uninstrumented functions.
884   void EmitDeferredUnusedCoverageMappings();
885
886   /// Tell the consumer that this variable has been instantiated.
887   void HandleCXXStaticMemberVarInstantiation(VarDecl *VD);
888
889   /// \brief If the declaration has internal linkage but is inside an
890   /// extern "C" linkage specification, prepare to emit an alias for it
891   /// to the expected name.
892   template<typename SomeDecl>
893   void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV);
894
895   /// Add a global to a list to be added to the llvm.used metadata.
896   void addUsedGlobal(llvm::GlobalValue *GV);
897
898   /// Add a global to a list to be added to the llvm.compiler.used metadata.
899   void addCompilerUsedGlobal(llvm::GlobalValue *GV);
900
901   /// Add a destructor and object to add to the C++ global destructor function.
902   void AddCXXDtorEntry(llvm::Constant *DtorFn, llvm::Constant *Object) {
903     CXXGlobalDtors.emplace_back(DtorFn, Object);
904   }
905
906   /// Create a new runtime function with the specified type and name.
907   llvm::Constant *
908   CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name,
909                         llvm::AttributeList ExtraAttrs = llvm::AttributeList(),
910                         bool Local = false);
911
912   /// Create a new compiler builtin function with the specified type and name.
913   llvm::Constant *
914   CreateBuiltinFunction(llvm::FunctionType *Ty, StringRef Name,
915                         llvm::AttributeList ExtraAttrs = llvm::AttributeList());
916   /// Create a new runtime global variable with the specified type and name.
917   llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty,
918                                         StringRef Name);
919
920   ///@name Custom Blocks Runtime Interfaces
921   ///@{
922
923   llvm::Constant *getNSConcreteGlobalBlock();
924   llvm::Constant *getNSConcreteStackBlock();
925   llvm::Constant *getBlockObjectAssign();
926   llvm::Constant *getBlockObjectDispose();
927
928   ///@}
929
930   llvm::Constant *getLLVMLifetimeStartFn();
931   llvm::Constant *getLLVMLifetimeEndFn();
932
933   // Make sure that this type is translated.
934   void UpdateCompletedType(const TagDecl *TD);
935
936   llvm::Constant *getMemberPointerConstant(const UnaryOperator *e);
937
938   /// Try to emit the initializer for the given declaration as a constant;
939   /// returns 0 if the expression cannot be emitted as a constant.
940   llvm::Constant *EmitConstantInit(const VarDecl &D,
941                                    CodeGenFunction *CGF = nullptr);
942
943   /// Try to emit the given expression as a constant; returns 0 if the
944   /// expression cannot be emitted as a constant.
945   llvm::Constant *EmitConstantExpr(const Expr *E, QualType DestType,
946                                    CodeGenFunction *CGF = nullptr);
947
948   /// Emit the given constant value as a constant, in the type's scalar
949   /// representation.
950   llvm::Constant *EmitConstantValue(const APValue &Value, QualType DestType,
951                                     CodeGenFunction *CGF = nullptr);
952
953   /// Emit the given constant value as a constant, in the type's memory
954   /// representation.
955   llvm::Constant *EmitConstantValueForMemory(const APValue &Value,
956                                              QualType DestType,
957                                              CodeGenFunction *CGF = nullptr);
958
959   /// \brief Emit type info if type of an expression is a variably modified
960   /// type. Also emit proper debug info for cast types.
961   void EmitExplicitCastExprType(const ExplicitCastExpr *E,
962                                 CodeGenFunction *CGF = nullptr);
963
964   /// Return the result of value-initializing the given type, i.e. a null
965   /// expression of the given type.  This is usually, but not always, an LLVM
966   /// null constant.
967   llvm::Constant *EmitNullConstant(QualType T);
968
969   /// Return a null constant appropriate for zero-initializing a base class with
970   /// the given type. This is usually, but not always, an LLVM null constant.
971   llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record);
972
973   /// Emit a general error that something can't be done.
974   void Error(SourceLocation loc, StringRef error);
975
976   /// Print out an error that codegen doesn't support the specified stmt yet.
977   void ErrorUnsupported(const Stmt *S, const char *Type);
978
979   /// Print out an error that codegen doesn't support the specified decl yet.
980   void ErrorUnsupported(const Decl *D, const char *Type);
981
982   /// Set the attributes on the LLVM function for the given decl and function
983   /// info. This applies attributes necessary for handling the ABI as well as
984   /// user specified attributes like section.
985   void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F,
986                                      const CGFunctionInfo &FI);
987
988   /// Set the LLVM function attributes (sext, zext, etc).
989   void SetLLVMFunctionAttributes(const Decl *D,
990                                  const CGFunctionInfo &Info,
991                                  llvm::Function *F);
992
993   /// Set the LLVM function attributes which only apply to a function
994   /// definition.
995   void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
996
997   /// Return true iff the given type uses 'sret' when used as a return type.
998   bool ReturnTypeUsesSRet(const CGFunctionInfo &FI);
999
1000   /// Return true iff the given type uses an argument slot when 'sret' is used
1001   /// as a return type.
1002   bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI);
1003
1004   /// Return true iff the given type uses 'fpret' when used as a return type.
1005   bool ReturnTypeUsesFPRet(QualType ResultType);
1006
1007   /// Return true iff the given type uses 'fp2ret' when used as a return type.
1008   bool ReturnTypeUsesFP2Ret(QualType ResultType);
1009
1010   /// Get the LLVM attributes and calling convention to use for a particular
1011   /// function type.
1012   ///
1013   /// \param Name - The function name.
1014   /// \param Info - The function type information.
1015   /// \param CalleeInfo - The callee information these attributes are being
1016   /// constructed for. If valid, the attributes applied to this decl may
1017   /// contribute to the function attributes and calling convention.
1018   /// \param Attrs [out] - On return, the attribute list to use.
1019   /// \param CallingConv [out] - On return, the LLVM calling convention to use.
1020   void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info,
1021                               CGCalleeInfo CalleeInfo,
1022                               llvm::AttributeList &Attrs, unsigned &CallingConv,
1023                               bool AttrOnCallSite);
1024
1025   /// Adds attributes to F according to our CodeGenOptions and LangOptions, as
1026   /// though we had emitted it ourselves.  We remove any attributes on F that
1027   /// conflict with the attributes we add here.
1028   ///
1029   /// This is useful for adding attrs to bitcode modules that you want to link
1030   /// with but don't control, such as CUDA's libdevice.  When linking with such
1031   /// a bitcode library, you might want to set e.g. its functions'
1032   /// "unsafe-fp-math" attribute to match the attr of the functions you're
1033   /// codegen'ing.  Otherwise, LLVM will interpret the bitcode module's lack of
1034   /// unsafe-fp-math attrs as tantamount to unsafe-fp-math=false, and then LLVM
1035   /// will propagate unsafe-fp-math=false up to every transitive caller of a
1036   /// function in the bitcode library!
1037   ///
1038   /// With the exception of fast-math attrs, this will only make the attributes
1039   /// on the function more conservative.  But it's unsafe to call this on a
1040   /// function which relies on particular fast-math attributes for correctness.
1041   /// It's up to you to ensure that this is safe.
1042   void AddDefaultFnAttrs(llvm::Function &F);
1043
1044   // Fills in the supplied string map with the set of target features for the
1045   // passed in function.
1046   void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
1047                              const FunctionDecl *FD);
1048
1049   StringRef getMangledName(GlobalDecl GD);
1050   StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD);
1051
1052   void EmitTentativeDefinition(const VarDecl *D);
1053
1054   void EmitVTable(CXXRecordDecl *Class);
1055
1056   void RefreshTypeCacheForClass(const CXXRecordDecl *Class);
1057
1058   /// \brief Appends Opts to the "Linker Options" metadata value.
1059   void AppendLinkerOptions(StringRef Opts);
1060
1061   /// \brief Appends a detect mismatch command to the linker options.
1062   void AddDetectMismatch(StringRef Name, StringRef Value);
1063
1064   /// \brief Appends a dependent lib to the "Linker Options" metadata value.
1065   void AddDependentLib(StringRef Lib);
1066
1067   llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD);
1068
1069   void setFunctionLinkage(GlobalDecl GD, llvm::Function *F) {
1070     F->setLinkage(getFunctionLinkage(GD));
1071   }
1072
1073   /// Set the DLL storage class on F.
1074   void setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F);
1075
1076   /// Return the appropriate linkage for the vtable, VTT, and type information
1077   /// of the given class.
1078   llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD);
1079
1080   /// Return the store size, in character units, of the given LLVM type.
1081   CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const;
1082   
1083   /// Returns LLVM linkage for a declarator.
1084   llvm::GlobalValue::LinkageTypes
1085   getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage,
1086                               bool IsConstantVariable);
1087
1088   /// Returns LLVM linkage for a declarator.
1089   llvm::GlobalValue::LinkageTypes
1090   getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant);
1091
1092   /// Emit all the global annotations.
1093   void EmitGlobalAnnotations();
1094
1095   /// Emit an annotation string.
1096   llvm::Constant *EmitAnnotationString(StringRef Str);
1097
1098   /// Emit the annotation's translation unit.
1099   llvm::Constant *EmitAnnotationUnit(SourceLocation Loc);
1100
1101   /// Emit the annotation line number.
1102   llvm::Constant *EmitAnnotationLineNo(SourceLocation L);
1103
1104   /// Generate the llvm::ConstantStruct which contains the annotation
1105   /// information for a given GlobalValue. The annotation struct is
1106   /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
1107   /// GlobalValue being annotated. The second field is the constant string
1108   /// created from the AnnotateAttr's annotation. The third field is a constant
1109   /// string containing the name of the translation unit. The fourth field is
1110   /// the line number in the file of the annotated value declaration.
1111   llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
1112                                    const AnnotateAttr *AA,
1113                                    SourceLocation L);
1114
1115   /// Add global annotations that are set on D, for the global GV. Those
1116   /// annotations are emitted during finalization of the LLVM code.
1117   void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV);
1118
1119   bool isInSanitizerBlacklist(llvm::Function *Fn, SourceLocation Loc) const;
1120
1121   bool isInSanitizerBlacklist(llvm::GlobalVariable *GV, SourceLocation Loc,
1122                               QualType Ty,
1123                               StringRef Category = StringRef()) const;
1124
1125   /// Imbue XRay attributes to a function, applying the always/never attribute
1126   /// lists in the process. Returns true if we did imbue attributes this way,
1127   /// false otherwise.
1128   bool imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
1129                       StringRef Category = StringRef()) const;
1130
1131   SanitizerMetadata *getSanitizerMetadata() {
1132     return SanitizerMD.get();
1133   }
1134
1135   void addDeferredVTable(const CXXRecordDecl *RD) {
1136     DeferredVTables.push_back(RD);
1137   }
1138
1139   /// Emit code for a singal global function or var decl. Forward declarations
1140   /// are emitted lazily.
1141   void EmitGlobal(GlobalDecl D);
1142
1143   bool TryEmitDefinitionAsAlias(GlobalDecl Alias, GlobalDecl Target,
1144                                 bool InEveryTU);
1145   bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D);
1146
1147   /// Set attributes for a global definition.
1148   void setFunctionDefinitionAttributes(const FunctionDecl *D,
1149                                        llvm::Function *F);
1150
1151   llvm::GlobalValue *GetGlobalValue(StringRef Ref);
1152
1153   /// Set attributes which are common to any form of a global definition (alias,
1154   /// Objective-C method, function, global variable).
1155   ///
1156   /// NOTE: This should only be called for definitions.
1157   void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV);
1158
1159   /// Set attributes which must be preserved by an alias. This includes common
1160   /// attributes (i.e. it includes a call to SetCommonAttributes).
1161   ///
1162   /// NOTE: This should only be called for definitions.
1163   void setAliasAttributes(const Decl *D, llvm::GlobalValue *GV);
1164
1165   void addReplacement(StringRef Name, llvm::Constant *C);
1166
1167   void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C);
1168
1169   /// \brief Emit a code for threadprivate directive.
1170   /// \param D Threadprivate declaration.
1171   void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D);
1172
1173   /// \brief Emit a code for declare reduction construct.
1174   void EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
1175                                CodeGenFunction *CGF = nullptr);
1176
1177   /// Returns whether the given record has hidden LTO visibility and therefore
1178   /// may participate in (single-module) CFI and whole-program vtable
1179   /// optimization.
1180   bool HasHiddenLTOVisibility(const CXXRecordDecl *RD);
1181
1182   /// Emit type metadata for the given vtable using the given layout.
1183   void EmitVTableTypeMetadata(llvm::GlobalVariable *VTable,
1184                               const VTableLayout &VTLayout);
1185
1186   /// Generate a cross-DSO type identifier for MD.
1187   llvm::ConstantInt *CreateCrossDsoCfiTypeId(llvm::Metadata *MD);
1188
1189   /// Create a metadata identifier for the given type. This may either be an
1190   /// MDString (for external identifiers) or a distinct unnamed MDNode (for
1191   /// internal identifiers).
1192   llvm::Metadata *CreateMetadataIdentifierForType(QualType T);
1193
1194   /// Create and attach type metadata to the given function.
1195   void CreateFunctionTypeMetadata(const FunctionDecl *FD, llvm::Function *F);
1196
1197   /// Returns whether this module needs the "all-vtables" type identifier.
1198   bool NeedAllVtablesTypeId() const;
1199
1200   /// Create and attach type metadata for the given vtable.
1201   void AddVTableTypeMetadata(llvm::GlobalVariable *VTable, CharUnits Offset,
1202                              const CXXRecordDecl *RD);
1203
1204   /// \brief Get the declaration of std::terminate for the platform.
1205   llvm::Constant *getTerminateFn();
1206
1207   llvm::SanitizerStatReport &getSanStats();
1208
1209   llvm::Value *
1210   createOpenCLIntToSamplerConversion(const Expr *E, CodeGenFunction &CGF);
1211
1212   /// Get target specific null pointer.
1213   /// \param T is the LLVM type of the null pointer.
1214   /// \param QT is the clang QualType of the null pointer.
1215   llvm::Constant *getNullPointer(llvm::PointerType *T, QualType QT);
1216
1217 private:
1218   llvm::Constant *GetOrCreateLLVMFunction(
1219       StringRef MangledName, llvm::Type *Ty, GlobalDecl D, bool ForVTable,
1220       bool DontDefer = false, bool IsThunk = false,
1221       llvm::AttributeList ExtraAttrs = llvm::AttributeList(),
1222       ForDefinition_t IsForDefinition = NotForDefinition);
1223
1224   llvm::Constant *GetOrCreateLLVMGlobal(StringRef MangledName,
1225                                         llvm::PointerType *PTy,
1226                                         const VarDecl *D,
1227                                         ForDefinition_t IsForDefinition
1228                                           = NotForDefinition);
1229
1230   void setNonAliasAttributes(const Decl *D, llvm::GlobalObject *GO);
1231
1232   /// Set function attributes for a function declaration.
1233   void SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1234                              bool IsIncompleteFunction, bool IsThunk);
1235
1236   void EmitGlobalDefinition(GlobalDecl D, llvm::GlobalValue *GV = nullptr);
1237
1238   void EmitGlobalFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
1239   void EmitGlobalVarDefinition(const VarDecl *D, bool IsTentative = false);
1240   void EmitAliasDefinition(GlobalDecl GD);
1241   void emitIFuncDefinition(GlobalDecl GD);
1242   void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
1243   void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
1244   
1245   // C++ related functions.
1246
1247   void EmitDeclContext(const DeclContext *DC);
1248   void EmitLinkageSpec(const LinkageSpecDecl *D);
1249
1250   /// \brief Emit the function that initializes C++ thread_local variables.
1251   void EmitCXXThreadLocalInitFunc();
1252
1253   /// Emit the function that initializes C++ globals.
1254   void EmitCXXGlobalInitFunc();
1255
1256   /// Emit the function that destroys C++ globals.
1257   void EmitCXXGlobalDtorFunc();
1258
1259   /// Emit the function that initializes the specified global (if PerformInit is
1260   /// true) and registers its destructor.
1261   void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
1262                                     llvm::GlobalVariable *Addr,
1263                                     bool PerformInit);
1264
1265   void EmitPointerToInitFunc(const VarDecl *VD, llvm::GlobalVariable *Addr,
1266                              llvm::Function *InitFunc, InitSegAttr *ISA);
1267
1268   // FIXME: Hardcoding priority here is gross.
1269   void AddGlobalCtor(llvm::Function *Ctor, int Priority = 65535,
1270                      llvm::Constant *AssociatedData = nullptr);
1271   void AddGlobalDtor(llvm::Function *Dtor, int Priority = 65535);
1272
1273   /// EmitCtorList - Generates a global array of functions and priorities using
1274   /// the given list and name. This array will have appending linkage and is
1275   /// suitable for use as a LLVM constructor or destructor array. Clears Fns.
1276   void EmitCtorList(CtorList &Fns, const char *GlobalName);
1277
1278   /// Emit any needed decls for which code generation was deferred.
1279   void EmitDeferred();
1280
1281   /// Call replaceAllUsesWith on all pairs in Replacements.
1282   void applyReplacements();
1283
1284   /// Call replaceAllUsesWith on all pairs in GlobalValReplacements.
1285   void applyGlobalValReplacements();
1286
1287   void checkAliases();
1288
1289   /// Emit any vtables which we deferred and still have a use for.
1290   void EmitDeferredVTables();
1291
1292   /// Emit a dummy function that reference a CoreFoundation symbol when
1293   /// @available is used on Darwin.
1294   void emitAtAvailableLinkGuard();
1295
1296   /// Emit the llvm.used and llvm.compiler.used metadata.
1297   void emitLLVMUsed();
1298
1299   /// \brief Emit the link options introduced by imported modules.
1300   void EmitModuleLinkOptions();
1301
1302   /// \brief Emit aliases for internal-linkage declarations inside "C" language
1303   /// linkage specifications, giving them the "expected" name where possible.
1304   void EmitStaticExternCAliases();
1305
1306   void EmitDeclMetadata();
1307
1308   /// \brief Emit the Clang version as llvm.ident metadata.
1309   void EmitVersionIdentMetadata();
1310
1311   /// Emits target specific Metadata for global declarations.
1312   void EmitTargetMetadata();
1313
1314   /// Emit the llvm.gcov metadata used to tell LLVM where to emit the .gcno and
1315   /// .gcda files in a way that persists in .bc files.
1316   void EmitCoverageFile();
1317
1318   /// Emits the initializer for a uuidof string.
1319   llvm::Constant *EmitUuidofInitializer(StringRef uuidstr);
1320
1321   /// Determine whether the definition must be emitted; if this returns \c
1322   /// false, the definition can be emitted lazily if it's used.
1323   bool MustBeEmitted(const ValueDecl *D);
1324
1325   /// Determine whether the definition can be emitted eagerly, or should be
1326   /// delayed until the end of the translation unit. This is relevant for
1327   /// definitions whose linkage can change, e.g. implicit function instantions
1328   /// which may later be explicitly instantiated.
1329   bool MayBeEmittedEagerly(const ValueDecl *D);
1330
1331   /// Check whether we can use a "simpler", more core exceptions personality
1332   /// function.
1333   void SimplifyPersonality();
1334
1335   /// Helper function for ConstructAttributeList and AddDefaultFnAttrs.
1336   /// Constructs an AttrList for a function with the given properties.
1337   void ConstructDefaultFnAttrList(StringRef Name, bool HasOptnone,
1338                                   bool AttrOnCallSite,
1339                                   llvm::AttrBuilder &FuncAttrs);
1340 };
1341 }  // end namespace CodeGen
1342 }  // end namespace clang
1343
1344 #endif // LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H