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