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