Config.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. //===-Config.h - LLVM Link Time Optimizer Configuration ---------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines the lto::Config data structure, which allows clients to
  10. // configure LTO.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_LTO_CONFIG_H
  14. #define LLVM_LTO_CONFIG_H
  15. #include "llvm/ADT/DenseSet.h"
  16. #include "llvm/Config/llvm-config.h"
  17. #include "llvm/IR/DiagnosticInfo.h"
  18. #include "llvm/IR/GlobalValue.h"
  19. #include "llvm/IR/LLVMContext.h"
  20. #include "llvm/IR/LegacyPassManager.h"
  21. #include "llvm/Passes/PassBuilder.h"
  22. #include "llvm/Support/CodeGen.h"
  23. #include "llvm/Target/TargetOptions.h"
  24. #include <functional>
  25. namespace llvm {
  26. class Error;
  27. class Module;
  28. class ModuleSummaryIndex;
  29. class raw_pwrite_stream;
  30. namespace lto {
  31. /// LTO configuration. A linker can configure LTO by setting fields in this data
  32. /// structure and passing it to the lto::LTO constructor.
  33. struct Config {
  34. enum VisScheme {
  35. FromPrevailing,
  36. ELF,
  37. };
  38. // Note: when adding fields here, consider whether they need to be added to
  39. // computeCacheKey in LTO.cpp.
  40. std::string CPU;
  41. TargetOptions Options;
  42. std::vector<std::string> MAttrs;
  43. std::vector<std::string> PassPlugins;
  44. /// For adding passes that run right before codegen.
  45. std::function<void(legacy::PassManager &)> PreCodeGenPassesHook;
  46. Optional<Reloc::Model> RelocModel = Reloc::PIC_;
  47. Optional<CodeModel::Model> CodeModel = None;
  48. CodeGenOpt::Level CGOptLevel = CodeGenOpt::Default;
  49. CodeGenFileType CGFileType = CGFT_ObjectFile;
  50. unsigned OptLevel = 2;
  51. bool DisableVerify = false;
  52. /// Use the new pass manager
  53. bool UseNewPM = LLVM_ENABLE_NEW_PASS_MANAGER;
  54. /// Flag to indicate that the optimizer should not assume builtins are present
  55. /// on the target.
  56. bool Freestanding = false;
  57. /// Disable entirely the optimizer, including importing for ThinLTO
  58. bool CodeGenOnly = false;
  59. /// Run PGO context sensitive IR instrumentation.
  60. bool RunCSIRInstr = false;
  61. /// Asserts whether we can assume whole program visibility during the LTO
  62. /// link.
  63. bool HasWholeProgramVisibility = false;
  64. /// Always emit a Regular LTO object even when it is empty because no Regular
  65. /// LTO modules were linked. This option is useful for some build system which
  66. /// want to know a priori all possible output files.
  67. bool AlwaysEmitRegularLTOObj = false;
  68. /// Allows non-imported definitions to get the potentially more constraining
  69. /// visibility from the prevailing definition. FromPrevailing is the default
  70. /// because it works for many binary formats. ELF can use the more optimized
  71. /// 'ELF' scheme.
  72. VisScheme VisibilityScheme = FromPrevailing;
  73. /// If this field is set, the set of passes run in the middle-end optimizer
  74. /// will be the one specified by the string. Only works with the new pass
  75. /// manager as the old one doesn't have this ability.
  76. std::string OptPipeline;
  77. // If this field is set, it has the same effect of specifying an AA pipeline
  78. // identified by the string. Only works with the new pass manager, in
  79. // conjunction OptPipeline.
  80. std::string AAPipeline;
  81. /// Setting this field will replace target triples in input files with this
  82. /// triple.
  83. std::string OverrideTriple;
  84. /// Setting this field will replace unspecified target triples in input files
  85. /// with this triple.
  86. std::string DefaultTriple;
  87. /// Context Sensitive PGO profile path.
  88. std::string CSIRProfile;
  89. /// Sample PGO profile path.
  90. std::string SampleProfile;
  91. /// Name remapping file for profile data.
  92. std::string ProfileRemapping;
  93. /// The directory to store .dwo files.
  94. std::string DwoDir;
  95. /// The name for the split debug info file used for the DW_AT_[GNU_]dwo_name
  96. /// attribute in the skeleton CU. This should generally only be used when
  97. /// running an individual backend directly via thinBackend(), as otherwise
  98. /// all objects would use the same .dwo file. Not used as output path.
  99. std::string SplitDwarfFile;
  100. /// The path to write a .dwo file to. This should generally only be used when
  101. /// running an individual backend directly via thinBackend(), as otherwise
  102. /// all .dwo files will be written to the same path. Not used in skeleton CU.
  103. std::string SplitDwarfOutput;
  104. /// Optimization remarks file path.
  105. std::string RemarksFilename;
  106. /// Optimization remarks pass filter.
  107. std::string RemarksPasses;
  108. /// Whether to emit optimization remarks with hotness informations.
  109. bool RemarksWithHotness = false;
  110. /// The minimum hotness value a diagnostic needs in order to be included in
  111. /// optimization diagnostics.
  112. ///
  113. /// The threshold is an Optional value, which maps to one of the 3 states:
  114. /// 1. 0 => threshold disabled. All emarks will be printed.
  115. /// 2. positive int => manual threshold by user. Remarks with hotness exceed
  116. /// threshold will be printed.
  117. /// 3. None => 'auto' threshold by user. The actual value is not
  118. /// available at command line, but will be synced with
  119. /// hotness threhold from profile summary during
  120. /// compilation.
  121. ///
  122. /// If threshold option is not specified, it is disabled by default.
  123. llvm::Optional<uint64_t> RemarksHotnessThreshold = 0;
  124. /// The format used for serializing remarks (default: YAML).
  125. std::string RemarksFormat;
  126. /// Whether to emit the pass manager debuggging informations.
  127. bool DebugPassManager = false;
  128. /// Statistics output file path.
  129. std::string StatsFile;
  130. /// Specific thinLTO modules to compile.
  131. std::vector<std::string> ThinLTOModulesToCompile;
  132. /// Time trace enabled.
  133. bool TimeTraceEnabled = false;
  134. /// Time trace granularity.
  135. unsigned TimeTraceGranularity = 500;
  136. bool ShouldDiscardValueNames = true;
  137. DiagnosticHandlerFunction DiagHandler;
  138. /// Add FSAFDO discriminators.
  139. bool AddFSDiscriminator = false;
  140. /// If this field is set, LTO will write input file paths and symbol
  141. /// resolutions here in llvm-lto2 command line flag format. This can be
  142. /// used for testing and for running the LTO pipeline outside of the linker
  143. /// with llvm-lto2.
  144. std::unique_ptr<raw_ostream> ResolutionFile;
  145. /// Tunable parameters for passes in the default pipelines.
  146. PipelineTuningOptions PTO;
  147. /// The following callbacks deal with tasks, which normally represent the
  148. /// entire optimization and code generation pipeline for what will become a
  149. /// single native object file. Each task has a unique identifier between 0 and
  150. /// getMaxTasks()-1, which is supplied to the callback via the Task parameter.
  151. /// A task represents the entire pipeline for ThinLTO and regular
  152. /// (non-parallel) LTO, but a parallel code generation task will be split into
  153. /// N tasks before code generation, where N is the parallelism level.
  154. ///
  155. /// LTO may decide to stop processing a task at any time, for example if the
  156. /// module is empty or if a module hook (see below) returns false. For this
  157. /// reason, the client should not expect to receive exactly getMaxTasks()
  158. /// native object files.
  159. /// A module hook may be used by a linker to perform actions during the LTO
  160. /// pipeline. For example, a linker may use this function to implement
  161. /// -save-temps. If this function returns false, any further processing for
  162. /// that task is aborted.
  163. ///
  164. /// Module hooks must be thread safe with respect to the linker's internal
  165. /// data structures. A module hook will never be called concurrently from
  166. /// multiple threads with the same task ID, or the same module.
  167. ///
  168. /// Note that in out-of-process backend scenarios, none of the hooks will be
  169. /// called for ThinLTO tasks.
  170. using ModuleHookFn = std::function<bool(unsigned Task, const Module &)>;
  171. /// This module hook is called after linking (regular LTO) or loading
  172. /// (ThinLTO) the module, before modifying it.
  173. ModuleHookFn PreOptModuleHook;
  174. /// This hook is called after promoting any internal functions
  175. /// (ThinLTO-specific).
  176. ModuleHookFn PostPromoteModuleHook;
  177. /// This hook is called after internalizing the module.
  178. ModuleHookFn PostInternalizeModuleHook;
  179. /// This hook is called after importing from other modules (ThinLTO-specific).
  180. ModuleHookFn PostImportModuleHook;
  181. /// This module hook is called after optimization is complete.
  182. ModuleHookFn PostOptModuleHook;
  183. /// This module hook is called before code generation. It is similar to the
  184. /// PostOptModuleHook, but for parallel code generation it is called after
  185. /// splitting the module.
  186. ModuleHookFn PreCodeGenModuleHook;
  187. /// A combined index hook is called after all per-module indexes have been
  188. /// combined (ThinLTO-specific). It can be used to implement -save-temps for
  189. /// the combined index.
  190. ///
  191. /// If this function returns false, any further processing for ThinLTO tasks
  192. /// is aborted.
  193. ///
  194. /// It is called regardless of whether the backend is in-process, although it
  195. /// is not called from individual backend processes.
  196. using CombinedIndexHookFn = std::function<bool(
  197. const ModuleSummaryIndex &Index,
  198. const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols)>;
  199. CombinedIndexHookFn CombinedIndexHook;
  200. /// This is a convenience function that configures this Config object to write
  201. /// temporary files named after the given OutputFileName for each of the LTO
  202. /// phases to disk. A client can use this function to implement -save-temps.
  203. ///
  204. /// FIXME: Temporary files derived from ThinLTO backends are currently named
  205. /// after the input file name, rather than the output file name, when
  206. /// UseInputModulePath is set to true.
  207. ///
  208. /// Specifically, it (1) sets each of the above module hooks and the combined
  209. /// index hook to a function that calls the hook function (if any) that was
  210. /// present in the appropriate field when the addSaveTemps function was
  211. /// called, and writes the module to a bitcode file with a name prefixed by
  212. /// the given output file name, and (2) creates a resolution file whose name
  213. /// is prefixed by the given output file name and sets ResolutionFile to its
  214. /// file handle.
  215. Error addSaveTemps(std::string OutputFileName,
  216. bool UseInputModulePath = false);
  217. };
  218. struct LTOLLVMDiagnosticHandler : public DiagnosticHandler {
  219. DiagnosticHandlerFunction *Fn;
  220. LTOLLVMDiagnosticHandler(DiagnosticHandlerFunction *DiagHandlerFn)
  221. : Fn(DiagHandlerFn) {}
  222. bool handleDiagnostics(const DiagnosticInfo &DI) override {
  223. (*Fn)(DI);
  224. return true;
  225. }
  226. };
  227. /// A derived class of LLVMContext that initializes itself according to a given
  228. /// Config object. The purpose of this class is to tie ownership of the
  229. /// diagnostic handler to the context, as opposed to the Config object (which
  230. /// may be ephemeral).
  231. // FIXME: This should not be required as diagnostic handler is not callback.
  232. struct LTOLLVMContext : LLVMContext {
  233. LTOLLVMContext(const Config &C) : DiagHandler(C.DiagHandler) {
  234. setDiscardValueNames(C.ShouldDiscardValueNames);
  235. enableDebugTypeODRUniquing();
  236. setDiagnosticHandler(
  237. std::make_unique<LTOLLVMDiagnosticHandler>(&DiagHandler), true);
  238. }
  239. DiagnosticHandlerFunction DiagHandler;
  240. };
  241. }
  242. }
  243. #endif