CodeGenModule.h 52 KB

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