CodeGenModule.h 37 KB

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