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