CodeGenModule.h 36 KB

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