CodeGenModule.h 34 KB

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