]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/CodeGen/CodeGenModule.h
Merge ^/head r275759 through r275911.
[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 CLANG_CODEGEN_CODEGENMODULE_H
15 #define CLANG_CODEGEN_CODEGENMODULE_H
16
17 #include "CGVTables.h"
18 #include "CodeGenTypes.h"
19 #include "SanitizerBlacklist.h"
20 #include "clang/AST/Attr.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/GlobalDecl.h"
24 #include "clang/AST/Mangle.h"
25 #include "clang/Basic/ABI.h"
26 #include "clang/Basic/LangOptions.h"
27 #include "clang/Basic/Module.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/SetVector.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/StringMap.h"
32 #include "llvm/IR/CallingConv.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/ValueHandle.h"
35
36 namespace llvm {
37 class Module;
38 class Constant;
39 class ConstantInt;
40 class Function;
41 class GlobalValue;
42 class DataLayout;
43 class FunctionType;
44 class LLVMContext;
45 class IndexedInstrProfReader;
46 }
47
48 namespace clang {
49 class TargetCodeGenInfo;
50 class ASTContext;
51 class AtomicType;
52 class FunctionDecl;
53 class IdentifierInfo;
54 class ObjCMethodDecl;
55 class ObjCImplementationDecl;
56 class ObjCCategoryImplDecl;
57 class ObjCProtocolDecl;
58 class ObjCEncodeExpr;
59 class BlockExpr;
60 class CharUnits;
61 class Decl;
62 class Expr;
63 class Stmt;
64 class InitListExpr;
65 class StringLiteral;
66 class NamedDecl;
67 class ValueDecl;
68 class VarDecl;
69 class LangOptions;
70 class CodeGenOptions;
71 class DiagnosticsEngine;
72 class AnnotateAttr;
73 class CXXDestructorDecl;
74 class Module;
75
76 namespace CodeGen {
77
78 class CallArgList;
79 class CodeGenFunction;
80 class CodeGenTBAA;
81 class CGCXXABI;
82 class CGDebugInfo;
83 class CGObjCRuntime;
84 class CGOpenCLRuntime;
85 class CGOpenMPRuntime;
86 class CGCUDARuntime;
87 class BlockFieldFlags;
88 class FunctionArgList;
89
90 struct OrderGlobalInits {
91   unsigned int priority;
92   unsigned int lex_order;
93   OrderGlobalInits(unsigned int p, unsigned int l)
94       : priority(p), lex_order(l) {}
95
96   bool operator==(const OrderGlobalInits &RHS) const {
97     return priority == RHS.priority && lex_order == RHS.lex_order;
98   }
99
100   bool operator<(const OrderGlobalInits &RHS) const {
101     return std::tie(priority, lex_order) <
102            std::tie(RHS.priority, RHS.lex_order);
103   }
104 };
105
106 struct CodeGenTypeCache {
107   /// void
108   llvm::Type *VoidTy;
109
110   /// i8, i16, i32, and i64
111   llvm::IntegerType *Int8Ty, *Int16Ty, *Int32Ty, *Int64Ty;
112   /// float, double
113   llvm::Type *FloatTy, *DoubleTy;
114
115   /// int
116   llvm::IntegerType *IntTy;
117
118   /// intptr_t, size_t, and ptrdiff_t, which we assume are the same size.
119   union {
120     llvm::IntegerType *IntPtrTy;
121     llvm::IntegerType *SizeTy;
122     llvm::IntegerType *PtrDiffTy;
123   };
124
125   /// void* in address space 0
126   union {
127     llvm::PointerType *VoidPtrTy;
128     llvm::PointerType *Int8PtrTy;
129   };
130
131   /// void** in address space 0
132   union {
133     llvm::PointerType *VoidPtrPtrTy;
134     llvm::PointerType *Int8PtrPtrTy;
135   };
136
137   /// The width of a pointer into the generic address space.
138   unsigned char PointerWidthInBits;
139
140   /// The size and alignment of a pointer into the generic address
141   /// space.
142   union {
143     unsigned char PointerAlignInBytes;
144     unsigned char PointerSizeInBytes;
145     unsigned char SizeSizeInBytes; // sizeof(size_t)
146   };
147
148   llvm::CallingConv::ID RuntimeCC;
149   llvm::CallingConv::ID getRuntimeCC() const { return RuntimeCC; }
150 };
151
152 struct RREntrypoints {
153   RREntrypoints() { memset(this, 0, sizeof(*this)); }
154   /// void objc_autoreleasePoolPop(void*);
155   llvm::Constant *objc_autoreleasePoolPop;
156
157   /// void *objc_autoreleasePoolPush(void);
158   llvm::Constant *objc_autoreleasePoolPush;
159 };
160
161 struct ARCEntrypoints {
162   ARCEntrypoints() { memset(this, 0, sizeof(*this)); }
163
164   /// id objc_autorelease(id);
165   llvm::Constant *objc_autorelease;
166
167   /// id objc_autoreleaseReturnValue(id);
168   llvm::Constant *objc_autoreleaseReturnValue;
169
170   /// void objc_copyWeak(id *dest, id *src);
171   llvm::Constant *objc_copyWeak;
172
173   /// void objc_destroyWeak(id*);
174   llvm::Constant *objc_destroyWeak;
175
176   /// id objc_initWeak(id*, id);
177   llvm::Constant *objc_initWeak;
178
179   /// id objc_loadWeak(id*);
180   llvm::Constant *objc_loadWeak;
181
182   /// id objc_loadWeakRetained(id*);
183   llvm::Constant *objc_loadWeakRetained;
184
185   /// void objc_moveWeak(id *dest, id *src);
186   llvm::Constant *objc_moveWeak;
187
188   /// id objc_retain(id);
189   llvm::Constant *objc_retain;
190
191   /// id objc_retainAutorelease(id);
192   llvm::Constant *objc_retainAutorelease;
193
194   /// id objc_retainAutoreleaseReturnValue(id);
195   llvm::Constant *objc_retainAutoreleaseReturnValue;
196
197   /// id objc_retainAutoreleasedReturnValue(id);
198   llvm::Constant *objc_retainAutoreleasedReturnValue;
199
200   /// id objc_retainBlock(id);
201   llvm::Constant *objc_retainBlock;
202
203   /// void objc_release(id);
204   llvm::Constant *objc_release;
205
206   /// id objc_storeStrong(id*, id);
207   llvm::Constant *objc_storeStrong;
208
209   /// id objc_storeWeak(id*, id);
210   llvm::Constant *objc_storeWeak;
211
212   /// A void(void) inline asm to use to mark that the return value of
213   /// a call will be immediately retain.
214   llvm::InlineAsm *retainAutoreleasedReturnValueMarker;
215
216   /// void clang.arc.use(...);
217   llvm::Constant *clang_arc_use;
218 };
219
220 /// This class records statistics on instrumentation based profiling.
221 class InstrProfStats {
222   uint32_t VisitedInMainFile;
223   uint32_t MissingInMainFile;
224   uint32_t Visited;
225   uint32_t Missing;
226   uint32_t Mismatched;
227
228 public:
229   InstrProfStats()
230       : VisitedInMainFile(0), MissingInMainFile(0), Visited(0), Missing(0),
231         Mismatched(0) {}
232   /// Record that we've visited a function and whether or not that function was
233   /// in the main source file.
234   void addVisited(bool MainFile) {
235     if (MainFile)
236       ++VisitedInMainFile;
237     ++Visited;
238   }
239   /// Record that a function we've visited has no profile data.
240   void addMissing(bool MainFile) {
241     if (MainFile)
242       ++MissingInMainFile;
243     ++Missing;
244   }
245   /// Record that a function we've visited has mismatched profile data.
246   void addMismatched(bool MainFile) { ++Mismatched; }
247   /// Whether or not the stats we've gathered indicate any potential problems.
248   bool hasDiagnostics() { return Missing || Mismatched; }
249   /// Report potential problems we've found to \c Diags.
250   void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile);
251 };
252
253 /// This class organizes the cross-function state that is used while generating
254 /// LLVM code.
255 class CodeGenModule : public CodeGenTypeCache {
256   CodeGenModule(const CodeGenModule &) LLVM_DELETED_FUNCTION;
257   void operator=(const CodeGenModule &) LLVM_DELETED_FUNCTION;
258
259   struct Structor {
260     Structor() : Priority(0), Initializer(nullptr), AssociatedData(nullptr) {}
261     Structor(int Priority, llvm::Constant *Initializer,
262              llvm::Constant *AssociatedData)
263         : Priority(Priority), Initializer(Initializer),
264           AssociatedData(AssociatedData) {}
265     int Priority;
266     llvm::Constant *Initializer;
267     llvm::Constant *AssociatedData;
268   };
269
270   typedef std::vector<Structor> CtorList;
271
272   ASTContext &Context;
273   const LangOptions &LangOpts;
274   const CodeGenOptions &CodeGenOpts;
275   llvm::Module &TheModule;
276   DiagnosticsEngine &Diags;
277   const llvm::DataLayout &TheDataLayout;
278   const TargetInfo &Target;
279   std::unique_ptr<CGCXXABI> ABI;
280   llvm::LLVMContext &VMContext;
281
282   CodeGenTBAA *TBAA;
283   
284   mutable const 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   CGObjCRuntime* ObjCRuntime;
295   CGOpenCLRuntime* OpenCLRuntime;
296   CGOpenMPRuntime* OpenMPRuntime;
297   CGCUDARuntime* CUDARuntime;
298   CGDebugInfo* DebugInfo;
299   ARCEntrypoints *ARCData;
300   llvm::MDNode *NoObjCARCExceptionsMetadata;
301   RREntrypoints *RRData;
302   std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader;
303   InstrProfStats PGOStats;
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   struct DeferredGlobal {
319     DeferredGlobal(llvm::GlobalValue *GV, GlobalDecl GD) : GV(GV), GD(GD) {}
320     llvm::AssertingVH<llvm::GlobalValue> GV;
321     GlobalDecl GD;
322   };
323   std::vector<DeferredGlobal> DeferredDeclsToEmit;
324   void addDeferredDeclToEmit(llvm::GlobalValue *GV, GlobalDecl GD) {
325     DeferredDeclsToEmit.push_back(DeferredGlobal(GV, GD));
326   }
327
328   /// List of alias we have emitted. Used to make sure that what they point to
329   /// is defined once we get to the end of the of the translation unit.
330   std::vector<GlobalDecl> Aliases;
331
332   typedef llvm::StringMap<llvm::TrackingVH<llvm::Constant> > ReplacementsTy;
333   ReplacementsTy Replacements;
334
335   /// A queue of (optional) vtables to consider emitting.
336   std::vector<const CXXRecordDecl*> DeferredVTables;
337
338   /// List of global values which are required to be present in the object file;
339   /// bitcast to i8*. This is used for forcing visibility of symbols which may
340   /// otherwise be optimized out.
341   std::vector<llvm::WeakVH> LLVMUsed;
342   std::vector<llvm::WeakVH> LLVMCompilerUsed;
343
344   /// Store the list of global constructors and their respective priorities to
345   /// be emitted when the translation unit is complete.
346   CtorList GlobalCtors;
347
348   /// Store the list of global destructors and their respective priorities to be
349   /// emitted when the translation unit is complete.
350   CtorList GlobalDtors;
351
352   /// An ordered map of canonical GlobalDecls to their mangled names.
353   llvm::MapVector<GlobalDecl, StringRef> MangledDeclNames;
354   llvm::StringMap<GlobalDecl, llvm::BumpPtrAllocator> Manglings;
355
356   /// Global annotations.
357   std::vector<llvm::Constant*> Annotations;
358
359   /// Map used to get unique annotation strings.
360   llvm::StringMap<llvm::Constant*> AnnotationStrings;
361
362   llvm::StringMap<llvm::Constant*> CFConstantStringMap;
363
364   llvm::DenseMap<llvm::Constant *, llvm::GlobalVariable *> ConstantStringMap;
365   llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap;
366   llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardMap;
367   llvm::DenseMap<const Expr*, llvm::Constant *> MaterializedGlobalTemporaryMap;
368
369   llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap;
370   llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap;
371
372   /// Map used to get unique type descriptor constants for sanitizers.
373   llvm::DenseMap<QualType, llvm::Constant *> TypeDescriptorMap;
374
375   /// Map used to track internal linkage functions declared within
376   /// extern "C" regions.
377   typedef llvm::MapVector<IdentifierInfo *,
378                           llvm::GlobalValue *> StaticExternCMap;
379   StaticExternCMap StaticExternCValues;
380
381   /// \brief thread_local variables defined or used in this TU.
382   std::vector<std::pair<const VarDecl *, llvm::GlobalVariable *> >
383     CXXThreadLocals;
384
385   /// \brief thread_local variables with initializers that need to run
386   /// before any thread_local variable in this TU is odr-used.
387   std::vector<llvm::Constant*> CXXThreadLocalInits;
388
389   /// Global variables with initializers that need to run before main.
390   std::vector<llvm::Constant*> CXXGlobalInits;
391
392   /// When a C++ decl with an initializer is deferred, null is
393   /// appended to CXXGlobalInits, and the index of that null is placed
394   /// here so that the initializer will be performed in the correct
395   /// order.
396   llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition;
397   
398   typedef std::pair<OrderGlobalInits, llvm::Function*> GlobalInitData;
399
400   struct GlobalInitPriorityCmp {
401     bool operator()(const GlobalInitData &LHS,
402                     const GlobalInitData &RHS) const {
403       return LHS.first.priority < RHS.first.priority;
404     }
405   };
406
407   /// Global variables with initializers whose order of initialization is set by
408   /// init_priority attribute.
409   SmallVector<GlobalInitData, 8> PrioritizedCXXGlobalInits;
410
411   /// Global destructor functions and arguments that need to run on termination.
412   std::vector<std::pair<llvm::WeakVH,llvm::Constant*> > CXXGlobalDtors;
413
414   /// \brief The complete set of modules that has been imported.
415   llvm::SetVector<clang::Module *> ImportedModules;
416
417   /// \brief A vector of metadata strings.
418   SmallVector<llvm::Value *, 16> LinkerOptionsMetadata;
419
420   /// @name Cache for Objective-C runtime types
421   /// @{
422
423   /// Cached reference to the class for constant strings. This value has type
424   /// int * but is actually an Obj-C class pointer.
425   llvm::WeakVH CFConstantStringClassRef;
426
427   /// Cached reference to the class for constant strings. This value has type
428   /// int * but is actually an Obj-C class pointer.
429   llvm::WeakVH ConstantStringClassRef;
430
431   /// \brief The LLVM type corresponding to NSConstantString.
432   llvm::StructType *NSConstantStringType;
433   
434   /// \brief The type used to describe the state of a fast enumeration in
435   /// Objective-C's for..in loop.
436   QualType ObjCFastEnumerationStateType;
437   
438   /// @}
439
440   /// Lazily create the Objective-C runtime
441   void createObjCRuntime();
442
443   void createOpenCLRuntime();
444   void createOpenMPRuntime();
445   void createCUDARuntime();
446
447   bool isTriviallyRecursive(const FunctionDecl *F);
448   bool shouldEmitFunction(GlobalDecl GD);
449
450   /// @name Cache for Blocks Runtime Globals
451   /// @{
452
453   llvm::Constant *NSConcreteGlobalBlock;
454   llvm::Constant *NSConcreteStackBlock;
455
456   llvm::Constant *BlockObjectAssign;
457   llvm::Constant *BlockObjectDispose;
458
459   llvm::Type *BlockDescriptorType;
460   llvm::Type *GenericBlockLiteralType;
461
462   struct {
463     int GlobalUniqueCount;
464   } Block;
465
466   /// void @llvm.lifetime.start(i64 %size, i8* nocapture <ptr>)
467   llvm::Constant *LifetimeStartFn;
468
469   /// void @llvm.lifetime.end(i64 %size, i8* nocapture <ptr>)
470   llvm::Constant *LifetimeEndFn;
471
472   GlobalDecl initializedGlobalDecl;
473
474   SanitizerBlacklist SanitizerBL;
475
476   /// @}
477 public:
478   CodeGenModule(ASTContext &C, const CodeGenOptions &CodeGenOpts,
479                 llvm::Module &M, const llvm::DataLayout &TD,
480                 DiagnosticsEngine &Diags);
481
482   ~CodeGenModule();
483
484   void clear();
485
486   /// Finalize LLVM code generation.
487   void Release();
488
489   /// Return a reference to the configured Objective-C runtime.
490   CGObjCRuntime &getObjCRuntime() {
491     if (!ObjCRuntime) createObjCRuntime();
492     return *ObjCRuntime;
493   }
494
495   /// Return true iff an Objective-C runtime has been configured.
496   bool hasObjCRuntime() { return !!ObjCRuntime; }
497
498   /// Return a reference to the configured OpenCL runtime.
499   CGOpenCLRuntime &getOpenCLRuntime() {
500     assert(OpenCLRuntime != nullptr);
501     return *OpenCLRuntime;
502   }
503
504   /// Return a reference to the configured OpenMP runtime.
505   CGOpenMPRuntime &getOpenMPRuntime() {
506     assert(OpenMPRuntime != nullptr);
507     return *OpenMPRuntime;
508   }
509
510   /// Return a reference to the configured CUDA runtime.
511   CGCUDARuntime &getCUDARuntime() {
512     assert(CUDARuntime != nullptr);
513     return *CUDARuntime;
514   }
515
516   ARCEntrypoints &getARCEntrypoints() const {
517     assert(getLangOpts().ObjCAutoRefCount && ARCData != nullptr);
518     return *ARCData;
519   }
520
521   RREntrypoints &getRREntrypoints() const {
522     assert(RRData != nullptr);
523     return *RRData;
524   }
525
526   InstrProfStats &getPGOStats() { return PGOStats; }
527   llvm::IndexedInstrProfReader *getPGOReader() const { return PGOReader.get(); }
528
529   llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) {
530     return StaticLocalDeclMap[D];
531   }
532   void setStaticLocalDeclAddress(const VarDecl *D, 
533                                  llvm::Constant *C) {
534     StaticLocalDeclMap[D] = C;
535   }
536
537   llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) {
538     return StaticLocalDeclGuardMap[D];
539   }
540   void setStaticLocalDeclGuardAddress(const VarDecl *D, 
541                                       llvm::GlobalVariable *C) {
542     StaticLocalDeclGuardMap[D] = C;
543   }
544
545   bool lookupRepresentativeDecl(StringRef MangledName,
546                                 GlobalDecl &Result) const;
547
548   llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) {
549     return AtomicSetterHelperFnMap[Ty];
550   }
551   void setAtomicSetterHelperFnMap(QualType Ty,
552                             llvm::Constant *Fn) {
553     AtomicSetterHelperFnMap[Ty] = Fn;
554   }
555
556   llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) {
557     return AtomicGetterHelperFnMap[Ty];
558   }
559   void setAtomicGetterHelperFnMap(QualType Ty,
560                             llvm::Constant *Fn) {
561     AtomicGetterHelperFnMap[Ty] = Fn;
562   }
563
564   llvm::Constant *getTypeDescriptorFromMap(QualType Ty) {
565     return TypeDescriptorMap[Ty];
566   }
567   void setTypeDescriptorInMap(QualType Ty, llvm::Constant *C) {
568     TypeDescriptorMap[Ty] = C;
569   }
570
571   CGDebugInfo *getModuleDebugInfo() { return DebugInfo; }
572
573   llvm::MDNode *getNoObjCARCExceptionsMetadata() {
574     if (!NoObjCARCExceptionsMetadata)
575       NoObjCARCExceptionsMetadata =
576         llvm::MDNode::get(getLLVMContext(),
577                           SmallVector<llvm::Value*,1>());
578     return NoObjCARCExceptionsMetadata;
579   }
580
581   ASTContext &getContext() const { return Context; }
582   const LangOptions &getLangOpts() const { return LangOpts; }
583   const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
584   llvm::Module &getModule() const { return TheModule; }
585   DiagnosticsEngine &getDiags() const { return Diags; }
586   const llvm::DataLayout &getDataLayout() const { return TheDataLayout; }
587   const TargetInfo &getTarget() const { return Target; }
588   CGCXXABI &getCXXABI() const { return *ABI; }
589   llvm::LLVMContext &getLLVMContext() { return VMContext; }
590
591   bool shouldUseTBAA() const { return TBAA != nullptr; }
592
593   const TargetCodeGenInfo &getTargetCodeGenInfo(); 
594   
595   CodeGenTypes &getTypes() { return Types; }
596  
597   CodeGenVTables &getVTables() { return VTables; }
598
599   ItaniumVTableContext &getItaniumVTableContext() {
600     return VTables.getItaniumVTableContext();
601   }
602
603   MicrosoftVTableContext &getMicrosoftVTableContext() {
604     return VTables.getMicrosoftVTableContext();
605   }
606
607   llvm::MDNode *getTBAAInfo(QualType QTy);
608   llvm::MDNode *getTBAAInfoForVTablePtr();
609   llvm::MDNode *getTBAAStructInfo(QualType QTy);
610   /// Return the MDNode in the type DAG for the given struct type.
611   llvm::MDNode *getTBAAStructTypeInfo(QualType QTy);
612   /// Return the path-aware tag for given base type, access node and offset.
613   llvm::MDNode *getTBAAStructTagInfo(QualType BaseTy, llvm::MDNode *AccessN,
614                                      uint64_t O);
615
616   bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor);
617
618   bool isPaddedAtomicType(QualType type);
619   bool isPaddedAtomicType(const AtomicType *type);
620
621   /// Decorate the instruction with a TBAA tag. For scalar TBAA, the tag
622   /// is the same as the type. For struct-path aware TBAA, the tag
623   /// is different from the type: base type, access type and offset.
624   /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
625   void DecorateInstruction(llvm::Instruction *Inst,
626                            llvm::MDNode *TBAAInfo,
627                            bool ConvertTypeToTag = true);
628
629   /// Emit the given number of characters as a value of type size_t.
630   llvm::ConstantInt *getSize(CharUnits numChars);
631
632   /// Set the visibility for the given LLVM GlobalValue.
633   void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const;
634
635   /// Set the TLS mode for the given LLVM GlobalVariable for the thread-local
636   /// variable declaration D.
637   void setTLSMode(llvm::GlobalVariable *GV, const VarDecl &D) const;
638
639   static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
640     switch (V) {
641     case DefaultVisibility:   return llvm::GlobalValue::DefaultVisibility;
642     case HiddenVisibility:    return llvm::GlobalValue::HiddenVisibility;
643     case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
644     }
645     llvm_unreachable("unknown visibility!");
646   }
647
648   llvm::Constant *GetAddrOfGlobal(GlobalDecl GD) {
649     if (isa<CXXConstructorDecl>(GD.getDecl()))
650       return GetAddrOfCXXConstructor(cast<CXXConstructorDecl>(GD.getDecl()),
651                                      GD.getCtorType());
652     else if (isa<CXXDestructorDecl>(GD.getDecl()))
653       return GetAddrOfCXXDestructor(cast<CXXDestructorDecl>(GD.getDecl()),
654                                      GD.getDtorType());
655     else if (isa<FunctionDecl>(GD.getDecl()))
656       return GetAddrOfFunction(GD);
657     else
658       return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl()));
659   }
660
661   /// Will return a global variable of the given type. If a variable with a
662   /// different type already exists then a new  variable with the right type
663   /// will be created and all uses of the old variable will be replaced with a
664   /// bitcast to the new variable.
665   llvm::GlobalVariable *
666   CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty,
667                                     llvm::GlobalValue::LinkageTypes Linkage);
668
669   /// Return the address space of the underlying global variable for D, as
670   /// determined by its declaration. Normally this is the same as the address
671   /// space of D's type, but in CUDA, address spaces are associated with
672   /// declarations, not types.
673   unsigned GetGlobalVarAddressSpace(const VarDecl *D, unsigned AddrSpace);
674
675   /// Return the llvm::Constant for the address of the given global variable.
676   /// If Ty is non-null and if the global doesn't exist, then it will be greated
677   /// with the specified type instead of whatever the normal requested type
678   /// would be.
679   llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
680                                      llvm::Type *Ty = nullptr);
681
682   /// Return the address of the given function. If Ty is non-null, then this
683   /// function will use the specified type if it has to create it.
684   llvm::Constant *GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty = 0,
685                                     bool ForVTable = false,
686                                     bool DontDefer = false);
687
688   /// Get the address of the RTTI descriptor for the given type.
689   llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
690
691   /// Get the address of a uuid descriptor .
692   llvm::Constant *GetAddrOfUuidDescriptor(const CXXUuidofExpr* E);
693
694   /// Get the address of the thunk for the given global decl.
695   llvm::Constant *GetAddrOfThunk(GlobalDecl GD, const ThunkInfo &Thunk);
696
697   /// Get a reference to the target of VD.
698   llvm::Constant *GetWeakRefReference(const ValueDecl *VD);
699
700   /// Returns the offset from a derived class to  a class. Returns null if the
701   /// offset is 0.
702   llvm::Constant *
703   GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
704                                CastExpr::path_const_iterator PathBegin,
705                                CastExpr::path_const_iterator PathEnd);
706
707   /// A pair of helper functions for a __block variable.
708   class ByrefHelpers : public llvm::FoldingSetNode {
709   public:
710     llvm::Constant *CopyHelper;
711     llvm::Constant *DisposeHelper;
712
713     /// The alignment of the field.  This is important because
714     /// different offsets to the field within the byref struct need to
715     /// have different helper functions.
716     CharUnits Alignment;
717
718     ByrefHelpers(CharUnits alignment) : Alignment(alignment) {}
719     virtual ~ByrefHelpers();
720
721     void Profile(llvm::FoldingSetNodeID &id) const {
722       id.AddInteger(Alignment.getQuantity());
723       profileImpl(id);
724     }
725     virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0;
726
727     virtual bool needsCopy() const { return true; }
728     virtual void emitCopy(CodeGenFunction &CGF,
729                           llvm::Value *dest, llvm::Value *src) = 0;
730
731     virtual bool needsDispose() const { return true; }
732     virtual void emitDispose(CodeGenFunction &CGF, llvm::Value *field) = 0;
733   };
734
735   llvm::FoldingSet<ByrefHelpers> ByrefHelpersCache;
736
737   /// Fetches the global unique block count.
738   int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; }
739   
740   /// Fetches the type of a generic block descriptor.
741   llvm::Type *getBlockDescriptorType();
742
743   /// The type of a generic block literal.
744   llvm::Type *getGenericBlockLiteralType();
745
746   /// Gets the address of a block which requires no captures.
747   llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, const char *);
748   
749   /// Return a pointer to a constant CFString object for the given string.
750   llvm::Constant *GetAddrOfConstantCFString(const StringLiteral *Literal);
751
752   /// Return a pointer to a constant NSString object for the given string. Or a
753   /// user defined String object as defined via
754   /// -fconstant-string-class=class_name option.
755   llvm::Constant *GetAddrOfConstantString(const StringLiteral *Literal);
756
757   /// Return a constant array for the given string.
758   llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E);
759
760   /// Return a pointer to a constant array for the given string literal.
761   llvm::GlobalVariable *
762   GetAddrOfConstantStringFromLiteral(const StringLiteral *S);
763
764   /// Return a pointer to a constant array for the given ObjCEncodeExpr node.
765   llvm::GlobalVariable *
766   GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
767
768   /// Returns a pointer to a character array containing the literal and a
769   /// terminating '\0' character. The result has pointer to array type.
770   ///
771   /// \param GlobalName If provided, the name to use for the global (if one is
772   /// created).
773   llvm::GlobalVariable *
774   GetAddrOfConstantCString(const std::string &Str,
775                            const char *GlobalName = nullptr,
776                            unsigned Alignment = 0);
777
778   /// Returns a pointer to a constant global variable for the given file-scope
779   /// compound literal expression.
780   llvm::Constant *GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E);
781
782   /// \brief Returns a pointer to a global variable representing a temporary
783   /// with static or thread storage duration.
784   llvm::Constant *GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E,
785                                            const Expr *Inner);
786
787   /// \brief Retrieve the record type that describes the state of an
788   /// Objective-C fast enumeration loop (for..in).
789   QualType getObjCFastEnumerationStateType();
790   
791   /// Return the address of the constructor of the given type.
792   llvm::GlobalValue *
793   GetAddrOfCXXConstructor(const CXXConstructorDecl *ctor, CXXCtorType ctorType,
794                           const CGFunctionInfo *fnInfo = nullptr,
795                           bool DontDefer = false);
796
797   /// Return the address of the constructor of the given type.
798   llvm::GlobalValue *
799   GetAddrOfCXXDestructor(const CXXDestructorDecl *dtor,
800                          CXXDtorType dtorType,
801                          const CGFunctionInfo *fnInfo = nullptr,
802                          llvm::FunctionType *fnType = nullptr,
803                          bool DontDefer = false);
804
805   /// Given a builtin id for a function like "__builtin_fabsf", return a
806   /// Function* for "fabsf".
807   llvm::Value *getBuiltinLibFunction(const FunctionDecl *FD,
808                                      unsigned BuiltinID);
809
810   llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys = None);
811
812   /// Emit code for a single top level declaration.
813   void EmitTopLevelDecl(Decl *D);
814
815   /// Tell the consumer that this variable has been instantiated.
816   void HandleCXXStaticMemberVarInstantiation(VarDecl *VD);
817
818   /// \brief If the declaration has internal linkage but is inside an
819   /// extern "C" linkage specification, prepare to emit an alias for it
820   /// to the expected name.
821   template<typename SomeDecl>
822   void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV);
823
824   /// Add a global to a list to be added to the llvm.used metadata.
825   void addUsedGlobal(llvm::GlobalValue *GV);
826
827   /// Add a global to a list to be added to the llvm.compiler.used metadata.
828   void addCompilerUsedGlobal(llvm::GlobalValue *GV);
829
830   /// Add a destructor and object to add to the C++ global destructor function.
831   void AddCXXDtorEntry(llvm::Constant *DtorFn, llvm::Constant *Object) {
832     CXXGlobalDtors.push_back(std::make_pair(DtorFn, Object));
833   }
834
835   /// Create a new runtime function with the specified type and name.
836   llvm::Constant *CreateRuntimeFunction(llvm::FunctionType *Ty,
837                                         StringRef Name,
838                                         llvm::AttributeSet ExtraAttrs =
839                                           llvm::AttributeSet());
840   /// Create a new runtime global variable with the specified type and name.
841   llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty,
842                                         StringRef Name);
843
844   ///@name Custom Blocks Runtime Interfaces
845   ///@{
846
847   llvm::Constant *getNSConcreteGlobalBlock();
848   llvm::Constant *getNSConcreteStackBlock();
849   llvm::Constant *getBlockObjectAssign();
850   llvm::Constant *getBlockObjectDispose();
851
852   ///@}
853
854   llvm::Constant *getLLVMLifetimeStartFn();
855   llvm::Constant *getLLVMLifetimeEndFn();
856
857   // Make sure that this type is translated.
858   void UpdateCompletedType(const TagDecl *TD);
859
860   llvm::Constant *getMemberPointerConstant(const UnaryOperator *e);
861
862   /// Try to emit the initializer for the given declaration as a constant;
863   /// returns 0 if the expression cannot be emitted as a constant.
864   llvm::Constant *EmitConstantInit(const VarDecl &D,
865                                    CodeGenFunction *CGF = nullptr);
866
867   /// Try to emit the given expression as a constant; returns 0 if the
868   /// expression cannot be emitted as a constant.
869   llvm::Constant *EmitConstantExpr(const Expr *E, QualType DestType,
870                                    CodeGenFunction *CGF = nullptr);
871
872   /// Emit the given constant value as a constant, in the type's scalar
873   /// representation.
874   llvm::Constant *EmitConstantValue(const APValue &Value, QualType DestType,
875                                     CodeGenFunction *CGF = nullptr);
876
877   /// Emit the given constant value as a constant, in the type's memory
878   /// representation.
879   llvm::Constant *EmitConstantValueForMemory(const APValue &Value,
880                                              QualType DestType,
881                                              CodeGenFunction *CGF = nullptr);
882
883   /// Return the result of value-initializing the given type, i.e. a null
884   /// expression of the given type.  This is usually, but not always, an LLVM
885   /// null constant.
886   llvm::Constant *EmitNullConstant(QualType T);
887
888   /// Return a null constant appropriate for zero-initializing a base class with
889   /// the given type. This is usually, but not always, an LLVM null constant.
890   llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record);
891
892   /// Emit a general error that something can't be done.
893   void Error(SourceLocation loc, StringRef error);
894
895   /// Print out an error that codegen doesn't support the specified stmt yet.
896   void ErrorUnsupported(const Stmt *S, const char *Type);
897
898   /// Print out an error that codegen doesn't support the specified decl yet.
899   void ErrorUnsupported(const Decl *D, const char *Type);
900
901   /// Set the attributes on the LLVM function for the given decl and function
902   /// info. This applies attributes necessary for handling the ABI as well as
903   /// user specified attributes like section.
904   void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F,
905                                      const CGFunctionInfo &FI);
906
907   /// Set the LLVM function attributes (sext, zext, etc).
908   void SetLLVMFunctionAttributes(const Decl *D,
909                                  const CGFunctionInfo &Info,
910                                  llvm::Function *F);
911
912   /// Set the LLVM function attributes which only apply to a function
913   /// definintion.
914   void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
915
916   /// Return true iff the given type uses 'sret' when used as a return type.
917   bool ReturnTypeUsesSRet(const CGFunctionInfo &FI);
918
919   /// Return true iff the given type uses an argument slot when 'sret' is used
920   /// as a return type.
921   bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI);
922
923   /// Return true iff the given type uses 'fpret' when used as a return type.
924   bool ReturnTypeUsesFPRet(QualType ResultType);
925
926   /// Return true iff the given type uses 'fp2ret' when used as a return type.
927   bool ReturnTypeUsesFP2Ret(QualType ResultType);
928
929   /// Get the LLVM attributes and calling convention to use for a particular
930   /// function type.
931   ///
932   /// \param Info - The function type information.
933   /// \param TargetDecl - The decl these attributes are being constructed
934   /// for. If supplied the attributes applied to this decl may contribute to the
935   /// function attributes and calling convention.
936   /// \param PAL [out] - On return, the attribute list to use.
937   /// \param CallingConv [out] - On return, the LLVM calling convention to use.
938   void ConstructAttributeList(const CGFunctionInfo &Info,
939                               const Decl *TargetDecl,
940                               AttributeListType &PAL,
941                               unsigned &CallingConv,
942                               bool AttrOnCallSite);
943
944   StringRef getMangledName(GlobalDecl GD);
945   StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD);
946
947   void EmitTentativeDefinition(const VarDecl *D);
948
949   void EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired);
950
951   /// Emit the RTTI descriptors for the builtin types.
952   void EmitFundamentalRTTIDescriptors();
953
954   /// \brief Appends Opts to the "Linker Options" metadata value.
955   void AppendLinkerOptions(StringRef Opts);
956
957   /// \brief Appends a detect mismatch command to the linker options.
958   void AddDetectMismatch(StringRef Name, StringRef Value);
959
960   /// \brief Appends a dependent lib to the "Linker Options" metadata value.
961   void AddDependentLib(StringRef Lib);
962
963   llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD);
964
965   void setFunctionLinkage(GlobalDecl GD, llvm::Function *F) {
966     F->setLinkage(getFunctionLinkage(GD));
967   }
968
969   /// Return the appropriate linkage for the vtable, VTT, and type information
970   /// of the given class.
971   llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD);
972
973   /// Return the store size, in character units, of the given LLVM type.
974   CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const;
975   
976   /// Returns LLVM linkage for a declarator.
977   llvm::GlobalValue::LinkageTypes
978   getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage,
979                               bool IsConstantVariable);
980
981   /// Returns LLVM linkage for a declarator.
982   llvm::GlobalValue::LinkageTypes
983   getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant);
984
985   /// Emit all the global annotations.
986   void EmitGlobalAnnotations();
987
988   /// Emit an annotation string.
989   llvm::Constant *EmitAnnotationString(StringRef Str);
990
991   /// Emit the annotation's translation unit.
992   llvm::Constant *EmitAnnotationUnit(SourceLocation Loc);
993
994   /// Emit the annotation line number.
995   llvm::Constant *EmitAnnotationLineNo(SourceLocation L);
996
997   /// Generate the llvm::ConstantStruct which contains the annotation
998   /// information for a given GlobalValue. The annotation struct is
999   /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
1000   /// GlobalValue being annotated. The second field is the constant string
1001   /// created from the AnnotateAttr's annotation. The third field is a constant
1002   /// string containing the name of the translation unit. The fourth field is
1003   /// the line number in the file of the annotated value declaration.
1004   llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
1005                                    const AnnotateAttr *AA,
1006                                    SourceLocation L);
1007
1008   /// Add global annotations that are set on D, for the global GV. Those
1009   /// annotations are emitted during finalization of the LLVM code.
1010   void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV);
1011
1012   const SanitizerBlacklist &getSanitizerBlacklist() const {
1013     return SanitizerBL;
1014   }
1015
1016   void reportGlobalToASan(llvm::GlobalVariable *GV, const VarDecl &D,
1017                           bool IsDynInit = false);
1018   void reportGlobalToASan(llvm::GlobalVariable *GV, SourceLocation Loc,
1019                           StringRef Name, bool IsDynInit = false,
1020                           bool IsBlacklisted = false);
1021
1022   /// Disable sanitizer instrumentation for this global.
1023   void disableSanitizerForGlobal(llvm::GlobalVariable *GV);
1024
1025   void addDeferredVTable(const CXXRecordDecl *RD) {
1026     DeferredVTables.push_back(RD);
1027   }
1028
1029   /// Emit code for a singal global function or var decl. Forward declarations
1030   /// are emitted lazily.
1031   void EmitGlobal(GlobalDecl D);
1032
1033 private:
1034   llvm::GlobalValue *GetGlobalValue(StringRef Ref);
1035
1036   llvm::Constant *
1037   GetOrCreateLLVMFunction(StringRef MangledName, llvm::Type *Ty, GlobalDecl D,
1038                           bool ForVTable, bool DontDefer = false,
1039                           llvm::AttributeSet ExtraAttrs = llvm::AttributeSet());
1040
1041   llvm::Constant *GetOrCreateLLVMGlobal(StringRef MangledName,
1042                                         llvm::PointerType *PTy,
1043                                         const VarDecl *D);
1044
1045   /// Set attributes which are common to any form of a global definition (alias,
1046   /// Objective-C method, function, global variable).
1047   ///
1048   /// NOTE: This should only be called for definitions.
1049   void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV);
1050
1051   void setNonAliasAttributes(const Decl *D, llvm::GlobalObject *GO);
1052
1053   /// Set attributes for a global definition.
1054   void setFunctionDefinitionAttributes(const FunctionDecl *D,
1055                                        llvm::Function *F);
1056
1057   /// Set function attributes for a function declaration.
1058   void SetFunctionAttributes(GlobalDecl GD,
1059                              llvm::Function *F,
1060                              bool IsIncompleteFunction);
1061
1062   void EmitGlobalDefinition(GlobalDecl D, llvm::GlobalValue *GV = nullptr);
1063
1064   void EmitGlobalFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
1065   void EmitGlobalVarDefinition(const VarDecl *D);
1066   void EmitAliasDefinition(GlobalDecl GD);
1067   void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
1068   void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
1069   
1070   // C++ related functions.
1071
1072   bool TryEmitDefinitionAsAlias(GlobalDecl Alias, GlobalDecl Target,
1073                                 bool InEveryTU);
1074   bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D);
1075
1076   void EmitNamespace(const NamespaceDecl *D);
1077   void EmitLinkageSpec(const LinkageSpecDecl *D);
1078   void CompleteDIClassType(const CXXMethodDecl* D);
1079
1080   /// Emit a single constructor with the given type from a C++ constructor Decl.
1081   void EmitCXXConstructor(const CXXConstructorDecl *D, CXXCtorType Type);
1082
1083   /// Emit a single destructor with the given type from a C++ destructor Decl.
1084   void EmitCXXDestructor(const CXXDestructorDecl *D, CXXDtorType Type);
1085
1086   /// \brief Emit the function that initializes C++ thread_local variables.
1087   void EmitCXXThreadLocalInitFunc();
1088
1089   /// Emit the function that initializes C++ globals.
1090   void EmitCXXGlobalInitFunc();
1091
1092   /// Emit the function that destroys C++ globals.
1093   void EmitCXXGlobalDtorFunc();
1094
1095   /// Emit the function that initializes the specified global (if PerformInit is
1096   /// true) and registers its destructor.
1097   void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
1098                                     llvm::GlobalVariable *Addr,
1099                                     bool PerformInit);
1100
1101   void EmitPointerToInitFunc(const VarDecl *VD, llvm::GlobalVariable *Addr,
1102                              llvm::Function *InitFunc, InitSegAttr *ISA);
1103
1104   // FIXME: Hardcoding priority here is gross.
1105   void AddGlobalCtor(llvm::Function *Ctor, int Priority = 65535,
1106                      llvm::Constant *AssociatedData = 0);
1107   void AddGlobalDtor(llvm::Function *Dtor, int Priority = 65535);
1108
1109   /// Generates a global array of functions and priorities using the given list
1110   /// and name. This array will have appending linkage and is suitable for use
1111   /// as a LLVM constructor or destructor array.
1112   void EmitCtorList(const CtorList &Fns, const char *GlobalName);
1113
1114   /// Emit the RTTI descriptors for the given type.
1115   void EmitFundamentalRTTIDescriptor(QualType Type);
1116
1117   /// Emit any needed decls for which code generation was deferred.
1118   void EmitDeferred();
1119
1120   /// Call replaceAllUsesWith on all pairs in Replacements.
1121   void applyReplacements();
1122
1123   void checkAliases();
1124
1125   /// Emit any vtables which we deferred and still have a use for.
1126   void EmitDeferredVTables();
1127
1128   /// Emit the llvm.used and llvm.compiler.used metadata.
1129   void emitLLVMUsed();
1130
1131   /// \brief Emit the link options introduced by imported modules.
1132   void EmitModuleLinkOptions();
1133
1134   /// \brief Emit aliases for internal-linkage declarations inside "C" language
1135   /// linkage specifications, giving them the "expected" name where possible.
1136   void EmitStaticExternCAliases();
1137
1138   void EmitDeclMetadata();
1139
1140   /// \brief Emit the Clang version as llvm.ident metadata.
1141   void EmitVersionIdentMetadata();
1142
1143   /// Emits target specific Metadata for global declarations.
1144   void EmitTargetMetadata();
1145
1146   /// Emit the llvm.gcov metadata used to tell LLVM where to emit the .gcno and
1147   /// .gcda files in a way that persists in .bc files.
1148   void EmitCoverageFile();
1149
1150   /// Emits the initializer for a uuidof string.
1151   llvm::Constant *EmitUuidofInitializer(StringRef uuidstr, QualType IIDType);
1152
1153   /// Determine if the given decl can be emitted lazily; this is only relevant
1154   /// for definitions. The given decl must be either a function or var decl.
1155   bool MayDeferGeneration(const ValueDecl *D);
1156
1157   /// Check whether we can use a "simpler", more core exceptions personality
1158   /// function.
1159   void SimplifyPersonality();
1160 };
1161 }  // end namespace CodeGen
1162 }  // end namespace clang
1163
1164 #endif