LLVM 24.0.0git
Config.h
Go to the documentation of this file.
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
14#ifndef LLVM_LTO_CONFIG_H
15#define LLVM_LTO_CONFIG_H
16
17#include "llvm/ADT/DenseSet.h"
18#include "llvm/Config/llvm-config.h"
20#include "llvm/IR/GlobalValue.h"
21#include "llvm/IR/LLVMContext.h"
28
29#include <functional>
30#include <optional>
31
32namespace llvm {
33
34class Error;
35class Module;
38class PassPlugin;
39
40namespace lto {
41
42/// LTO configuration. A linker can configure LTO by setting fields in this data
43/// structure and passing it to the lto::LTO constructor.
44struct Config {
49 // The library options of every LLVMContext that LTO creates.
50 // TODO: Make it non-null once every client sets it. Null means the defaults.
52 // Note: when adding fields here, consider whether they need to be added to
53 // computeLTOCacheKey in LTO.cpp.
54 std::string CPU;
56 std::vector<std::string> MAttrs;
57 std::vector<std::string> MllvmArgs;
58 // Pass-plugins already loaded by the client. LTO does not take ownership, so
59 // they must outlive the lto::LTO object.
60 std::vector<llvm::PassPlugin *> LoadedPassPlugins;
61 // Plugins that are passed by filename are loaded in lto::LTO::run(). Clients
62 // that call lto::backend(), lto::thinBackend() or lto::opt() directly must
63 // use LoadedPassPlugins.
64 std::vector<std::string> PassPluginFilenames;
65 std::function<void(PassBuilder &)> PassBuilderCallback;
66 std::optional<Reloc::Model> RelocModel = Reloc::PIC_;
67 std::optional<CodeModel::Model> CodeModel;
70 unsigned OptLevel = 2;
71 bool VerifyEach = false;
72 bool DisableVerify = false;
73
74 /// Flag to indicate that the optimizer should not assume builtins are present
75 /// on the target.
76 bool Freestanding = false;
77
78 /// Disable entirely the optimizer, including importing for ThinLTO
79 bool CodeGenOnly = false;
80
81 /// Run PGO context sensitive IR instrumentation.
82 bool RunCSIRInstr = false;
83
84 /// Turn on/off the warning about a hash mismatch in the PGO profile data.
85 bool PGOWarnMismatch = true;
86
87 /// Asserts whether we can assume whole program visibility during the LTO
88 /// link.
90
91 /// We're validating that all native vtables have corresponding type infos.
93 /// If all native vtables have corresponding type infos, allow
94 /// usage of RTTI to block devirtualization on types used in native files.
96
97 /// Always emit a Regular LTO object even when it is empty because no Regular
98 /// LTO modules were linked. This option is useful for some build system which
99 /// want to know a priori all possible output files.
101
102 /// If true, the LTO instance creates copies of the symbol names for LTO::run.
103 /// The lld linker uses string saver to keep symbol names alive and doesn't
104 /// need to create copies, so it can set this field to false.
106
107 /// This flag is used as one of parameters to calculate cache entries and to
108 /// ensure that in-process cache and out-of-process (DTLTO) cache are
109 /// distinguished.
110 mutable bool Dtlto = 0;
111
112 /// Allows non-imported definitions to get the potentially more constraining
113 /// visibility from the prevailing definition. FromPrevailing is the default
114 /// because it works for many binary formats. ELF can use the more optimized
115 /// 'ELF' scheme.
117
118 /// If this field is set, the set of passes run in the middle-end optimizer
119 /// will be the one specified by the string. Only works with the new pass
120 /// manager as the old one doesn't have this ability.
121 std::string OptPipeline;
122
123 // If this field is set, it has the same effect of specifying an AA pipeline
124 // identified by the string. Only works with the new pass manager, in
125 // conjunction OptPipeline.
126 std::string AAPipeline;
127
128 /// Setting this field will replace target triples in input files with this
129 /// triple.
130 std::string OverrideTriple;
131
132 /// Setting this field will replace unspecified target triples in input files
133 /// with this triple.
134 std::string DefaultTriple;
135
136 /// Context Sensitive PGO profile path.
137 std::string CSIRProfile;
138
139 /// Sample PGO profile path.
140 std::string SampleProfile;
141
142 /// Name remapping file for profile data.
143 std::string ProfileRemapping;
144
145 /// The directory to store .dwo files.
146 std::string DwoDir;
147
148 /// The name for the split debug info file used for the DW_AT_[GNU_]dwo_name
149 /// attribute in the skeleton CU. This should generally only be used when
150 /// running an individual backend directly via thinBackend(), as otherwise
151 /// all objects would use the same .dwo file. Not used as output path.
152 std::string SplitDwarfFile;
153
154 /// The path to write a .dwo file to. This should generally only be used when
155 /// running an individual backend directly via thinBackend(), as otherwise
156 /// all .dwo files will be written to the same path. Not used in skeleton CU.
157 std::string SplitDwarfOutput;
158
159 /// Optimization remarks file path.
160 std::string RemarksFilename;
161
162 /// Optimization remarks pass filter.
163 std::string RemarksPasses;
164
165 /// Whether to emit optimization remarks with hotness informations.
166 bool RemarksWithHotness = false;
167
168 /// The minimum hotness value a diagnostic needs in order to be included in
169 /// optimization diagnostics.
170 ///
171 /// The threshold is an Optional value, which maps to one of the 3 states:
172 /// 1. 0 => threshold disabled. All emarks will be printed.
173 /// 2. positive int => manual threshold by user. Remarks with hotness exceed
174 /// threshold will be printed.
175 /// 3. None => 'auto' threshold by user. The actual value is not
176 /// available at command line, but will be synced with
177 /// hotness threhold from profile summary during
178 /// compilation.
179 ///
180 /// If threshold option is not specified, it is disabled by default.
181 std::optional<uint64_t> RemarksHotnessThreshold = 0;
182
183 /// The format used for serializing remarks (default: YAML).
184 std::string RemarksFormat;
185
186 /// Whether to emit the pass manager debuggging informations.
187 bool DebugPassManager = false;
188
189 /// Statistics output file path.
190 std::string StatsFile;
191
192 /// Specific thinLTO modules to compile.
193 std::vector<std::string> ThinLTOModulesToCompile;
194
195 /// Time trace enabled.
196 bool TimeTraceEnabled = false;
197
198 /// Time trace granularity.
199 unsigned TimeTraceGranularity = 500;
200
203
204 /// Add FSAFDO discriminators.
205 bool AddFSDiscriminator = false;
206
207 /// If this field is set, LTO will write input file paths and symbol
208 /// resolutions here in llvm-lto2 command line flag format. This can be
209 /// used for testing and for running the LTO pipeline outside of the linker
210 /// with llvm-lto2.
211 std::unique_ptr<raw_ostream> ResolutionFile;
212
213 /// Tunable parameters for passes in the default pipelines.
215
216 /// The following callbacks deal with tasks, which normally represent the
217 /// entire optimization and code generation pipeline for what will become a
218 /// single native object file. Each task has a unique identifier between 0 and
219 /// getMaxTasks()-1, which is supplied to the callback via the Task parameter.
220 /// A task represents the entire pipeline for ThinLTO and regular
221 /// (non-parallel) LTO, but a parallel code generation task will be split into
222 /// N tasks before code generation, where N is the parallelism level.
223 ///
224 /// LTO may decide to stop processing a task at any time, for example if the
225 /// module is empty or if a module hook (see below) returns false. For this
226 /// reason, the client should not expect to receive exactly getMaxTasks()
227 /// native object files.
228
229 /// A module hook may be used by a linker to perform actions during the LTO
230 /// pipeline. For example, a linker may use this function to implement
231 /// -save-temps. If this function returns false, any further processing for
232 /// that task is aborted.
233 ///
234 /// Module hooks must be thread safe with respect to the linker's internal
235 /// data structures. A module hook will never be called concurrently from
236 /// multiple threads with the same task ID, or the same module.
237 ///
238 /// Note that in out-of-process backend scenarios, none of the hooks will be
239 /// called for ThinLTO tasks.
240 using ModuleHookFn = std::function<bool(unsigned Task, const Module &)>;
241
242 /// This module hook is called after linking (regular LTO) or loading
243 /// (ThinLTO) the module, before modifying it.
245
246 /// This hook is called after promoting any internal functions
247 /// (ThinLTO-specific).
249
250 /// This hook is called after internalizing the module.
252
253 /// This hook is called after importing from other modules (ThinLTO-specific).
255
256 /// This module hook is called after optimization is complete.
258
259 /// This module hook is called before code generation. It is similar to the
260 /// PostOptModuleHook, but for parallel code generation it is called after
261 /// splitting the module.
263
264 /// A combined index hook is called after all per-module indexes have been
265 /// combined (ThinLTO-specific). It can be used to implement -save-temps for
266 /// the combined index.
267 ///
268 /// If this function returns false, any further processing for ThinLTO tasks
269 /// is aborted.
270 ///
271 /// It is called regardless of whether the backend is in-process, although it
272 /// is not called from individual backend processes.
273 using CombinedIndexHookFn = std::function<bool(
274 const ModuleSummaryIndex &Index,
275 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols)>;
277
278 /// This hook is called after regular LTO modules with summaries (e.g., split
279 /// LTO units) have been linked into the combined module, before optimizing
280 /// the combined module or running ThinLTO.
281 using PostRegularLTOLinkHookFn = std::function<void()>;
283
284 /// This is a convenience function that configures this Config object to write
285 /// temporary files named after the given OutputFileName for each of the LTO
286 /// phases to disk. A client can use this function to implement -save-temps.
287 ///
288 /// FIXME: Temporary files derived from ThinLTO backends are currently named
289 /// after the input file name, rather than the output file name, when
290 /// UseInputModulePath is set to true.
291 ///
292 /// Specifically, it (1) sets each of the above module hooks and the combined
293 /// index hook to a function that calls the hook function (if any) that was
294 /// present in the appropriate field when the addSaveTemps function was
295 /// called, and writes the module to a bitcode file with a name prefixed by
296 /// the given output file name, and (2) creates a resolution file whose name
297 /// is prefixed by the given output file name and sets ResolutionFile to its
298 /// file handle.
299 ///
300 /// SaveTempsArgs can be specified to select which temps to save.
301 /// If SaveTempsArgs is not provided, all temps are saved.
302 LLVM_ABI Error addSaveTemps(std::string OutputFileName,
303 bool UseInputModulePath = false,
304 const DenseSet<StringRef> &SaveTempsArgs = {});
305
306 /// Called by WriteIndexesThinBackend when it needs to write a bitcode
307 /// module's summary index. The callback should return a stream to write
308 /// the index into. If not set, the backend falls back
309 /// to writing the summary index to a file.
310 std::function<std::unique_ptr<raw_pwrite_stream>(size_t Task)>
312 /// Called by WriteIndexesThinBackend when it needs to store a bitcode
313 /// module's imports list. The callback should return a vector that the
314 /// backend will populate with the imported module paths. If not set, the
315 /// backend writes the imports list to a file instead.
316 std::function<std::vector<std::string> &(size_t Task)>
318 /// Called by WriteIndexesThinBackend when it needs to store a bitcode
319 /// module's cache key. The callback should return a string that the backend
320 /// will fill with the computed cache key. If not set, the cache key is
321 /// discarded.
322 std::function<std::string &(size_t Task)> GetCacheKeyOutputString;
323};
324
328 : Fn(DiagHandlerFn) {}
329 bool handleDiagnostics(const DiagnosticInfo &DI) override {
330 (*Fn)(DI);
331 return true;
332 }
333};
334/// A derived class of LLVMContext that initializes itself according to a given
335/// Config object. The purpose of this class is to tie ownership of the
336/// diagnostic handler to the context, as opposed to the Config object (which
337/// may be ephemeral).
338// FIXME: This should not be required as diagnostic handler is not callback.
340
342 setDiscardValueNames(C.ShouldDiscardValueNames);
345 std::make_unique<LTOLLVMDiagnosticHandler>(&DiagHandler), true);
346 if (C.LibraryOptions)
347 getLibraryOptions().assign(*C.LibraryOptions);
348 }
350};
351
352}
353}
354
355#endif
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
#define LLVM_ABI
Definition Compiler.h:211
This file defines the DenseSet and SmallDenseSet classes.
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
This is the base abstract class for diagnostic reporting in the backend.
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
LLVM_ABI void enableDebugTypeODRUniquing()
LLVM_ABI LLVMContext()
LLVM_ABI cl::LibraryOptionsContext & getLibraryOptions() const
The library options this context reads in place of their process-wide values.
LLVM_ABI void setDiscardValueNames(bool Discard)
Set the Context runtime configuration to discard all value name (but GlobalValue).
LLVM_ABI void setDiagnosticHandler(std::unique_ptr< DiagnosticHandler > &&DH, bool RespectFilters=false)
setDiagnosticHandler - This method sets unique_ptr to object of DiagnosticHandler to provide custom d...
Class to hold module path string table and global value map, and encapsulate methods for operating on...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
This class provides access to building LLVM's passes.
A loaded pass plugin.
Definition PassPlugin.h:97
Tunable parameters for passes in the default pipelines.
Definition PassBuilder.h:48
void assign(const LibraryOptionsContext &Other)
An abstract base class for streams implementations that also support a pwrite operation.
Interfaces for registering analysis passes, producing common pass manager configurations,...
This is an optimization pass for GlobalISel generic memory operations.
std::function< void(const DiagnosticInfo &)> DiagnosticHandlerFunction
CodeGenFileType
These enums are meant to be passed into addPassesToEmitFile to indicate what type of file to emit,...
Definition CodeGen.h:309
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:280
@ Default
-O2, -Os, -Oz
Definition CodeGen.h:283
DiagnosticHandler(void *DiagContext=nullptr)
LTO configuration.
Definition Config.h:44
DiagnosticHandlerFunction DiagHandler
Definition Config.h:202
bool HasWholeProgramVisibility
Asserts whether we can assume whole program visibility during the LTO link.
Definition Config.h:89
bool ValidateAllVtablesHaveTypeInfos
We're validating that all native vtables have corresponding type infos.
Definition Config.h:92
std::function< std::string &(size_t Task)> GetCacheKeyOutputString
Called by WriteIndexesThinBackend when it needs to store a bitcode module's cache key.
Definition Config.h:322
bool KeepSymbolNameCopies
If true, the LTO instance creates copies of the symbol names for LTO::run.
Definition Config.h:105
std::function< bool(unsigned Task, const Module &)> ModuleHookFn
The following callbacks deal with tasks, which normally represent the entire optimization and code ge...
Definition Config.h:240
PostRegularLTOLinkHookFn PostRegularLTOLinkHook
Definition Config.h:282
bool DebugPassManager
Whether to emit the pass manager debuggging informations.
Definition Config.h:187
bool AddFSDiscriminator
Add FSAFDO discriminators.
Definition Config.h:205
std::function< std::vector< std::string > &(size_t Task)> GetImportsListOutputArray
Called by WriteIndexesThinBackend when it needs to store a bitcode module's imports list.
Definition Config.h:317
std::optional< uint64_t > RemarksHotnessThreshold
The minimum hotness value a diagnostic needs in order to be included in optimization diagnostics.
Definition Config.h:181
const cl::LibraryOptionsContext * LibraryOptions
Definition Config.h:51
LLVM_ABI Error addSaveTemps(std::string OutputFileName, bool UseInputModulePath=false, const DenseSet< StringRef > &SaveTempsArgs={})
This is a convenience function that configures this Config object to write temporary files named afte...
std::string StatsFile
Statistics output file path.
Definition Config.h:190
ModuleHookFn PreOptModuleHook
This module hook is called after linking (regular LTO) or loading (ThinLTO) the module,...
Definition Config.h:244
CombinedIndexHookFn CombinedIndexHook
Definition Config.h:276
std::optional< CodeModel::Model > CodeModel
Definition Config.h:67
std::string AAPipeline
Definition Config.h:126
bool CodeGenOnly
Disable entirely the optimizer, including importing for ThinLTO.
Definition Config.h:79
bool DisableVerify
Definition Config.h:72
std::vector< std::string > MAttrs
Definition Config.h:56
std::vector< std::string > MllvmArgs
Definition Config.h:57
std::vector< std::string > ThinLTOModulesToCompile
Specific thinLTO modules to compile.
Definition Config.h:193
std::function< void(PassBuilder &)> PassBuilderCallback
Definition Config.h:65
CodeGenOptLevel CGOptLevel
Definition Config.h:68
PipelineTuningOptions PTO
Tunable parameters for passes in the default pipelines.
Definition Config.h:214
std::vector< llvm::PassPlugin * > LoadedPassPlugins
Definition Config.h:60
std::unique_ptr< raw_ostream > ResolutionFile
If this field is set, LTO will write input file paths and symbol resolutions here in llvm-lto2 comman...
Definition Config.h:211
bool Dtlto
This flag is used as one of parameters to calculate cache entries and to ensure that in-process cache...
Definition Config.h:110
std::string DefaultTriple
Setting this field will replace unspecified target triples in input files with this triple.
Definition Config.h:134
bool AlwaysEmitRegularLTOObj
Always emit a Regular LTO object even when it is empty because no Regular LTO modules were linked.
Definition Config.h:100
std::string CPU
Definition Config.h:54
std::string DwoDir
The directory to store .dwo files.
Definition Config.h:146
std::string RemarksFilename
Optimization remarks file path.
Definition Config.h:160
VisScheme VisibilityScheme
Allows non-imported definitions to get the potentially more constraining visibility from the prevaili...
Definition Config.h:116
std::function< void()> PostRegularLTOLinkHookFn
This hook is called after regular LTO modules with summaries (e.g., split LTO units) have been linked...
Definition Config.h:281
std::vector< std::string > PassPluginFilenames
Definition Config.h:64
ModuleHookFn PostPromoteModuleHook
This hook is called after promoting any internal functions (ThinLTO-specific).
Definition Config.h:248
std::string OverrideTriple
Setting this field will replace target triples in input files with this triple.
Definition Config.h:130
std::string ProfileRemapping
Name remapping file for profile data.
Definition Config.h:143
bool AllVtablesHaveTypeInfos
If all native vtables have corresponding type infos, allow usage of RTTI to block devirtualization on...
Definition Config.h:95
TargetOptions Options
Definition Config.h:55
std::string SplitDwarfFile
The name for the split debug info file used for the DW_AT_[GNU_]dwo_name attribute in the skeleton CU...
Definition Config.h:152
std::string SplitDwarfOutput
The path to write a .dwo file to.
Definition Config.h:157
bool TimeTraceEnabled
Time trace enabled.
Definition Config.h:196
ModuleHookFn PostOptModuleHook
This module hook is called after optimization is complete.
Definition Config.h:257
std::function< std::unique_ptr< raw_pwrite_stream >(size_t Task)> GetSummaryIndexOutputStream
Called by WriteIndexesThinBackend when it needs to write a bitcode module's summary index.
Definition Config.h:311
std::string RemarksPasses
Optimization remarks pass filter.
Definition Config.h:163
std::string OptPipeline
If this field is set, the set of passes run in the middle-end optimizer will be the one specified by ...
Definition Config.h:121
bool RunCSIRInstr
Run PGO context sensitive IR instrumentation.
Definition Config.h:82
ModuleHookFn PostInternalizeModuleHook
This hook is called after internalizing the module.
Definition Config.h:251
unsigned TimeTraceGranularity
Time trace granularity.
Definition Config.h:199
unsigned OptLevel
Definition Config.h:70
ModuleHookFn PostImportModuleHook
This hook is called after importing from other modules (ThinLTO-specific).
Definition Config.h:254
bool RemarksWithHotness
Whether to emit optimization remarks with hotness informations.
Definition Config.h:166
std::function< bool( const ModuleSummaryIndex &Index, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols)> CombinedIndexHookFn
A combined index hook is called after all per-module indexes have been combined (ThinLTO-specific).
Definition Config.h:273
std::string CSIRProfile
Context Sensitive PGO profile path.
Definition Config.h:137
ModuleHookFn PreCodeGenModuleHook
This module hook is called before code generation.
Definition Config.h:262
std::optional< Reloc::Model > RelocModel
Definition Config.h:66
bool ShouldDiscardValueNames
Definition Config.h:201
bool PGOWarnMismatch
Turn on/off the warning about a hash mismatch in the PGO profile data.
Definition Config.h:85
CodeGenFileType CGFileType
Definition Config.h:69
bool Freestanding
Flag to indicate that the optimizer should not assume builtins are present on the target.
Definition Config.h:76
std::string SampleProfile
Sample PGO profile path.
Definition Config.h:140
std::string RemarksFormat
The format used for serializing remarks (default: YAML).
Definition Config.h:184
DiagnosticHandlerFunction DiagHandler
Definition Config.h:349
LTOLLVMContext(const Config &C)
Definition Config.h:341
LTOLLVMDiagnosticHandler(DiagnosticHandlerFunction *DiagHandlerFn)
Definition Config.h:327
DiagnosticHandlerFunction * Fn
Definition Config.h:326
bool handleDiagnostics(const DiagnosticInfo &DI) override
Override handleDiagnostics to provide custom implementation.
Definition Config.h:329