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