Config.h 12 KB

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