CodeGenModule.h 34 KB

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