LTO.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===-LTO.h - LLVM Link Time Optimizer ------------------------------------===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file declares functions and classes used to support LTO. It is intended
  15. // to be used both by LTO classes as well as by clients (gold-plugin) that
  16. // don't utilize the LTO code generator interfaces.
  17. //
  18. //===----------------------------------------------------------------------===//
  19. #ifndef LLVM_LTO_LTO_H
  20. #define LLVM_LTO_LTO_H
  21. #include "llvm/ADT/MapVector.h"
  22. #include "llvm/ADT/StringMap.h"
  23. #include "llvm/Bitcode/BitcodeReader.h"
  24. #include "llvm/IR/ModuleSummaryIndex.h"
  25. #include "llvm/LTO/Config.h"
  26. #include "llvm/Object/IRSymtab.h"
  27. #include "llvm/Support/Caching.h"
  28. #include "llvm/Support/Error.h"
  29. #include "llvm/Support/thread.h"
  30. #include "llvm/Transforms/IPO/FunctionAttrs.h"
  31. #include "llvm/Transforms/IPO/FunctionImport.h"
  32. namespace llvm {
  33. class Error;
  34. class IRMover;
  35. class LLVMContext;
  36. class MemoryBufferRef;
  37. class Module;
  38. class raw_pwrite_stream;
  39. class ToolOutputFile;
  40. /// Resolve linkage for prevailing symbols in the \p Index. Linkage changes
  41. /// recorded in the index and the ThinLTO backends must apply the changes to
  42. /// the module via thinLTOFinalizeInModule.
  43. ///
  44. /// This is done for correctness (if value exported, ensure we always
  45. /// emit a copy), and compile-time optimization (allow drop of duplicates).
  46. void thinLTOResolvePrevailingInIndex(
  47. const lto::Config &C, ModuleSummaryIndex &Index,
  48. function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
  49. isPrevailing,
  50. function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
  51. recordNewLinkage,
  52. const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols);
  53. /// Update the linkages in the given \p Index to mark exported values
  54. /// as external and non-exported values as internal. The ThinLTO backends
  55. /// must apply the changes to the Module via thinLTOInternalizeModule.
  56. void thinLTOInternalizeAndPromoteInIndex(
  57. ModuleSummaryIndex &Index,
  58. function_ref<bool(StringRef, ValueInfo)> isExported,
  59. function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
  60. isPrevailing);
  61. /// Computes a unique hash for the Module considering the current list of
  62. /// export/import and other global analysis results.
  63. /// The hash is produced in \p Key.
  64. void computeLTOCacheKey(
  65. SmallString<40> &Key, const lto::Config &Conf,
  66. const ModuleSummaryIndex &Index, StringRef ModuleID,
  67. const FunctionImporter::ImportMapTy &ImportList,
  68. const FunctionImporter::ExportSetTy &ExportList,
  69. const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
  70. const GVSummaryMapTy &DefinedGlobals,
  71. const std::set<GlobalValue::GUID> &CfiFunctionDefs = {},
  72. const std::set<GlobalValue::GUID> &CfiFunctionDecls = {});
  73. namespace lto {
  74. /// Given the original \p Path to an output file, replace any path
  75. /// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
  76. /// resulting directory if it does not yet exist.
  77. std::string getThinLTOOutputFile(const std::string &Path,
  78. const std::string &OldPrefix,
  79. const std::string &NewPrefix);
  80. /// Setup optimization remarks.
  81. Expected<std::unique_ptr<ToolOutputFile>> setupLLVMOptimizationRemarks(
  82. LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses,
  83. StringRef RemarksFormat, bool RemarksWithHotness,
  84. Optional<uint64_t> RemarksHotnessThreshold = 0, int Count = -1);
  85. /// Setups the output file for saving statistics.
  86. Expected<std::unique_ptr<ToolOutputFile>>
  87. setupStatsFile(StringRef StatsFilename);
  88. /// Produces a container ordering for optimal multi-threaded processing. Returns
  89. /// ordered indices to elements in the input array.
  90. std::vector<int> generateModulesOrdering(ArrayRef<BitcodeModule *> R);
  91. class LTO;
  92. struct SymbolResolution;
  93. class ThinBackendProc;
  94. /// An input file. This is a symbol table wrapper that only exposes the
  95. /// information that an LTO client should need in order to do symbol resolution.
  96. class InputFile {
  97. public:
  98. class Symbol;
  99. private:
  100. // FIXME: Remove LTO class friendship once we have bitcode symbol tables.
  101. friend LTO;
  102. InputFile() = default;
  103. std::vector<BitcodeModule> Mods;
  104. SmallVector<char, 0> Strtab;
  105. std::vector<Symbol> Symbols;
  106. // [begin, end) for each module
  107. std::vector<std::pair<size_t, size_t>> ModuleSymIndices;
  108. StringRef TargetTriple, SourceFileName, COFFLinkerOpts;
  109. std::vector<StringRef> DependentLibraries;
  110. std::vector<std::pair<StringRef, Comdat::SelectionKind>> ComdatTable;
  111. public:
  112. ~InputFile();
  113. /// Create an InputFile.
  114. static Expected<std::unique_ptr<InputFile>> create(MemoryBufferRef Object);
  115. /// The purpose of this class is to only expose the symbol information that an
  116. /// LTO client should need in order to do symbol resolution.
  117. class Symbol : irsymtab::Symbol {
  118. friend LTO;
  119. public:
  120. Symbol(const irsymtab::Symbol &S) : irsymtab::Symbol(S) {}
  121. using irsymtab::Symbol::isUndefined;
  122. using irsymtab::Symbol::isCommon;
  123. using irsymtab::Symbol::isWeak;
  124. using irsymtab::Symbol::isIndirect;
  125. using irsymtab::Symbol::getName;
  126. using irsymtab::Symbol::getIRName;
  127. using irsymtab::Symbol::getVisibility;
  128. using irsymtab::Symbol::canBeOmittedFromSymbolTable;
  129. using irsymtab::Symbol::isTLS;
  130. using irsymtab::Symbol::getComdatIndex;
  131. using irsymtab::Symbol::getCommonSize;
  132. using irsymtab::Symbol::getCommonAlignment;
  133. using irsymtab::Symbol::getCOFFWeakExternalFallback;
  134. using irsymtab::Symbol::getSectionName;
  135. using irsymtab::Symbol::isExecutable;
  136. using irsymtab::Symbol::isUsed;
  137. };
  138. /// A range over the symbols in this InputFile.
  139. ArrayRef<Symbol> symbols() const { return Symbols; }
  140. /// Returns linker options specified in the input file.
  141. StringRef getCOFFLinkerOpts() const { return COFFLinkerOpts; }
  142. /// Returns dependent library specifiers from the input file.
  143. ArrayRef<StringRef> getDependentLibraries() const { return DependentLibraries; }
  144. /// Returns the path to the InputFile.
  145. StringRef getName() const;
  146. /// Returns the input file's target triple.
  147. StringRef getTargetTriple() const { return TargetTriple; }
  148. /// Returns the source file path specified at compile time.
  149. StringRef getSourceFileName() const { return SourceFileName; }
  150. // Returns a table with all the comdats used by this file.
  151. ArrayRef<std::pair<StringRef, Comdat::SelectionKind>> getComdatTable() const {
  152. return ComdatTable;
  153. }
  154. // Returns the only BitcodeModule from InputFile.
  155. BitcodeModule &getSingleBitcodeModule();
  156. private:
  157. ArrayRef<Symbol> module_symbols(unsigned I) const {
  158. const auto &Indices = ModuleSymIndices[I];
  159. return {Symbols.data() + Indices.first, Symbols.data() + Indices.second};
  160. }
  161. };
  162. /// A ThinBackend defines what happens after the thin-link phase during ThinLTO.
  163. /// The details of this type definition aren't important; clients can only
  164. /// create a ThinBackend using one of the create*ThinBackend() functions below.
  165. using ThinBackend = std::function<std::unique_ptr<ThinBackendProc>(
  166. const Config &C, ModuleSummaryIndex &CombinedIndex,
  167. StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
  168. AddStreamFn AddStream, FileCache Cache)>;
  169. /// This ThinBackend runs the individual backend jobs in-process.
  170. /// The default value means to use one job per hardware core (not hyper-thread).
  171. ThinBackend createInProcessThinBackend(ThreadPoolStrategy Parallelism);
  172. /// This ThinBackend writes individual module indexes to files, instead of
  173. /// running the individual backend jobs. This backend is for distributed builds
  174. /// where separate processes will invoke the real backends.
  175. ///
  176. /// To find the path to write the index to, the backend checks if the path has a
  177. /// prefix of OldPrefix; if so, it replaces that prefix with NewPrefix. It then
  178. /// appends ".thinlto.bc" and writes the index to that path. If
  179. /// ShouldEmitImportsFiles is true it also writes a list of imported files to a
  180. /// similar path with ".imports" appended instead.
  181. /// LinkedObjectsFile is an output stream to write the list of object files for
  182. /// the final ThinLTO linking. Can be nullptr.
  183. /// OnWrite is callback which receives module identifier and notifies LTO user
  184. /// that index file for the module (and optionally imports file) was created.
  185. using IndexWriteCallback = std::function<void(const std::string &)>;
  186. ThinBackend createWriteIndexesThinBackend(std::string OldPrefix,
  187. std::string NewPrefix,
  188. bool ShouldEmitImportsFiles,
  189. raw_fd_ostream *LinkedObjectsFile,
  190. IndexWriteCallback OnWrite);
  191. /// This class implements a resolution-based interface to LLVM's LTO
  192. /// functionality. It supports regular LTO, parallel LTO code generation and
  193. /// ThinLTO. You can use it from a linker in the following way:
  194. /// - Set hooks and code generation options (see lto::Config struct defined in
  195. /// Config.h), and use the lto::Config object to create an lto::LTO object.
  196. /// - Create lto::InputFile objects using lto::InputFile::create(), then use
  197. /// the symbols() function to enumerate its symbols and compute a resolution
  198. /// for each symbol (see SymbolResolution below).
  199. /// - After the linker has visited each input file (and each regular object
  200. /// file) and computed a resolution for each symbol, take each lto::InputFile
  201. /// and pass it and an array of symbol resolutions to the add() function.
  202. /// - Call the getMaxTasks() function to get an upper bound on the number of
  203. /// native object files that LTO may add to the link.
  204. /// - Call the run() function. This function will use the supplied AddStream
  205. /// and Cache functions to add up to getMaxTasks() native object files to
  206. /// the link.
  207. class LTO {
  208. friend InputFile;
  209. public:
  210. /// Create an LTO object. A default constructed LTO object has a reasonable
  211. /// production configuration, but you can customize it by passing arguments to
  212. /// this constructor.
  213. /// FIXME: We do currently require the DiagHandler field to be set in Conf.
  214. /// Until that is fixed, a Config argument is required.
  215. LTO(Config Conf, ThinBackend Backend = nullptr,
  216. unsigned ParallelCodeGenParallelismLevel = 1);
  217. ~LTO();
  218. /// Add an input file to the LTO link, using the provided symbol resolutions.
  219. /// The symbol resolutions must appear in the enumeration order given by
  220. /// InputFile::symbols().
  221. Error add(std::unique_ptr<InputFile> Obj, ArrayRef<SymbolResolution> Res);
  222. /// Returns an upper bound on the number of tasks that the client may expect.
  223. /// This may only be called after all IR object files have been added. For a
  224. /// full description of tasks see LTOBackend.h.
  225. unsigned getMaxTasks() const;
  226. /// Runs the LTO pipeline. This function calls the supplied AddStream
  227. /// function to add native object files to the link.
  228. ///
  229. /// The Cache parameter is optional. If supplied, it will be used to cache
  230. /// native object files and add them to the link.
  231. ///
  232. /// The client will receive at most one callback (via either AddStream or
  233. /// Cache) for each task identifier.
  234. Error run(AddStreamFn AddStream, FileCache Cache = nullptr);
  235. /// Static method that returns a list of libcall symbols that can be generated
  236. /// by LTO but might not be visible from bitcode symbol table.
  237. static ArrayRef<const char*> getRuntimeLibcallSymbols();
  238. private:
  239. Config Conf;
  240. struct RegularLTOState {
  241. RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
  242. const Config &Conf);
  243. struct CommonResolution {
  244. uint64_t Size = 0;
  245. MaybeAlign Align;
  246. /// Record if at least one instance of the common was marked as prevailing
  247. bool Prevailing = false;
  248. };
  249. std::map<std::string, CommonResolution> Commons;
  250. unsigned ParallelCodeGenParallelismLevel;
  251. LTOLLVMContext Ctx;
  252. std::unique_ptr<Module> CombinedModule;
  253. std::unique_ptr<IRMover> Mover;
  254. // This stores the information about a regular LTO module that we have added
  255. // to the link. It will either be linked immediately (for modules without
  256. // summaries) or after summary-based dead stripping (for modules with
  257. // summaries).
  258. struct AddedModule {
  259. std::unique_ptr<Module> M;
  260. std::vector<GlobalValue *> Keep;
  261. };
  262. std::vector<AddedModule> ModsWithSummaries;
  263. bool EmptyCombinedModule = true;
  264. } RegularLTO;
  265. using ModuleMapType = MapVector<StringRef, BitcodeModule>;
  266. struct ThinLTOState {
  267. ThinLTOState(ThinBackend Backend);
  268. ThinBackend Backend;
  269. ModuleSummaryIndex CombinedIndex;
  270. // The full set of bitcode modules in input order.
  271. ModuleMapType ModuleMap;
  272. // The bitcode modules to compile, if specified by the LTO Config.
  273. Optional<ModuleMapType> ModulesToCompile;
  274. DenseMap<GlobalValue::GUID, StringRef> PrevailingModuleForGUID;
  275. } ThinLTO;
  276. // The global resolution for a particular (mangled) symbol name. This is in
  277. // particular necessary to track whether each symbol can be internalized.
  278. // Because any input file may introduce a new cross-partition reference, we
  279. // cannot make any final internalization decisions until all input files have
  280. // been added and the client has called run(). During run() we apply
  281. // internalization decisions either directly to the module (for regular LTO)
  282. // or to the combined index (for ThinLTO).
  283. struct GlobalResolution {
  284. /// The unmangled name of the global.
  285. std::string IRName;
  286. /// Keep track if the symbol is visible outside of a module with a summary
  287. /// (i.e. in either a regular object or a regular LTO module without a
  288. /// summary).
  289. bool VisibleOutsideSummary = false;
  290. /// The symbol was exported dynamically, and therefore could be referenced
  291. /// by a shared library not visible to the linker.
  292. bool ExportDynamic = false;
  293. bool UnnamedAddr = true;
  294. /// True if module contains the prevailing definition.
  295. bool Prevailing = false;
  296. /// Returns true if module contains the prevailing definition and symbol is
  297. /// an IR symbol. For example when module-level inline asm block is used,
  298. /// symbol can be prevailing in module but have no IR name.
  299. bool isPrevailingIRSymbol() const { return Prevailing && !IRName.empty(); }
  300. /// This field keeps track of the partition number of this global. The
  301. /// regular LTO object is partition 0, while each ThinLTO object has its own
  302. /// partition number from 1 onwards.
  303. ///
  304. /// Any global that is defined or used by more than one partition, or that
  305. /// is referenced externally, may not be internalized.
  306. ///
  307. /// Partitions generally have a one-to-one correspondence with tasks, except
  308. /// that we use partition 0 for all parallel LTO code generation partitions.
  309. /// Any partitioning of the combined LTO object is done internally by the
  310. /// LTO backend.
  311. unsigned Partition = Unknown;
  312. /// Special partition numbers.
  313. enum : unsigned {
  314. /// A partition number has not yet been assigned to this global.
  315. Unknown = -1u,
  316. /// This global is either used by more than one partition or has an
  317. /// external reference, and therefore cannot be internalized.
  318. External = -2u,
  319. /// The RegularLTO partition
  320. RegularLTO = 0,
  321. };
  322. };
  323. // Global mapping from mangled symbol names to resolutions.
  324. StringMap<GlobalResolution> GlobalResolutions;
  325. void addModuleToGlobalRes(ArrayRef<InputFile::Symbol> Syms,
  326. ArrayRef<SymbolResolution> Res, unsigned Partition,
  327. bool InSummary);
  328. // These functions take a range of symbol resolutions [ResI, ResE) and consume
  329. // the resolutions used by a single input module by incrementing ResI. After
  330. // these functions return, [ResI, ResE) will refer to the resolution range for
  331. // the remaining modules in the InputFile.
  332. Error addModule(InputFile &Input, unsigned ModI,
  333. const SymbolResolution *&ResI, const SymbolResolution *ResE);
  334. Expected<RegularLTOState::AddedModule>
  335. addRegularLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
  336. const SymbolResolution *&ResI, const SymbolResolution *ResE);
  337. Error linkRegularLTO(RegularLTOState::AddedModule Mod,
  338. bool LivenessFromIndex);
  339. Error addThinLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
  340. const SymbolResolution *&ResI, const SymbolResolution *ResE);
  341. Error runRegularLTO(AddStreamFn AddStream);
  342. Error runThinLTO(AddStreamFn AddStream, FileCache Cache,
  343. const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols);
  344. Error checkPartiallySplit();
  345. mutable bool CalledGetMaxTasks = false;
  346. // Use Optional to distinguish false from not yet initialized.
  347. Optional<bool> EnableSplitLTOUnit;
  348. // Identify symbols exported dynamically, and that therefore could be
  349. // referenced by a shared library not visible to the linker.
  350. DenseSet<GlobalValue::GUID> DynamicExportSymbols;
  351. // Diagnostic optimization remarks file
  352. std::unique_ptr<ToolOutputFile> DiagnosticOutputFile;
  353. };
  354. /// The resolution for a symbol. The linker must provide a SymbolResolution for
  355. /// each global symbol based on its internal resolution of that symbol.
  356. struct SymbolResolution {
  357. SymbolResolution()
  358. : Prevailing(0), FinalDefinitionInLinkageUnit(0), VisibleToRegularObj(0),
  359. ExportDynamic(0), LinkerRedefined(0) {}
  360. /// The linker has chosen this definition of the symbol.
  361. unsigned Prevailing : 1;
  362. /// The definition of this symbol is unpreemptable at runtime and is known to
  363. /// be in this linkage unit.
  364. unsigned FinalDefinitionInLinkageUnit : 1;
  365. /// The definition of this symbol is visible outside of the LTO unit.
  366. unsigned VisibleToRegularObj : 1;
  367. /// The symbol was exported dynamically, and therefore could be referenced
  368. /// by a shared library not visible to the linker.
  369. unsigned ExportDynamic : 1;
  370. /// Linker redefined version of the symbol which appeared in -wrap or -defsym
  371. /// linker option.
  372. unsigned LinkerRedefined : 1;
  373. };
  374. } // namespace lto
  375. } // namespace llvm
  376. #endif
  377. #ifdef __GNUC__
  378. #pragma GCC diagnostic pop
  379. #endif