CodeGenModule.h 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273
  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 LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H
  14. #define LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H
  15. #include "CGVTables.h"
  16. #include "CodeGenTypes.h"
  17. #include "SanitizerMetadata.h"
  18. #include "clang/AST/Attr.h"
  19. #include "clang/AST/DeclCXX.h"
  20. #include "clang/AST/DeclObjC.h"
  21. #include "clang/AST/GlobalDecl.h"
  22. #include "clang/AST/Mangle.h"
  23. #include "clang/Basic/ABI.h"
  24. #include "clang/Basic/LangOptions.h"
  25. #include "clang/Basic/Module.h"
  26. #include "clang/Basic/SanitizerBlacklist.h"
  27. #include "llvm/ADT/DenseMap.h"
  28. #include "llvm/ADT/SetVector.h"
  29. #include "llvm/ADT/SmallPtrSet.h"
  30. #include "llvm/ADT/StringMap.h"
  31. #include "llvm/IR/CallingConv.h"
  32. #include "llvm/IR/Module.h"
  33. #include "llvm/IR/ValueHandle.h"
  34. namespace llvm {
  35. class Module;
  36. class Constant;
  37. class ConstantInt;
  38. class Function;
  39. class GlobalValue;
  40. class DataLayout;
  41. class FunctionType;
  42. class LLVMContext;
  43. class IndexedInstrProfReader;
  44. }
  45. namespace clang {
  46. class TargetCodeGenInfo;
  47. class ASTContext;
  48. class AtomicType;
  49. class FunctionDecl;
  50. class IdentifierInfo;
  51. class ObjCMethodDecl;
  52. class ObjCImplementationDecl;
  53. class ObjCCategoryImplDecl;
  54. class ObjCProtocolDecl;
  55. class ObjCEncodeExpr;
  56. class BlockExpr;
  57. class CharUnits;
  58. class Decl;
  59. class Expr;
  60. class Stmt;
  61. class InitListExpr;
  62. class StringLiteral;
  63. class NamedDecl;
  64. class ValueDecl;
  65. class VarDecl;
  66. class LangOptions;
  67. class CodeGenOptions;
  68. class HeaderSearchOptions;
  69. class PreprocessorOptions;
  70. class DiagnosticsEngine;
  71. class AnnotateAttr;
  72. class CXXDestructorDecl;
  73. class Module;
  74. class CoverageSourceInfo;
  75. namespace CodeGen {
  76. class CallArgList;
  77. class CodeGenFunction;
  78. class CodeGenTBAA;
  79. class CGCXXABI;
  80. class CGDebugInfo;
  81. class CGObjCRuntime;
  82. class CGOpenCLRuntime;
  83. class CGOpenMPRuntime;
  84. class CGCUDARuntime;
  85. class CGHLSLRuntime; // HLSL Change
  86. class BlockFieldFlags;
  87. class FunctionArgList;
  88. class CoverageMappingModuleGen;
  89. struct OrderGlobalInits {
  90. unsigned int priority;
  91. unsigned int lex_order;
  92. OrderGlobalInits(unsigned int p, unsigned int l)
  93. : priority(p), lex_order(l) {}
  94. bool operator==(const OrderGlobalInits &RHS) const {
  95. return priority == RHS.priority && lex_order == RHS.lex_order;
  96. }
  97. bool operator<(const OrderGlobalInits &RHS) const {
  98. return std::tie(priority, lex_order) <
  99. std::tie(RHS.priority, RHS.lex_order);
  100. }
  101. };
  102. struct CodeGenTypeCache {
  103. /// void
  104. llvm::Type *VoidTy;
  105. /// i8, i16, i32, and i64
  106. llvm::IntegerType *Int8Ty, *Int16Ty, *Int32Ty, *Int64Ty;
  107. /// float, double
  108. llvm::Type *FloatTy, *DoubleTy;
  109. /// int
  110. llvm::IntegerType *IntTy;
  111. /// intptr_t, size_t, and ptrdiff_t, which we assume are the same size.
  112. union {
  113. llvm::IntegerType *IntPtrTy;
  114. llvm::IntegerType *SizeTy;
  115. llvm::IntegerType *PtrDiffTy;
  116. };
  117. /// void* in address space 0
  118. union {
  119. llvm::PointerType *VoidPtrTy;
  120. llvm::PointerType *Int8PtrTy;
  121. };
  122. /// void** in address space 0
  123. union {
  124. llvm::PointerType *VoidPtrPtrTy;
  125. llvm::PointerType *Int8PtrPtrTy;
  126. };
  127. /// The width of a pointer into the generic address space.
  128. unsigned char PointerWidthInBits;
  129. /// The size and alignment of a pointer into the generic address
  130. /// space.
  131. union {
  132. unsigned char PointerAlignInBytes;
  133. unsigned char PointerSizeInBytes;
  134. unsigned char SizeSizeInBytes; // sizeof(size_t)
  135. };
  136. llvm::CallingConv::ID RuntimeCC;
  137. llvm::CallingConv::ID getRuntimeCC() const { return RuntimeCC; }
  138. llvm::CallingConv::ID BuiltinCC;
  139. llvm::CallingConv::ID getBuiltinCC() const { return BuiltinCC; }
  140. };
  141. struct RREntrypoints {
  142. RREntrypoints() { memset(this, 0, sizeof(*this)); }
  143. /// void objc_autoreleasePoolPop(void*);
  144. llvm::Constant *objc_autoreleasePoolPop;
  145. /// void *objc_autoreleasePoolPush(void);
  146. llvm::Constant *objc_autoreleasePoolPush;
  147. };
  148. struct ARCEntrypoints {
  149. ARCEntrypoints() { memset(this, 0, sizeof(*this)); }
  150. /// id objc_autorelease(id);
  151. llvm::Constant *objc_autorelease;
  152. /// id objc_autoreleaseReturnValue(id);
  153. llvm::Constant *objc_autoreleaseReturnValue;
  154. /// void objc_copyWeak(id *dest, id *src);
  155. llvm::Constant *objc_copyWeak;
  156. /// void objc_destroyWeak(id*);
  157. llvm::Constant *objc_destroyWeak;
  158. /// id objc_initWeak(id*, id);
  159. llvm::Constant *objc_initWeak;
  160. /// id objc_loadWeak(id*);
  161. llvm::Constant *objc_loadWeak;
  162. /// id objc_loadWeakRetained(id*);
  163. llvm::Constant *objc_loadWeakRetained;
  164. /// void objc_moveWeak(id *dest, id *src);
  165. llvm::Constant *objc_moveWeak;
  166. /// id objc_retain(id);
  167. llvm::Constant *objc_retain;
  168. /// id objc_retainAutorelease(id);
  169. llvm::Constant *objc_retainAutorelease;
  170. /// id objc_retainAutoreleaseReturnValue(id);
  171. llvm::Constant *objc_retainAutoreleaseReturnValue;
  172. /// id objc_retainAutoreleasedReturnValue(id);
  173. llvm::Constant *objc_retainAutoreleasedReturnValue;
  174. /// id objc_retainBlock(id);
  175. llvm::Constant *objc_retainBlock;
  176. /// void objc_release(id);
  177. llvm::Constant *objc_release;
  178. /// id objc_storeStrong(id*, id);
  179. llvm::Constant *objc_storeStrong;
  180. /// id objc_storeWeak(id*, id);
  181. llvm::Constant *objc_storeWeak;
  182. /// A void(void) inline asm to use to mark that the return value of
  183. /// a call will be immediately retain.
  184. llvm::InlineAsm *retainAutoreleasedReturnValueMarker;
  185. /// void clang.arc.use(...);
  186. llvm::Constant *clang_arc_use;
  187. };
  188. /// This class records statistics on instrumentation based profiling.
  189. class InstrProfStats {
  190. uint32_t VisitedInMainFile;
  191. uint32_t MissingInMainFile;
  192. uint32_t Visited;
  193. uint32_t Missing;
  194. uint32_t Mismatched;
  195. public:
  196. InstrProfStats()
  197. : VisitedInMainFile(0), MissingInMainFile(0), Visited(0), Missing(0),
  198. Mismatched(0) {}
  199. /// Record that we've visited a function and whether or not that function was
  200. /// in the main source file.
  201. void addVisited(bool MainFile) {
  202. if (MainFile)
  203. ++VisitedInMainFile;
  204. ++Visited;
  205. }
  206. /// Record that a function we've visited has no profile data.
  207. void addMissing(bool MainFile) {
  208. if (MainFile)
  209. ++MissingInMainFile;
  210. ++Missing;
  211. }
  212. /// Record that a function we've visited has mismatched profile data.
  213. void addMismatched(bool MainFile) { ++Mismatched; }
  214. /// Whether or not the stats we've gathered indicate any potential problems.
  215. bool hasDiagnostics() { return Missing || Mismatched; }
  216. /// Report potential problems we've found to \c Diags.
  217. void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile);
  218. };
  219. /// This class organizes the cross-function state that is used while generating
  220. /// LLVM code.
  221. class CodeGenModule : public CodeGenTypeCache {
  222. CodeGenModule(const CodeGenModule &) = delete;
  223. void operator=(const CodeGenModule &) = delete;
  224. public:
  225. struct Structor {
  226. Structor() : Priority(0), Initializer(nullptr), AssociatedData(nullptr) {}
  227. Structor(int Priority, llvm::Constant *Initializer,
  228. llvm::Constant *AssociatedData)
  229. : Priority(Priority), Initializer(Initializer),
  230. AssociatedData(AssociatedData) {}
  231. int Priority;
  232. llvm::Constant *Initializer;
  233. llvm::Constant *AssociatedData;
  234. };
  235. typedef std::vector<Structor> CtorList;
  236. private:
  237. ASTContext &Context;
  238. const LangOptions &LangOpts;
  239. const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
  240. const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
  241. const CodeGenOptions &CodeGenOpts;
  242. llvm::Module &TheModule;
  243. DiagnosticsEngine &Diags;
  244. const llvm::DataLayout &TheDataLayout;
  245. const TargetInfo &Target;
  246. std::unique_ptr<CGCXXABI> ABI;
  247. llvm::LLVMContext &VMContext;
  248. CodeGenTBAA *TBAA;
  249. mutable std::unique_ptr<TargetCodeGenInfo> TheTargetCodeGenInfo; // HLSL Change - unique_ptr rather than const *
  250. // This should not be moved earlier, since its initialization depends on some
  251. // of the previous reference members being already initialized and also checks
  252. // if TheTargetCodeGenInfo is NULL
  253. CodeGenTypes Types;
  254. /// Holds information about C++ vtables.
  255. CodeGenVTables VTables;
  256. CGObjCRuntime* ObjCRuntime;
  257. CGOpenCLRuntime* OpenCLRuntime;
  258. CGOpenMPRuntime* OpenMPRuntime;
  259. CGCUDARuntime* CUDARuntime;
  260. CGHLSLRuntime* HLSLRuntime; // HLSL Change
  261. CGDebugInfo* DebugInfo;
  262. ARCEntrypoints *ARCData;
  263. llvm::MDNode *NoObjCARCExceptionsMetadata;
  264. RREntrypoints *RRData;
  265. std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader;
  266. InstrProfStats PGOStats;
  267. // A set of references that have only been seen via a weakref so far. This is
  268. // used to remove the weak of the reference if we ever see a direct reference
  269. // or a definition.
  270. llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences;
  271. /// This contains all the decls which have definitions but/ which are deferred
  272. /// for emission and therefore should only be output if they are actually
  273. /// used. If a decl is in this, then it is known to have not been referenced
  274. /// yet.
  275. std::map<StringRef, GlobalDecl> DeferredDecls;
  276. /// This is a list of deferred decls which we have seen that *are* actually
  277. /// referenced. These get code generated when the module is done.
  278. struct DeferredGlobal {
  279. DeferredGlobal(llvm::GlobalValue *GV, GlobalDecl GD) : GV(GV), GD(GD) {}
  280. llvm::TrackingVH<llvm::GlobalValue> GV;
  281. GlobalDecl GD;
  282. };
  283. std::vector<DeferredGlobal> DeferredDeclsToEmit;
  284. void addDeferredDeclToEmit(llvm::GlobalValue *GV, GlobalDecl GD) {
  285. DeferredDeclsToEmit.emplace_back(GV, GD);
  286. }
  287. /// List of alias we have emitted. Used to make sure that what they point to
  288. /// is defined once we get to the end of the of the translation unit.
  289. std::vector<GlobalDecl> Aliases;
  290. typedef llvm::StringMap<llvm::TrackingVH<llvm::Constant> > ReplacementsTy;
  291. ReplacementsTy Replacements;
  292. /// A queue of (optional) vtables to consider emitting.
  293. std::vector<const CXXRecordDecl*> DeferredVTables;
  294. /// List of global values which are required to be present in the object file;
  295. /// bitcast to i8*. This is used for forcing visibility of symbols which may
  296. /// otherwise be optimized out.
  297. std::vector<llvm::WeakVH> LLVMUsed;
  298. std::vector<llvm::WeakVH> LLVMCompilerUsed;
  299. /// Store the list of global constructors and their respective priorities to
  300. /// be emitted when the translation unit is complete.
  301. CtorList GlobalCtors;
  302. /// Store the list of global destructors and their respective priorities to be
  303. /// emitted when the translation unit is complete.
  304. CtorList GlobalDtors;
  305. /// An ordered map of canonical GlobalDecls to their mangled names.
  306. llvm::MapVector<GlobalDecl, StringRef> MangledDeclNames;
  307. llvm::StringMap<GlobalDecl, llvm::BumpPtrAllocator> Manglings;
  308. /// Global annotations.
  309. std::vector<llvm::Constant*> Annotations;
  310. /// Map used to get unique annotation strings.
  311. llvm::StringMap<llvm::Constant*> AnnotationStrings;
  312. llvm::StringMap<llvm::GlobalVariable *> CFConstantStringMap;
  313. llvm::DenseMap<llvm::Constant *, llvm::GlobalVariable *> ConstantStringMap;
  314. llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap;
  315. llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardMap;
  316. llvm::DenseMap<const Expr*, llvm::Constant *> MaterializedGlobalTemporaryMap;
  317. llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap;
  318. llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap;
  319. /// Map used to get unique type descriptor constants for sanitizers.
  320. llvm::DenseMap<QualType, llvm::Constant *> TypeDescriptorMap;
  321. /// Map used to track internal linkage functions declared within
  322. /// extern "C" regions.
  323. typedef llvm::MapVector<IdentifierInfo *,
  324. llvm::GlobalValue *> StaticExternCMap;
  325. StaticExternCMap StaticExternCValues;
  326. /// \brief thread_local variables defined or used in this TU.
  327. std::vector<std::pair<const VarDecl *, llvm::GlobalVariable *> >
  328. CXXThreadLocals;
  329. /// \brief thread_local variables with initializers that need to run
  330. /// before any thread_local variable in this TU is odr-used.
  331. std::vector<llvm::Function *> CXXThreadLocalInits;
  332. std::vector<llvm::GlobalVariable *> CXXThreadLocalInitVars;
  333. /// Global variables with initializers that need to run before main.
  334. std::vector<llvm::Function *> CXXGlobalInits;
  335. /// When a C++ decl with an initializer is deferred, null is
  336. /// appended to CXXGlobalInits, and the index of that null is placed
  337. /// here so that the initializer will be performed in the correct
  338. /// order. Once the decl is emitted, the index is replaced with ~0U to ensure
  339. /// that we don't re-emit the initializer.
  340. llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition;
  341. typedef std::pair<OrderGlobalInits, llvm::Function*> GlobalInitData;
  342. struct GlobalInitPriorityCmp {
  343. bool operator()(const GlobalInitData &LHS,
  344. const GlobalInitData &RHS) const {
  345. return LHS.first.priority < RHS.first.priority;
  346. }
  347. };
  348. /// Global variables with initializers whose order of initialization is set by
  349. /// init_priority attribute.
  350. SmallVector<GlobalInitData, 8> PrioritizedCXXGlobalInits;
  351. /// Global destructor functions and arguments that need to run on termination.
  352. std::vector<std::pair<llvm::WeakVH,llvm::Constant*> > CXXGlobalDtors;
  353. /// \brief The complete set of modules that has been imported.
  354. llvm::SetVector<clang::Module *> ImportedModules;
  355. /// \brief A vector of metadata strings.
  356. SmallVector<llvm::Metadata *, 16> LinkerOptionsMetadata;
  357. /// @name Cache for Objective-C runtime types
  358. /// @{
  359. /// Cached reference to the class for constant strings. This value has type
  360. /// int * but is actually an Obj-C class pointer.
  361. llvm::WeakVH CFConstantStringClassRef;
  362. /// Cached reference to the class for constant strings. This value has type
  363. /// int * but is actually an Obj-C class pointer.
  364. llvm::WeakVH ConstantStringClassRef;
  365. /// \brief The LLVM type corresponding to NSConstantString.
  366. llvm::StructType *NSConstantStringType;
  367. /// \brief The type used to describe the state of a fast enumeration in
  368. /// Objective-C's for..in loop.
  369. QualType ObjCFastEnumerationStateType;
  370. /// @}
  371. /// Lazily create the Objective-C runtime
  372. void createObjCRuntime();
  373. void createOpenCLRuntime();
  374. void createOpenMPRuntime();
  375. void createCUDARuntime();
  376. void createHLSLRuntime(); // HLSL Change
  377. bool isTriviallyRecursive(const FunctionDecl *F);
  378. bool shouldEmitFunction(GlobalDecl GD);
  379. /// @name Cache for Blocks Runtime Globals
  380. /// @{
  381. llvm::Constant *NSConcreteGlobalBlock;
  382. llvm::Constant *NSConcreteStackBlock;
  383. llvm::Constant *BlockObjectAssign;
  384. llvm::Constant *BlockObjectDispose;
  385. llvm::Type *BlockDescriptorType;
  386. llvm::Type *GenericBlockLiteralType;
  387. struct {
  388. int GlobalUniqueCount;
  389. } Block;
  390. /// void @llvm.lifetime.start(i64 %size, i8* nocapture <ptr>)
  391. llvm::Constant *LifetimeStartFn;
  392. /// void @llvm.lifetime.end(i64 %size, i8* nocapture <ptr>)
  393. llvm::Constant *LifetimeEndFn;
  394. GlobalDecl initializedGlobalDecl;
  395. std::unique_ptr<SanitizerMetadata> SanitizerMD;
  396. /// @}
  397. llvm::DenseMap<const Decl *, bool> DeferredEmptyCoverageMappingDecls;
  398. std::unique_ptr<CoverageMappingModuleGen> CoverageMapping;
  399. public:
  400. CodeGenModule(ASTContext &C,
  401. const HeaderSearchOptions &headersearchopts,
  402. const PreprocessorOptions &ppopts,
  403. const CodeGenOptions &CodeGenOpts,
  404. llvm::Module &M, const llvm::DataLayout &TD,
  405. DiagnosticsEngine &Diags,
  406. CoverageSourceInfo *CoverageInfo = nullptr);
  407. ~CodeGenModule();
  408. void clear();
  409. /// Finalize LLVM code generation.
  410. void Release();
  411. /// Return a reference to the configured Objective-C runtime.
  412. CGObjCRuntime &getObjCRuntime() {
  413. if (!ObjCRuntime) createObjCRuntime();
  414. return *ObjCRuntime;
  415. }
  416. /// Return true iff an Objective-C runtime has been configured.
  417. bool hasObjCRuntime() { return !!ObjCRuntime; }
  418. /// Return a reference to the configured OpenCL runtime.
  419. CGOpenCLRuntime &getOpenCLRuntime() {
  420. assert(OpenCLRuntime != nullptr);
  421. return *OpenCLRuntime;
  422. }
  423. /// Return a reference to the configured OpenMP runtime.
  424. CGOpenMPRuntime &getOpenMPRuntime() {
  425. assert(OpenMPRuntime != nullptr);
  426. return *OpenMPRuntime;
  427. }
  428. /// Return a reference to the configured CUDA runtime.
  429. CGCUDARuntime &getCUDARuntime() {
  430. assert(CUDARuntime != nullptr);
  431. return *CUDARuntime;
  432. }
  433. // HLSL Change Starts
  434. /// Return a reference to the configured HLSL runtime.
  435. CGHLSLRuntime &getHLSLRuntime() {
  436. assert(HLSLRuntime != nullptr);
  437. return *HLSLRuntime;
  438. }
  439. void FinishCodeGen();
  440. // HLSL Change Ends
  441. ARCEntrypoints &getARCEntrypoints() const {
  442. assert(getLangOpts().ObjCAutoRefCount && ARCData != nullptr);
  443. return *ARCData;
  444. }
  445. RREntrypoints &getRREntrypoints() const {
  446. assert(RRData != nullptr);
  447. return *RRData;
  448. }
  449. InstrProfStats &getPGOStats() { return PGOStats; }
  450. llvm::IndexedInstrProfReader *getPGOReader() const { return PGOReader.get(); }
  451. CoverageMappingModuleGen *getCoverageMapping() const {
  452. return CoverageMapping.get();
  453. }
  454. llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) {
  455. return StaticLocalDeclMap[D];
  456. }
  457. void setStaticLocalDeclAddress(const VarDecl *D,
  458. llvm::Constant *C) {
  459. StaticLocalDeclMap[D] = C;
  460. }
  461. llvm::Constant *
  462. getOrCreateStaticVarDecl(const VarDecl &D,
  463. llvm::GlobalValue::LinkageTypes Linkage);
  464. llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) {
  465. return StaticLocalDeclGuardMap[D];
  466. }
  467. void setStaticLocalDeclGuardAddress(const VarDecl *D,
  468. llvm::GlobalVariable *C) {
  469. StaticLocalDeclGuardMap[D] = C;
  470. }
  471. bool lookupRepresentativeDecl(StringRef MangledName,
  472. GlobalDecl &Result) const;
  473. llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) {
  474. return AtomicSetterHelperFnMap[Ty];
  475. }
  476. void setAtomicSetterHelperFnMap(QualType Ty,
  477. llvm::Constant *Fn) {
  478. AtomicSetterHelperFnMap[Ty] = Fn;
  479. }
  480. llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) {
  481. return AtomicGetterHelperFnMap[Ty];
  482. }
  483. void setAtomicGetterHelperFnMap(QualType Ty,
  484. llvm::Constant *Fn) {
  485. AtomicGetterHelperFnMap[Ty] = Fn;
  486. }
  487. llvm::Constant *getTypeDescriptorFromMap(QualType Ty) {
  488. return TypeDescriptorMap[Ty];
  489. }
  490. void setTypeDescriptorInMap(QualType Ty, llvm::Constant *C) {
  491. TypeDescriptorMap[Ty] = C;
  492. }
  493. CGDebugInfo *getModuleDebugInfo() { return DebugInfo; }
  494. llvm::MDNode *getNoObjCARCExceptionsMetadata() {
  495. if (!NoObjCARCExceptionsMetadata)
  496. NoObjCARCExceptionsMetadata = llvm::MDNode::get(getLLVMContext(), None);
  497. return NoObjCARCExceptionsMetadata;
  498. }
  499. ASTContext &getContext() const { return Context; }
  500. const LangOptions &getLangOpts() const { return LangOpts; }
  501. const HeaderSearchOptions &getHeaderSearchOpts()
  502. const { return HeaderSearchOpts; }
  503. const PreprocessorOptions &getPreprocessorOpts()
  504. const { return PreprocessorOpts; }
  505. const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
  506. llvm::Module &getModule() const { return TheModule; }
  507. DiagnosticsEngine &getDiags() const { return Diags; }
  508. const llvm::DataLayout &getDataLayout() const { return TheDataLayout; }
  509. const TargetInfo &getTarget() const { return Target; }
  510. const llvm::Triple &getTriple() const;
  511. bool supportsCOMDAT() const;
  512. void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO);
  513. CGCXXABI &getCXXABI() const { return *ABI; }
  514. llvm::LLVMContext &getLLVMContext() { return VMContext; }
  515. bool shouldUseTBAA() const { return TBAA != nullptr; }
  516. const TargetCodeGenInfo &getTargetCodeGenInfo();
  517. CodeGenTypes &getTypes() { return Types; }
  518. CodeGenVTables &getVTables() { return VTables; }
  519. ItaniumVTableContext &getItaniumVTableContext() {
  520. return VTables.getItaniumVTableContext();
  521. }
  522. MicrosoftVTableContext &getMicrosoftVTableContext() {
  523. return VTables.getMicrosoftVTableContext();
  524. }
  525. CtorList &getGlobalCtors() { return GlobalCtors; }
  526. CtorList &getGlobalDtors() { return GlobalDtors; }
  527. llvm::MDNode *getTBAAInfo(QualType QTy);
  528. llvm::MDNode *getTBAAInfoForVTablePtr();
  529. llvm::MDNode *getTBAAStructInfo(QualType QTy);
  530. /// Return the MDNode in the type DAG for the given struct type.
  531. llvm::MDNode *getTBAAStructTypeInfo(QualType QTy);
  532. /// Return the path-aware tag for given base type, access node and offset.
  533. llvm::MDNode *getTBAAStructTagInfo(QualType BaseTy, llvm::MDNode *AccessN,
  534. uint64_t O);
  535. bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor);
  536. bool isPaddedAtomicType(QualType type);
  537. bool isPaddedAtomicType(const AtomicType *type);
  538. /// Decorate the instruction with a TBAA tag. For scalar TBAA, the tag
  539. /// is the same as the type. For struct-path aware TBAA, the tag
  540. /// is different from the type: base type, access type and offset.
  541. /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
  542. void DecorateInstruction(llvm::Instruction *Inst,
  543. llvm::MDNode *TBAAInfo,
  544. bool ConvertTypeToTag = true);
  545. /// Emit the given number of characters as a value of type size_t.
  546. llvm::ConstantInt *getSize(CharUnits numChars);
  547. /// Set the visibility for the given LLVM GlobalValue.
  548. void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const;
  549. /// Set the TLS mode for the given LLVM GlobalValue for the thread-local
  550. /// variable declaration D.
  551. void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const;
  552. static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
  553. switch (V) {
  554. case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility;
  555. case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility;
  556. case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
  557. }
  558. llvm_unreachable("unknown visibility!");
  559. }
  560. llvm::Constant *GetAddrOfGlobal(GlobalDecl GD) {
  561. if (isa<CXXConstructorDecl>(GD.getDecl()))
  562. return getAddrOfCXXStructor(cast<CXXConstructorDecl>(GD.getDecl()),
  563. getFromCtorType(GD.getCtorType()));
  564. else if (isa<CXXDestructorDecl>(GD.getDecl()))
  565. return getAddrOfCXXStructor(cast<CXXDestructorDecl>(GD.getDecl()),
  566. getFromDtorType(GD.getDtorType()));
  567. else if (isa<FunctionDecl>(GD.getDecl()))
  568. return GetAddrOfFunction(GD);
  569. else
  570. return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl()));
  571. }
  572. /// Will return a global variable of the given type. If a variable with a
  573. /// different type already exists then a new variable with the right type
  574. /// will be created and all uses of the old variable will be replaced with a
  575. /// bitcast to the new variable.
  576. llvm::GlobalVariable *
  577. CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty,
  578. llvm::GlobalValue::LinkageTypes Linkage);
  579. llvm::Function *
  580. CreateGlobalInitOrDestructFunction(llvm::FunctionType *ty, const Twine &name,
  581. SourceLocation Loc = SourceLocation(),
  582. bool TLS = false);
  583. /// Return the address space of the underlying global variable for D, as
  584. /// determined by its declaration. Normally this is the same as the address
  585. /// space of D's type, but in CUDA, address spaces are associated with
  586. /// declarations, not types.
  587. unsigned GetGlobalVarAddressSpace(const VarDecl *D, unsigned AddrSpace);
  588. /// Return the llvm::Constant for the address of the given global variable.
  589. /// If Ty is non-null and if the global doesn't exist, then it will be greated
  590. /// with the specified type instead of whatever the normal requested type
  591. /// would be.
  592. llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
  593. llvm::Type *Ty = nullptr);
  594. /// Return the address of the given function. If Ty is non-null, then this
  595. /// function will use the specified type if it has to create it.
  596. llvm::Constant *GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty = 0,
  597. bool ForVTable = false,
  598. bool DontDefer = false);
  599. /// Get the address of the RTTI descriptor for the given type.
  600. llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
  601. llvm::Constant *getAddrOfCXXCatchHandlerType(QualType Ty,
  602. QualType CatchHandlerType);
  603. /// Get the address of a uuid descriptor .
  604. llvm::Constant *GetAddrOfUuidDescriptor(const CXXUuidofExpr* E);
  605. /// Get the address of the thunk for the given global decl.
  606. llvm::Constant *GetAddrOfThunk(GlobalDecl GD, const ThunkInfo &Thunk);
  607. /// Get a reference to the target of VD.
  608. llvm::Constant *GetWeakRefReference(const ValueDecl *VD);
  609. CharUnits
  610. computeNonVirtualBaseClassOffset(const CXXRecordDecl *DerivedClass,
  611. CastExpr::path_const_iterator Start,
  612. CastExpr::path_const_iterator End);
  613. /// Returns the offset from a derived class to a class. Returns null if the
  614. /// offset is 0.
  615. llvm::Constant *
  616. GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
  617. CastExpr::path_const_iterator PathBegin,
  618. CastExpr::path_const_iterator PathEnd);
  619. /// A pair of helper functions for a __block variable.
  620. class ByrefHelpers : public llvm::FoldingSetNode {
  621. public:
  622. llvm::Constant *CopyHelper;
  623. llvm::Constant *DisposeHelper;
  624. /// The alignment of the field. This is important because
  625. /// different offsets to the field within the byref struct need to
  626. /// have different helper functions.
  627. CharUnits Alignment;
  628. ByrefHelpers(CharUnits alignment) : Alignment(alignment) {}
  629. virtual ~ByrefHelpers();
  630. void Profile(llvm::FoldingSetNodeID &id) const {
  631. id.AddInteger(Alignment.getQuantity());
  632. profileImpl(id);
  633. }
  634. virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0;
  635. virtual bool needsCopy() const { return true; }
  636. virtual void emitCopy(CodeGenFunction &CGF,
  637. llvm::Value *dest, llvm::Value *src) = 0;
  638. virtual bool needsDispose() const { return true; }
  639. virtual void emitDispose(CodeGenFunction &CGF, llvm::Value *field) = 0;
  640. };
  641. llvm::FoldingSet<ByrefHelpers> ByrefHelpersCache;
  642. /// Fetches the global unique block count.
  643. int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; }
  644. /// Fetches the type of a generic block descriptor.
  645. llvm::Type *getBlockDescriptorType();
  646. /// The type of a generic block literal.
  647. llvm::Type *getGenericBlockLiteralType();
  648. /// Gets the address of a block which requires no captures.
  649. llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, const char *);
  650. /// Return a pointer to a constant CFString object for the given string.
  651. llvm::Constant *GetAddrOfConstantCFString(const StringLiteral *Literal);
  652. /// Return a pointer to a constant NSString object for the given string. Or a
  653. /// user defined String object as defined via
  654. /// -fconstant-string-class=class_name option.
  655. llvm::GlobalVariable *GetAddrOfConstantString(const StringLiteral *Literal);
  656. /// Return a constant array for the given string.
  657. llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E);
  658. /// Return a pointer to a constant array for the given string literal.
  659. llvm::GlobalVariable *
  660. GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
  661. StringRef Name = ".str");
  662. /// Return a pointer to a constant array for the given ObjCEncodeExpr node.
  663. llvm::GlobalVariable *
  664. GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
  665. /// Returns a pointer to a character array containing the literal and a
  666. /// terminating '\0' character. The result has pointer to array type.
  667. ///
  668. /// \param GlobalName If provided, the name to use for the global (if one is
  669. /// created).
  670. llvm::GlobalVariable *
  671. GetAddrOfConstantCString(const std::string &Str,
  672. const char *GlobalName = nullptr,
  673. unsigned Alignment = 0);
  674. /// Returns a pointer to a constant global variable for the given file-scope
  675. /// compound literal expression.
  676. llvm::Constant *GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E);
  677. /// \brief Returns a pointer to a global variable representing a temporary
  678. /// with static or thread storage duration.
  679. llvm::Constant *GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E,
  680. const Expr *Inner);
  681. /// \brief Retrieve the record type that describes the state of an
  682. /// Objective-C fast enumeration loop (for..in).
  683. QualType getObjCFastEnumerationStateType();
  684. // Produce code for this constructor/destructor. This method doesn't try
  685. // to apply any ABI rules about which other constructors/destructors
  686. // are needed or if they are alias to each other.
  687. llvm::Function *codegenCXXStructor(const CXXMethodDecl *MD,
  688. StructorType Type);
  689. /// Return the address of the constructor/destructor of the given type.
  690. llvm::GlobalValue *
  691. getAddrOfCXXStructor(const CXXMethodDecl *MD, StructorType Type,
  692. const CGFunctionInfo *FnInfo = nullptr,
  693. llvm::FunctionType *FnType = nullptr,
  694. bool DontDefer = false);
  695. /// Given a builtin id for a function like "__builtin_fabsf", return a
  696. /// Function* for "fabsf".
  697. llvm::Value *getBuiltinLibFunction(const FunctionDecl *FD,
  698. unsigned BuiltinID);
  699. llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys = None);
  700. /// Emit code for a single top level declaration.
  701. void EmitTopLevelDecl(Decl *D);
  702. /// \brief Stored a deferred empty coverage mapping for an unused
  703. /// and thus uninstrumented top level declaration.
  704. void AddDeferredUnusedCoverageMapping(Decl *D);
  705. /// \brief Remove the deferred empty coverage mapping as this
  706. /// declaration is actually instrumented.
  707. void ClearUnusedCoverageMapping(const Decl *D);
  708. /// \brief Emit all the deferred coverage mappings
  709. /// for the uninstrumented functions.
  710. void EmitDeferredUnusedCoverageMappings();
  711. /// Tell the consumer that this variable has been instantiated.
  712. void HandleCXXStaticMemberVarInstantiation(VarDecl *VD);
  713. /// \brief If the declaration has internal linkage but is inside an
  714. /// extern "C" linkage specification, prepare to emit an alias for it
  715. /// to the expected name.
  716. template<typename SomeDecl>
  717. void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV);
  718. /// Add a global to a list to be added to the llvm.used metadata.
  719. void addUsedGlobal(llvm::GlobalValue *GV);
  720. /// Add a global to a list to be added to the llvm.compiler.used metadata.
  721. void addCompilerUsedGlobal(llvm::GlobalValue *GV);
  722. /// Add a destructor and object to add to the C++ global destructor function.
  723. void AddCXXDtorEntry(llvm::Constant *DtorFn, llvm::Constant *Object) {
  724. CXXGlobalDtors.emplace_back(DtorFn, Object);
  725. }
  726. /// Create a new runtime function with the specified type and name.
  727. llvm::Constant *CreateRuntimeFunction(llvm::FunctionType *Ty,
  728. StringRef Name,
  729. llvm::AttributeSet ExtraAttrs =
  730. llvm::AttributeSet());
  731. /// Create a new compiler builtin function with the specified type and name.
  732. llvm::Constant *CreateBuiltinFunction(llvm::FunctionType *Ty,
  733. StringRef Name,
  734. llvm::AttributeSet ExtraAttrs =
  735. llvm::AttributeSet());
  736. /// Create a new runtime global variable with the specified type and name.
  737. llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty,
  738. StringRef Name);
  739. ///@name Custom Blocks Runtime Interfaces
  740. ///@{
  741. llvm::Constant *getNSConcreteGlobalBlock();
  742. llvm::Constant *getNSConcreteStackBlock();
  743. llvm::Constant *getBlockObjectAssign();
  744. llvm::Constant *getBlockObjectDispose();
  745. ///@}
  746. llvm::Constant *getLLVMLifetimeStartFn();
  747. llvm::Constant *getLLVMLifetimeEndFn();
  748. // Make sure that this type is translated.
  749. void UpdateCompletedType(const TagDecl *TD);
  750. llvm::Constant *getMemberPointerConstant(const UnaryOperator *e);
  751. /// Try to emit the initializer for the given declaration as a constant;
  752. /// returns 0 if the expression cannot be emitted as a constant.
  753. llvm::Constant *EmitConstantInit(const VarDecl &D,
  754. CodeGenFunction *CGF = nullptr);
  755. /// Try to emit the given expression as a constant; returns 0 if the
  756. /// expression cannot be emitted as a constant.
  757. llvm::Constant *EmitConstantExpr(const Expr *E, QualType DestType,
  758. CodeGenFunction *CGF = nullptr);
  759. /// Emit the given constant value as a constant, in the type's scalar
  760. /// representation.
  761. llvm::Constant *EmitConstantValue(const APValue &Value, QualType DestType,
  762. CodeGenFunction *CGF = nullptr);
  763. /// Emit the given constant value as a constant, in the type's memory
  764. /// representation.
  765. llvm::Constant *EmitConstantValueForMemory(const APValue &Value,
  766. QualType DestType,
  767. CodeGenFunction *CGF = nullptr);
  768. /// Return the result of value-initializing the given type, i.e. a null
  769. /// expression of the given type. This is usually, but not always, an LLVM
  770. /// null constant.
  771. llvm::Constant *EmitNullConstant(QualType T);
  772. /// Return a null constant appropriate for zero-initializing a base class with
  773. /// the given type. This is usually, but not always, an LLVM null constant.
  774. llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record);
  775. /// Emit a general error that something can't be done.
  776. void Error(SourceLocation loc, StringRef error);
  777. /// Print out an error that codegen doesn't support the specified stmt yet.
  778. void ErrorUnsupported(const Stmt *S, const char *Type);
  779. /// Print out an error that codegen doesn't support the specified decl yet.
  780. void ErrorUnsupported(const Decl *D, const char *Type);
  781. /// Set the attributes on the LLVM function for the given decl and function
  782. /// info. This applies attributes necessary for handling the ABI as well as
  783. /// user specified attributes like section.
  784. void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F,
  785. const CGFunctionInfo &FI);
  786. /// Set the LLVM function attributes (sext, zext, etc).
  787. void SetLLVMFunctionAttributes(const Decl *D,
  788. const CGFunctionInfo &Info,
  789. llvm::Function *F);
  790. /// Set the LLVM function attributes which only apply to a function
  791. /// definition.
  792. void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
  793. /// Return true iff the given type uses 'sret' when used as a return type.
  794. bool ReturnTypeUsesSRet(const CGFunctionInfo &FI);
  795. /// Return true iff the given type uses an argument slot when 'sret' is used
  796. /// as a return type.
  797. bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI);
  798. /// Return true iff the given type uses 'fpret' when used as a return type.
  799. bool ReturnTypeUsesFPRet(QualType ResultType);
  800. /// Return true iff the given type uses 'fp2ret' when used as a return type.
  801. bool ReturnTypeUsesFP2Ret(QualType ResultType);
  802. /// Get the LLVM attributes and calling convention to use for a particular
  803. /// function type.
  804. ///
  805. /// \param Info - The function type information.
  806. /// \param TargetDecl - The decl these attributes are being constructed
  807. /// for. If supplied the attributes applied to this decl may contribute to the
  808. /// function attributes and calling convention.
  809. /// \param PAL [out] - On return, the attribute list to use.
  810. /// \param CallingConv [out] - On return, the LLVM calling convention to use.
  811. void ConstructAttributeList(const CGFunctionInfo &Info,
  812. const Decl *TargetDecl,
  813. AttributeListType &PAL,
  814. unsigned &CallingConv,
  815. bool AttrOnCallSite);
  816. StringRef getMangledName(GlobalDecl GD);
  817. StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD);
  818. void EmitTentativeDefinition(const VarDecl *D);
  819. void EmitVTable(CXXRecordDecl *Class);
  820. /// Emit the RTTI descriptors for the builtin types.
  821. void EmitFundamentalRTTIDescriptors();
  822. /// \brief Appends Opts to the "Linker Options" metadata value.
  823. void AppendLinkerOptions(StringRef Opts);
  824. /// \brief Appends a detect mismatch command to the linker options.
  825. void AddDetectMismatch(StringRef Name, StringRef Value);
  826. /// \brief Appends a dependent lib to the "Linker Options" metadata value.
  827. void AddDependentLib(StringRef Lib);
  828. llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD);
  829. void setFunctionLinkage(GlobalDecl GD, llvm::Function *F) {
  830. F->setLinkage(getFunctionLinkage(GD));
  831. }
  832. /// Set the DLL storage class on F.
  833. void setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F);
  834. /// Return the appropriate linkage for the vtable, VTT, and type information
  835. /// of the given class.
  836. llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD);
  837. /// Return the store size, in character units, of the given LLVM type.
  838. CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const;
  839. /// Returns LLVM linkage for a declarator.
  840. llvm::GlobalValue::LinkageTypes
  841. getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage,
  842. bool IsConstantVariable);
  843. /// Returns LLVM linkage for a declarator.
  844. llvm::GlobalValue::LinkageTypes
  845. getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant);
  846. /// Emit all the global annotations.
  847. void EmitGlobalAnnotations();
  848. /// Emit an annotation string.
  849. llvm::Constant *EmitAnnotationString(StringRef Str);
  850. /// Emit the annotation's translation unit.
  851. llvm::Constant *EmitAnnotationUnit(SourceLocation Loc);
  852. /// Emit the annotation line number.
  853. llvm::Constant *EmitAnnotationLineNo(SourceLocation L);
  854. /// Generate the llvm::ConstantStruct which contains the annotation
  855. /// information for a given GlobalValue. The annotation struct is
  856. /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
  857. /// GlobalValue being annotated. The second field is the constant string
  858. /// created from the AnnotateAttr's annotation. The third field is a constant
  859. /// string containing the name of the translation unit. The fourth field is
  860. /// the line number in the file of the annotated value declaration.
  861. llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
  862. const AnnotateAttr *AA,
  863. SourceLocation L);
  864. /// Add global annotations that are set on D, for the global GV. Those
  865. /// annotations are emitted during finalization of the LLVM code.
  866. void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV);
  867. bool isInSanitizerBlacklist(llvm::Function *Fn, SourceLocation Loc) const;
  868. bool isInSanitizerBlacklist(llvm::GlobalVariable *GV, SourceLocation Loc,
  869. QualType Ty,
  870. StringRef Category = StringRef()) const;
  871. SanitizerMetadata *getSanitizerMetadata() {
  872. return SanitizerMD.get();
  873. }
  874. void addDeferredVTable(const CXXRecordDecl *RD) {
  875. DeferredVTables.push_back(RD);
  876. }
  877. /// Emit code for a singal global function or var decl. Forward declarations
  878. /// are emitted lazily.
  879. void EmitGlobal(GlobalDecl D);
  880. bool TryEmitDefinitionAsAlias(GlobalDecl Alias, GlobalDecl Target,
  881. bool InEveryTU);
  882. bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D);
  883. /// Set attributes for a global definition.
  884. void setFunctionDefinitionAttributes(const FunctionDecl *D,
  885. llvm::Function *F);
  886. llvm::GlobalValue *GetGlobalValue(StringRef Ref);
  887. /// Set attributes which are common to any form of a global definition (alias,
  888. /// Objective-C method, function, global variable).
  889. ///
  890. /// NOTE: This should only be called for definitions.
  891. void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV);
  892. /// Set attributes which must be preserved by an alias. This includes common
  893. /// attributes (i.e. it includes a call to SetCommonAttributes).
  894. ///
  895. /// NOTE: This should only be called for definitions.
  896. void setAliasAttributes(const Decl *D, llvm::GlobalValue *GV);
  897. void addReplacement(StringRef Name, llvm::Constant *C);
  898. /// \brief Emit a code for threadprivate directive.
  899. /// \param D Threadprivate declaration.
  900. void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D);
  901. /// Returns whether the given record is blacklisted from control flow
  902. /// integrity checks.
  903. bool IsCFIBlacklistedRecord(const CXXRecordDecl *RD);
  904. /// Emit bit set entries for the given vtable using the given layout if
  905. /// vptr CFI is enabled.
  906. void EmitVTableBitSetEntries(llvm::GlobalVariable *VTable,
  907. const VTableLayout &VTLayout);
  908. /// Create a bitset entry for the given vtable.
  909. llvm::MDTuple *CreateVTableBitSetEntry(llvm::GlobalVariable *VTable,
  910. CharUnits Offset,
  911. const CXXRecordDecl *RD);
  912. /// \breif Get the declaration of std::terminate for the platform.
  913. llvm::Constant *getTerminateFn();
  914. private:
  915. llvm::Constant *
  916. GetOrCreateLLVMFunction(StringRef MangledName, llvm::Type *Ty, GlobalDecl D,
  917. bool ForVTable, bool DontDefer = false,
  918. bool IsThunk = false,
  919. llvm::AttributeSet ExtraAttrs = llvm::AttributeSet());
  920. llvm::Constant *GetOrCreateLLVMGlobal(StringRef MangledName,
  921. llvm::PointerType *PTy,
  922. const VarDecl *D);
  923. void setNonAliasAttributes(const Decl *D, llvm::GlobalObject *GO);
  924. /// Set function attributes for a function declaration.
  925. void SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
  926. bool IsIncompleteFunction, bool IsThunk);
  927. void EmitGlobalDefinition(GlobalDecl D, llvm::GlobalValue *GV = nullptr);
  928. void EmitGlobalFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
  929. void EmitGlobalVarDefinition(const VarDecl *D);
  930. void EmitAliasDefinition(GlobalDecl GD);
  931. void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
  932. void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
  933. // C++ related functions.
  934. void EmitNamespace(const NamespaceDecl *D);
  935. void EmitLinkageSpec(const LinkageSpecDecl *D);
  936. void CompleteDIClassType(const CXXMethodDecl* D);
  937. /// \brief Emit the function that initializes C++ thread_local variables.
  938. void EmitCXXThreadLocalInitFunc();
  939. /// Emit the function that initializes C++ globals.
  940. void EmitCXXGlobalInitFunc();
  941. /// Emit the function that destroys C++ globals.
  942. void EmitCXXGlobalDtorFunc();
  943. /// Emit the function that initializes the specified global (if PerformInit is
  944. /// true) and registers its destructor.
  945. void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
  946. llvm::GlobalVariable *Addr,
  947. bool PerformInit);
  948. void EmitPointerToInitFunc(const VarDecl *VD, llvm::GlobalVariable *Addr,
  949. llvm::Function *InitFunc, InitSegAttr *ISA);
  950. // FIXME: Hardcoding priority here is gross.
  951. void AddGlobalCtor(llvm::Function *Ctor, int Priority = 65535,
  952. llvm::Constant *AssociatedData = 0);
  953. void AddGlobalDtor(llvm::Function *Dtor, int Priority = 65535);
  954. /// Generates a global array of functions and priorities using the given list
  955. /// and name. This array will have appending linkage and is suitable for use
  956. /// as a LLVM constructor or destructor array.
  957. void EmitCtorList(const CtorList &Fns, const char *GlobalName);
  958. /// Emit the RTTI descriptors for the given type.
  959. void EmitFundamentalRTTIDescriptor(QualType Type);
  960. /// Emit any needed decls for which code generation was deferred.
  961. void EmitDeferred();
  962. /// Call replaceAllUsesWith on all pairs in Replacements.
  963. void applyReplacements();
  964. void checkAliases();
  965. /// Emit any vtables which we deferred and still have a use for.
  966. void EmitDeferredVTables();
  967. /// Emit the llvm.used and llvm.compiler.used metadata.
  968. void emitLLVMUsed();
  969. /// \brief Emit the link options introduced by imported modules.
  970. void EmitModuleLinkOptions();
  971. /// \brief Emit aliases for internal-linkage declarations inside "C" language
  972. /// linkage specifications, giving them the "expected" name where possible.
  973. void EmitStaticExternCAliases();
  974. void EmitDeclMetadata();
  975. /// \brief Emit the Clang version as llvm.ident metadata.
  976. void EmitVersionIdentMetadata();
  977. /// Emits target specific Metadata for global declarations.
  978. void EmitTargetMetadata();
  979. /// Emit the llvm.gcov metadata used to tell LLVM where to emit the .gcno and
  980. /// .gcda files in a way that persists in .bc files.
  981. void EmitCoverageFile();
  982. /// Emits the initializer for a uuidof string.
  983. llvm::Constant *EmitUuidofInitializer(StringRef uuidstr);
  984. /// Determine whether the definition must be emitted; if this returns \c
  985. /// false, the definition can be emitted lazily if it's used.
  986. bool MustBeEmitted(const ValueDecl *D);
  987. /// Determine whether the definition can be emitted eagerly, or should be
  988. /// delayed until the end of the translation unit. This is relevant for
  989. /// definitions whose linkage can change, e.g. implicit function instantions
  990. /// which may later be explicitly instantiated.
  991. bool MayBeEmittedEagerly(const ValueDecl *D);
  992. /// Check whether we can use a "simpler", more core exceptions personality
  993. /// function.
  994. void SimplifyPersonality();
  995. };
  996. } // end namespace CodeGen
  997. } // end namespace clang
  998. #endif