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