MLIR 24.0.0git
MlirOptMain.h
Go to the documentation of this file.
1//===- MlirOptMain.h - MLIR Optimizer Driver main ---------------*- 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// Main entry function for mlir-opt for when built as standalone binary.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef MLIR_TOOLS_MLIROPT_MLIROPTMAIN_H
14#define MLIR_TOOLS_MLIROPT_MLIROPTMAIN_H
15
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/StringRef.h"
20
21#include <cstdlib>
22#include <functional>
23#include <memory>
24
25namespace llvm {
26class raw_ostream;
27class MemoryBuffer;
28} // namespace llvm
29
30namespace mlir {
31class DialectRegistry;
33class PassManager;
34
35/// enum class to indicate the verbosity level of the diagnostic filter.
41
47
52
53/// Configuration options for the mlir-opt tool.
54/// This is intended to help building tools like mlir-opt by collecting the
55/// supported options.
56/// The API is fluent, and the options are sorted in alphabetical order below.
57/// The options can be exposed to the LLVM command line by registering them
58/// with `MlirOptMainConfig::registerCLOptions(DialectRegistry &);` and creating
59/// a config using `auto config = MlirOptMainConfig::createFromCLOptions();`.
61public:
62 /// Register the options as global LLVM command line options.
63 static void registerCLOptions(DialectRegistry &dialectRegistry);
64
65 /// Create a new config with the default set from the CL options.
67
68 ///
69 /// Options.
70 ///
71
72 /// Allow operation with no registered dialects.
73 /// This option is for convenience during testing only and discouraged in
74 /// general.
77 return *this;
78 }
82
83 /// Set the debug configuration to use.
85 debugConfig = std::move(config);
86 return *this;
87 }
90
91 /// Print the pass-pipeline as text before executing.
94 return *this;
95 }
96
100
102
103 /// Set the output format to bytecode instead of textual IR.
106 return *this;
107 }
108 bool shouldEmitBytecode() const { return emitBytecodeFlag; }
109
113
115
116 /// Set the IRDL file to load before processing the input.
118 irdlFileFlag = file;
119 return *this;
120 }
121 StringRef getIrdlFile() const { return irdlFileFlag; }
122
123 /// Set the bytecode version to emit.
125 emitBytecodeVersion = version;
126 return *this;
127 }
128 std::optional<int64_t> bytecodeVersionToEmit() const {
129 return emitBytecodeVersion;
130 }
131
132 /// Set target dialect versions as strings of the form "dialect=version".
133 /// The dialect defines the syntax of its version string.
136 emitBytecodeDialectVersions.assign(versions.begin(), versions.end());
137 return *this;
138 }
142
143 /// Set the bytecode producer to use.
145 emitBytecodeProducerFlag = producer.str();
146 return *this;
147 }
148 std::optional<StringRef> bytecodeProducerToEmit() const {
149 if (emitBytecodeProducerFlag.empty())
150 return std::nullopt;
152 }
153
154 /// Set the callback to populate the pass manager.
156 setPassPipelineSetupFn(std::function<LogicalResult(PassManager &)> callback) {
157 passPipelineCallback = std::move(callback);
158 return *this;
159 }
160
161 /// Set the parser to use to populate the pass manager.
163
164 /// Populate the passmanager, if any callback was set.
165 LogicalResult setupPassPipeline(PassManager &pm) const {
167 return passPipelineCallback(pm);
168 return success();
169 }
170
171 /// List the registered passes and return.
173 listPassesFlag = list;
174 return *this;
175 }
176 bool shouldListPasses() const { return listPassesFlag; }
177
178 /// Enable running the reproducer information stored in resources (if
179 /// present).
180 MlirOptMainConfig &runReproducer(bool enableReproducer) {
181 runReproducerFlag = enableReproducer;
182 return *this;
183 };
184
185 /// Return true if the reproducer should be run.
186 bool shouldRunReproducer() const { return runReproducerFlag; }
187
188 /// Show the registered dialects before trying to load the input file.
190 showDialectsFlag = show;
191 return *this;
192 }
193 bool shouldShowDialects() const { return showDialectsFlag; }
194
195 /// Set the marker on which to split the input into chunks and process each
196 /// chunk independently. Input is not split if empty.
198 splitInputFile(std::string splitMarker = kDefaultSplitMarker) {
199 splitInputFileFlag = std::move(splitMarker);
200 return *this;
201 }
202 StringRef inputSplitMarker() const { return splitInputFileFlag; }
203
204 /// Set whether to merge the output chunks into one file using the given
205 /// marker.
207 outputSplitMarker(std::string splitMarker = kDefaultSplitMarker) {
208 outputSplitMarkerFlag = std::move(splitMarker);
209 return *this;
210 }
211 StringRef outputSplitMarker() const { return outputSplitMarkerFlag; }
212
213 /// Disable implicit addition of a top-level module op during parsing.
219
220 /// Set whether to check that emitted diagnostics match `expected-*` lines on
221 /// the corresponding line. This is meant for implementing diagnostic tests.
227
232
236
237 /// Set whether to run the verifier after each transformation pass.
240 return *this;
241 }
242 bool shouldVerifyPasses() const { return verifyPassesFlag; }
243
244 /// Set whether to run the verifier on parsing.
250
251 /// Set whether to run the verifier after each transformation pass.
254 return *this;
255 }
257
258 /// Checks if any remark filters are set.
259 bool shouldEmitRemarks() const {
260 // Emit all remarks only when no filters are specified.
261 const bool hasFilters =
262 !getRemarksAllFilter().empty() || !getRemarksPassedFilter().empty() ||
263 !getRemarksFailedFilter().empty() ||
264 !getRemarksMissedFilter().empty() || !getRemarksAnalyseFilter().empty();
265 return hasFilters;
266 }
267
268 /// Reproducer file generation (no crash required).
270
271 /// Set the reproducer output filename
273 /// Set the remark policy to use.
275 /// Set the remark format to use.
276 std::string getRemarksAllFilter() const { return remarksAllFilterFlag; }
277 /// Set the remark output file.
278 std::string getRemarksOutputFile() const { return remarksOutputFileFlag; }
279 /// Set the remark passed filters.
280 std::string getRemarksPassedFilter() const { return remarksPassedFilterFlag; }
281 /// Set the remark failed filters.
282 std::string getRemarksFailedFilter() const { return remarksFailedFilterFlag; }
283 /// Set the remark missed filters.
284 std::string getRemarksMissedFilter() const { return remarksMissedFilterFlag; }
285 /// Set the remark analyse filters.
286 std::string getRemarksAnalyseFilter() const {
288 }
289
290protected:
291 /// Allow operation with no registered dialects.
292 /// This option is for convenience during testing only and discouraged in
293 /// general.
295
296 /// Remark format
298 /// Remark policy
300 /// Remark file to output to
301 std::string remarksOutputFileFlag = "";
302 /// Remark filters
303 std::string remarksAllFilterFlag = "";
304 std::string remarksPassedFilterFlag = "";
305 std::string remarksFailedFilterFlag = "";
306 std::string remarksMissedFilterFlag = "";
307 std::string remarksAnalyseFilterFlag = "";
308
309 /// Configuration for the debugging hooks.
311
312 /// Verbosity level of diagnostic information. 0: Errors only,
313 /// 1: Errors and warnings, 2: Errors, warnings and remarks.
316
317 /// Print the pipeline that will be run.
319
320 /// Emit bytecode instead of textual assembly when generating output.
321 bool emitBytecodeFlag = false;
322
323 /// Elide resources when generating bytecode.
325
326 /// IRDL file to register before processing the input.
327 std::string irdlFileFlag = "";
328
329 /// Location Breakpoints to filter the action logging.
330 std::vector<tracing::BreakpointManager *> logActionLocationFilter;
331
332 /// Emit bytecode at given version.
333 std::optional<int64_t> emitBytecodeVersion = std::nullopt;
334
335 /// Target dialect versions for bytecode emission, as "dialect=version".
336 std::vector<std::string> emitBytecodeDialectVersions;
337
338 /// Emit bytecode with given producer.
339 std::string emitBytecodeProducerFlag = "";
340
341 /// The callback to populate the pass manager.
342 std::function<LogicalResult(PassManager &)> passPipelineCallback;
343
344 /// List the registered passes and return.
345 bool listPassesFlag = false;
346
347 /// Enable running the reproducer.
348 bool runReproducerFlag = false;
349
350 /// Show the registered dialects before trying to load the input file.
351 bool showDialectsFlag = false;
352
353 /// Show the notes in diagnostic information. Notes can be included in
354 /// any diagnostic information, so it is not specified in the verbosity
355 /// level.
357
358 /// Split the input file based on the given marker into chunks and process
359 /// each chunk independently. Input is not split if empty.
360 std::string splitInputFileFlag = "";
361
362 /// Merge output chunks into one file using the given marker.
363 std::string outputSplitMarkerFlag = "";
364
365 /// Use an explicit top-level module op during parsing.
367
368 /// Set whether to check that emitted diagnostics match `expected-*` lines on
369 /// the corresponding line. This is meant for implementing diagnostic tests.
372
373 /// Run the verifier after each transformation pass.
374 bool verifyPassesFlag = true;
375
376 /// Disable the verifier on parsing.
378
379 /// Verify that the input IR round-trips perfectly.
381
382 /// The reproducer output filename (no crash required).
384};
385
386/// This defines the function type used to setup the pass manager. This can be
387/// used to pass in a callback to setup a default pass pipeline to be applied on
388/// the loaded IR.
390
391/// Register basic command line options.
392/// - toolName is used for the header displayed by `--help`.
393/// - registry should contain all the dialects that can be parsed in the source.
394/// - return std::string for help header.
395std::string registerCLIOptions(llvm::StringRef toolName,
396 DialectRegistry &registry);
397
398/// Parse command line options.
399/// - helpHeader is used for the header displayed by `--help`.
400/// - return std::pair<std::string, std::string> for
401/// inputFilename and outputFilename command line option values.
402std::pair<std::string, std::string> parseCLIOptions(int argc, char **argv,
403 llvm::StringRef helpHeader);
404
405/// Register and parse command line options.
406/// - toolName is used for the header displayed by `--help`.
407/// - registry should contain all the dialects that can be parsed in the source.
408/// - return std::pair<std::string, std::string> for
409/// inputFilename and outputFilename command line option values.
410std::pair<std::string, std::string>
411registerAndParseCLIOptions(int argc, char **argv, llvm::StringRef toolName,
412 DialectRegistry &registry);
413
414/// Perform the core processing behind `mlir-opt`.
415/// - outputStream is the stream where the resulting IR is printed.
416/// - buffer is the in-memory file to parser and process.
417/// - registry should contain all the dialects that can be parsed in the source.
418/// - config contains the configuration options for the tool.
419LogicalResult MlirOptMain(llvm::raw_ostream &outputStream,
420 std::unique_ptr<llvm::MemoryBuffer> buffer,
421 DialectRegistry &registry,
422 const MlirOptMainConfig &config);
423
424/// Implementation for tools like `mlir-opt`.
425/// - toolName is used for the header displayed by `--help`.
426/// - registry should contain all the dialects that can be parsed in the source.
427LogicalResult MlirOptMain(int argc, char **argv, llvm::StringRef toolName,
428 DialectRegistry &registry);
429
430/// Implementation for tools like `mlir-opt`.
431/// This function can be used with registerAndParseCLIOptions so that
432/// CLI options can be accessed before running MlirOptMain.
433/// - inputFilename is the name of the input mlir file.
434/// - outputFilename is the name of the output file.
435/// - registry should contain all the dialects that can be parsed in the source.
436LogicalResult MlirOptMain(int argc, char **argv, llvm::StringRef inputFilename,
437 llvm::StringRef outputFilename,
438 DialectRegistry &registry);
439
440/// Helper wrapper to return the result of MlirOptMain directly from main.
441///
442/// Example:
443///
444/// int main(int argc, char **argv) {
445/// // ...
446/// return mlir::asMainReturnCode(mlir::MlirOptMain(
447/// argc, argv, /* ... */);
448/// }
449///
450inline int asMainReturnCode(LogicalResult r) {
451 return r.succeeded() ? EXIT_SUCCESS : EXIT_FAILURE;
452}
453
454} // namespace mlir
455
456#endif // MLIR_TOOLS_MLIROPT_MLIROPTMAIN_H
return success()
static LogicalResult emit(SolverOp solver, const SMTEmissionOptions &options, mlir::raw_indented_ostream &stream)
Emit the SMT operations in the given 'solver' to the 'stream'.
The DialectRegistry maps a dialect namespace to a constructor for the matching dialect.
Configuration options for the mlir-opt tool.
Definition MlirOptMain.h:60
MlirOptMainConfig & emitBytecode(bool emit)
Set the output format to bytecode instead of textual IR.
std::string getRemarksAnalyseFilter() const
Set the remark analyse filters.
std::string getRemarksMissedFilter() const
Set the remark missed filters.
bool shouldEmitRemarks() const
Checks if any remark filters are set.
static MlirOptMainConfig createFromCLOptions()
Create a new config with the default set from the CL options.
std::string splitInputFileFlag
Split the input file based on the given marker into chunks and process each chunk independently.
MlirOptMainConfig & runReproducer(bool enableReproducer)
Enable running the reproducer information stored in resources (if present).
bool shouldVerifyPasses() const
MlirOptMainConfig & splitInputFile(std::string splitMarker=kDefaultSplitMarker)
Set the marker on which to split the input into chunks and process each chunk independently.
MlirOptMainConfig & setEmitBytecodeDialectVersions(ArrayRef< std::string > versions)
Set target dialect versions as strings of the form "dialect=version".
MlirOptMainConfig & showDialects(bool show)
Show the registered dialects before trying to load the input file.
MlirOptMainConfig & allowUnregisteredDialects(bool allow)
Options.
Definition MlirOptMain.h:75
MlirOptMainConfig & verifyOnParsing(bool verify)
Set whether to run the verifier on parsing.
StringRef inputSplitMarker() const
MlirOptMainConfig & outputSplitMarker(std::string splitMarker=kDefaultSplitMarker)
Set whether to merge the output chunks into one file using the given marker.
MlirOptMainConfig & verifyDiagnostics(SourceMgrDiagnosticVerifierHandler::Level verify)
Set whether to check that emitted diagnostics match expected-* lines on the corresponding line.
bool shouldVerifyRoundtrip() const
SourceMgrDiagnosticVerifierHandler::Level verifyDiagnosticsLevel() const
bool shouldShowNotes() const
bool disableVerifierOnParsingFlag
Disable the verifier on parsing.
MlirOptMainConfig & verifyRoundtrip(bool verify)
Set whether to run the verifier after each transformation pass.
std::optional< int64_t > emitBytecodeVersion
Emit bytecode at given version.
StringRef getReproducerFilename() const
Reproducer file generation (no crash required).
std::string irdlFileFlag
IRDL file to register before processing the input.
VerbosityLevel diagnosticVerbosityLevelFlag
Verbosity level of diagnostic information.
std::vector< tracing::BreakpointManager * > logActionLocationFilter
Location Breakpoints to filter the action logging.
bool emitBytecodeFlag
Emit bytecode instead of textual assembly when generating output.
std::string getRemarksOutputFile() const
Set the remark output file.
bool shouldShowDialects() const
MlirOptMainConfig & setEmitBytecodeVersion(int64_t version)
Set the bytecode version to emit.
std::string getRemarksFailedFilter() const
Set the remark failed filters.
bool disableDiagnosticNotesFlag
Show the notes in diagnostic information.
std::string generateReproducerFileFlag
The reproducer output filename (no crash required).
SourceMgrDiagnosticVerifierHandler::Level verifyDiagnosticsFlag
Set whether to check that emitted diagnostics match expected-* lines on the corresponding line.
MlirOptMainConfig & useExplicitModule(bool useExplicitModule)
Disable implicit addition of a top-level module op during parsing.
MlirOptMainConfig & setPassPipelineSetupFn(std::function< LogicalResult(PassManager &)> callback)
Set the callback to populate the pass manager.
std::function< LogicalResult(PassManager &)> passPipelineCallback
The callback to populate the pass manager.
bool dumpPassPipelineFlag
Print the pipeline that will be run.
const tracing::DebugConfig & getDebugConfig() const
Definition MlirOptMain.h:89
bool verifyPassesFlag
Run the verifier after each transformation pass.
std::string remarksOutputFileFlag
Remark file to output to.
bool shouldVerifyOnParsing() const
std::string getRemarksAllFilter() const
Set the remark format to use.
MlirOptMainConfig & emitBytecodeProducer(StringRef producer)
Set the bytecode producer to use.
RemarkPolicy getRemarkPolicy() const
Set the remark policy to use.
bool shouldElideResourceDataFromBytecode() const
bool shouldEmitBytecode() const
tracing::DebugConfig debugConfig
Configuration for the debugging hooks.
RemarkFormat remarkFormatFlag
Remark format.
MlirOptMainConfig & dumpPassPipeline(bool dump)
Print the pass-pipeline as text before executing.
Definition MlirOptMain.h:92
MlirOptMainConfig & verifyPasses(bool verify)
Set whether to run the verifier after each transformation pass.
std::string emitBytecodeProducerFlag
Emit bytecode with given producer.
StringRef outputSplitMarker() const
RemarkFormat getRemarkFormat() const
Set the reproducer output filename.
MlirOptMainConfig & setIrdlFile(StringRef file)
Set the IRDL file to load before processing the input.
bool runReproducerFlag
Enable running the reproducer.
RemarkPolicy remarkPolicyFlag
Remark policy.
std::string remarksAllFilterFlag
Remark filters.
bool verifyRoundtripFlag
Verify that the input IR round-trips perfectly.
std::string remarksPassedFilterFlag
ArrayRef< std::string > bytecodeDialectVersionsToEmit() const
std::optional< StringRef > bytecodeProducerToEmit() const
bool allowUnregisteredDialectsFlag
Allow operation with no registered dialects.
MlirOptMainConfig & listPasses(bool list)
List the registered passes and return.
LogicalResult setupPassPipeline(PassManager &pm) const
Populate the passmanager, if any callback was set.
std::string remarksAnalyseFilterFlag
static void registerCLOptions(DialectRegistry &dialectRegistry)
Register the options as global LLVM command line options.
bool shouldAllowUnregisteredDialects() const
Definition MlirOptMain.h:79
bool shouldUseExplicitModule() const
VerbosityLevel getDiagnosticVerbosityLevel() const
Definition MlirOptMain.h:97
bool shouldRunReproducer() const
Return true if the reproducer should be run.
bool elideResourceDataFromBytecodeFlag
Elide resources when generating bytecode.
std::optional< int64_t > bytecodeVersionToEmit() const
std::string remarksFailedFilterFlag
bool shouldDumpPassPipeline() const
bool shouldVerifyDiagnostics() const
bool useExplicitModuleFlag
Use an explicit top-level module op during parsing.
std::string remarksMissedFilterFlag
tracing::DebugConfig & getDebugConfig()
Definition MlirOptMain.h:88
std::string getRemarksPassedFilter() const
Set the remark passed filters.
bool shouldListPasses() const
bool showDialectsFlag
Show the registered dialects before trying to load the input file.
StringRef getIrdlFile() const
MlirOptMainConfig & setDebugConfig(tracing::DebugConfig config)
Set the debug configuration to use.
Definition MlirOptMain.h:84
std::vector< std::string > emitBytecodeDialectVersions
Target dialect versions for bytecode emission, as "dialect=version".
bool listPassesFlag
List the registered passes and return.
std::string outputSplitMarkerFlag
Merge output chunks into one file using the given marker.
MlirOptMainConfig & setPassPipelineParser(const PassPipelineCLParser &parser)
Set the parser to use to populate the pass manager.
The main pass manager and pipeline builder.
This class implements a command-line parser for MLIR passes.
The OpAsmOpInterface, see OpAsmInterface.td for more details.
Definition CallGraph.h:227
Include the generated interface declarations.
std::pair< std::string, std::string > parseCLIOptions(int argc, char **argv, llvm::StringRef helpHeader)
Parse command line options.
const char *const kDefaultSplitMarker
int asMainReturnCode(LogicalResult r)
Helper wrapper to return the result of MlirOptMain directly from main.
std::string registerCLIOptions(llvm::StringRef toolName, DialectRegistry &registry)
Register basic command line options.
LogicalResult MlirOptMain(llvm::raw_ostream &outputStream, std::unique_ptr< llvm::MemoryBuffer > buffer, DialectRegistry &registry, const MlirOptMainConfig &config)
Perform the core processing behind mlir-opt.
llvm::function_ref< LogicalResult(PassManager &pm)> PassPipelineFn
This defines the function type used to setup the pass manager.
RemarkPolicy
Definition MlirOptMain.h:48
RemarkFormat
Definition MlirOptMain.h:42
std::pair< std::string, std::string > registerAndParseCLIOptions(int argc, char **argv, llvm::StringRef toolName, DialectRegistry &registry)
Register and parse command line options.
VerbosityLevel
enum class to indicate the verbosity level of the diagnostic filter.
Definition MlirOptMain.h:36
LogicalResult verify(Operation *op, bool verifyRecursively=true)
Perform (potentially expensive) checks of invariants, used to detect compiler bugs,...
Definition Verifier.cpp:566