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