CodeGenModule.h 35 KB

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