CodeGenModule.h 51 KB

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