MLIR 23.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/StringRef.h"
19
20#include <cstdlib>
21#include <functional>
22#include <memory>
23
24namespace llvm {
25class raw_ostream;
26class MemoryBuffer;
27} // namespace llvm
28
29namespace mlir {
30class DialectRegistry;
32class PassManager;
33
34/// enum class to indicate the verbosity level of the diagnostic filter.
40
46
51
52/// Configuration options for the mlir-opt tool.
53/// This is intended to help building tools like mlir-opt by collecting the
54/// supported options.
55/// The API is fluent, and the options are sorted in alphabetical order below.
56/// The options can be exposed to the LLVM command line by registering them
57/// with `MlirOptMainConfig::registerCLOptions(DialectRegistry &);` and creating
58/// a config using `auto config = MlirOptMainConfig::createFromCLOptions();`.
60public:
61 /// Register the options as global LLVM command line options.
62 static void registerCLOptions(DialectRegistry &dialectRegistry);
63
64 /// Create a new config with the default set from the CL options.
66
67 ///
68 /// Options.
69 ///
70
71 /// Allow operation with no registered dialects.
72 /// This option is for convenience during testing only and discouraged in
73 /// general.
76 return *this;
77 }
81
82 /// Set the debug configuration to use.
84 debugConfig = std::move(config);
85 return *this;
86 }
89
90 /// Print the pass-pipeline as text before executing.
93 return *this;
94 }
95
99
101
102 /// Set the output format to bytecode instead of textual IR.
105 return *this;
106 }
107 bool shouldEmitBytecode() const { return emitBytecodeFlag; }
108
112
114
115 /// Set the IRDL file to load before processing the input.
117 irdlFileFlag = file;
118 return *this;
119 }
120 StringRef getIrdlFile() const { return irdlFileFlag; }
121
122 /// Set the bytecode version to emit.
124 emitBytecodeVersion = version;
125 return *this;
126 }
127 std::optional<int64_t> bytecodeVersionToEmit() const {
128 return emitBytecodeVersion;
129 }
130
131 /// Set the bytecode producer to use.
133 emitBytecodeProducerFlag = producer.str();
134 return *this;
135 }
136 std::optional<StringRef> bytecodeProducerToEmit() const {
137 if (emitBytecodeProducerFlag.empty())
138 return std::nullopt;
140 }
141
142 /// Set the callback to populate the pass manager.
144 setPassPipelineSetupFn(std::function<LogicalResult(PassManager &)> callback) {
145 passPipelineCallback = std::move(callback);
146 return *this;
147 }
148
149 /// Set the parser to use to populate the pass manager.
151
152 /// Populate the passmanager, if any callback was set.
153 LogicalResult setupPassPipeline(PassManager &pm) const {
155 return passPipelineCallback(pm);
156 return success();
157 }
158
159 /// List the registered passes and return.
161 listPassesFlag = list;
162 return *this;
163 }
164 bool shouldListPasses() const { return listPassesFlag; }
165
166 /// Enable running the reproducer information stored in resources (if
167 /// present).
168 MlirOptMainConfig &runReproducer(bool enableReproducer) {
169 runReproducerFlag = enableReproducer;
170 return *this;
171 };
172
173 /// Return true if the reproducer should be run.
174 bool shouldRunReproducer() const { return runReproducerFlag; }
175
176 /// Show the registered dialects before trying to load the input file.
178 showDialectsFlag = show;
179 return *this;
180 }
181 bool shouldShowDialects() const { return showDialectsFlag; }
182
183 /// Set the marker on which to split the input into chunks and process each
184 /// chunk independently. Input is not split if empty.
186 splitInputFile(std::string splitMarker = kDefaultSplitMarker) {
187 splitInputFileFlag = std::move(splitMarker);
188 return *this;
189 }
190 StringRef inputSplitMarker() const { return splitInputFileFlag; }
191
192 /// Set whether to merge the output chunks into one file using the given
193 /// marker.
195 outputSplitMarker(std::string splitMarker = kDefaultSplitMarker) {
196 outputSplitMarkerFlag = std::move(splitMarker);
197 return *this;
198 }
199 StringRef outputSplitMarker() const { return outputSplitMarkerFlag; }
200
201 /// Disable implicit addition of a top-level module op during parsing.
207
208 /// Set whether to check that emitted diagnostics match `expected-*` lines on
209 /// the corresponding line. This is meant for implementing diagnostic tests.
215
220
224
225 /// Set whether to run the verifier after each transformation pass.
228 return *this;
229 }
230 bool shouldVerifyPasses() const { return verifyPassesFlag; }
231
232 /// Set whether to run the verifier on parsing.
238
239 /// Set whether to run the verifier after each transformation pass.
242 return *this;
243 }
245
246 /// Checks if any remark filters are set.
247 bool shouldEmitRemarks() const {
248 // Emit all remarks only when no filters are specified.
249 const bool hasFilters =
250 !getRemarksAllFilter().empty() || !getRemarksPassedFilter().empty() ||
251 !getRemarksFailedFilter().empty() ||
252 !getRemarksMissedFilter().empty() || !getRemarksAnalyseFilter().empty();
253 return hasFilters;
254 }
255
256 /// Reproducer file generation (no crash required).
258
259 /// Set the reproducer output filename
261 /// Set the remark policy to use.
263 /// Set the remark format to use.
264 std::string getRemarksAllFilter() const { return remarksAllFilterFlag; }
265 /// Set the remark output file.
266 std::string getRemarksOutputFile() const { return remarksOutputFileFlag; }
267 /// Set the remark passed filters.
268 std::string getRemarksPassedFilter() const { return remarksPassedFilterFlag; }
269 /// Set the remark failed filters.
270 std::string getRemarksFailedFilter() const { return remarksFailedFilterFlag; }
271 /// Set the remark missed filters.
272 std::string getRemarksMissedFilter() const { return remarksMissedFilterFlag; }
273 /// Set the remark analyse filters.
274 std::string getRemarksAnalyseFilter() const {
276 }
277
278protected:
279 /// Allow operation with no registered dialects.
280 /// This option is for convenience during testing only and discouraged in
281 /// general.
283
284 /// Remark format
286 /// Remark policy
288 /// Remark file to output to
289 std::string remarksOutputFileFlag = "";
290 /// Remark filters
291 std::string remarksAllFilterFlag = "";
292 std::string remarksPassedFilterFlag = "";
293 std::string remarksFailedFilterFlag = "";
294 std::string remarksMissedFilterFlag = "";
295 std::string remarksAnalyseFilterFlag = "";
296
297 /// Configuration for the debugging hooks.
299
300 /// Verbosity level of diagnostic information. 0: Errors only,
301 /// 1: Errors and warnings, 2: Errors, warnings and remarks.
304
305 /// Print the pipeline that will be run.
307
308 /// Emit bytecode instead of textual assembly when generating output.
309 bool emitBytecodeFlag = false;
310
311 /// Elide resources when generating bytecode.
313
314 /// IRDL file to register before processing the input.
315 std::string irdlFileFlag = "";
316
317 /// Location Breakpoints to filter the action logging.
318 std::vector<tracing::BreakpointManager *> logActionLocationFilter;
319
320 /// Emit bytecode at given version.
321 std::optional<int64_t> emitBytecodeVersion = std::nullopt;
322
323 /// Emit bytecode with given producer.
324 std::string emitBytecodeProducerFlag = "";
325
326 /// The callback to populate the pass manager.
327 std::function<LogicalResult(PassManager &)> passPipelineCallback;
328
329 /// List the registered passes and return.
330 bool listPassesFlag = false;
331
332 /// Enable running the reproducer.
333 bool runReproducerFlag = false;
334
335 /// Show the registered dialects before trying to load the input file.
336 bool showDialectsFlag = false;
337
338 /// Show the notes in diagnostic information. Notes can be included in
339 /// any diagnostic information, so it is not specified in the verbosity
340 /// level.
342
343 /// Split the input file based on the given marker into chunks and process
344 /// each chunk independently. Input is not split if empty.
345 std::string splitInputFileFlag = "";
346
347 /// Merge output chunks into one file using the given marker.
348 std::string outputSplitMarkerFlag = "";
349
350 /// Use an explicit top-level module op during parsing.
352
353 /// Set whether to check that emitted diagnostics match `expected-*` lines on
354 /// the corresponding line. This is meant for implementing diagnostic tests.
357
358 /// Run the verifier after each transformation pass.
359 bool verifyPassesFlag = true;
360
361 /// Disable the verifier on parsing.
363
364 /// Verify that the input IR round-trips perfectly.
366
367 /// The reproducer output filename (no crash required).
369};
370
371/// This defines the function type used to setup the pass manager. This can be
372/// used to pass in a callback to setup a default pass pipeline to be applied on
373/// the loaded IR.
375
376/// Register basic command line options.
377/// - toolName is used for the header displayed by `--help`.
378/// - registry should contain all the dialects that can be parsed in the source.
379/// - return std::string for help header.
380std::string registerCLIOptions(llvm::StringRef toolName,
381 DialectRegistry &registry);
382
383/// Parse command line options.
384/// - helpHeader is used for the header displayed by `--help`.
385/// - return std::pair<std::string, std::string> for
386/// inputFilename and outputFilename command line option values.
387std::pair<std::string, std::string> parseCLIOptions(int argc, char **argv,
388 llvm::StringRef helpHeader);
389
390/// Register and parse command line options.
391/// - toolName is used for the header displayed by `--help`.
392/// - registry should contain all the dialects that can be parsed in the source.
393/// - return std::pair<std::string, std::string> for
394/// inputFilename and outputFilename command line option values.
395std::pair<std::string, std::string>
396registerAndParseCLIOptions(int argc, char **argv, llvm::StringRef toolName,
397 DialectRegistry &registry);
398
399/// Perform the core processing behind `mlir-opt`.
400/// - outputStream is the stream where the resulting IR is printed.
401/// - buffer is the in-memory file to parser and process.
402/// - registry should contain all the dialects that can be parsed in the source.
403/// - config contains the configuration options for the tool.
404LogicalResult MlirOptMain(llvm::raw_ostream &outputStream,
405 std::unique_ptr<llvm::MemoryBuffer> buffer,
406 DialectRegistry &registry,
407 const MlirOptMainConfig &config);
408
409/// Implementation for tools like `mlir-opt`.
410/// - toolName is used for the header displayed by `--help`.
411/// - registry should contain all the dialects that can be parsed in the source.
412LogicalResult MlirOptMain(int argc, char **argv, llvm::StringRef toolName,
413 DialectRegistry &registry);
414
415/// Implementation for tools like `mlir-opt`.
416/// This function can be used with registerAndParseCLIOptions so that
417/// CLI options can be accessed before running MlirOptMain.
418/// - inputFilename is the name of the input mlir file.
419/// - outputFilename is the name of the output file.
420/// - registry should contain all the dialects that can be parsed in the source.
421LogicalResult MlirOptMain(int argc, char **argv, llvm::StringRef inputFilename,
422 llvm::StringRef outputFilename,
423 DialectRegistry &registry);
424
425/// Helper wrapper to return the result of MlirOptMain directly from main.
426///
427/// Example:
428///
429/// int main(int argc, char **argv) {
430/// // ...
431/// return mlir::asMainReturnCode(mlir::MlirOptMain(
432/// argc, argv, /* ... */);
433/// }
434///
435inline int asMainReturnCode(LogicalResult r) {
436 return r.succeeded() ? EXIT_SUCCESS : EXIT_FAILURE;
437}
438
439} // namespace mlir
440
441#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:59
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 & showDialects(bool show)
Show the registered dialects before trying to load the input file.
MlirOptMainConfig & allowUnregisteredDialects(bool allow)
Options.
Definition MlirOptMain.h:74
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:88
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:91
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
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:78
bool shouldUseExplicitModule() const
VerbosityLevel getDiagnosticVerbosityLevel() const
Definition MlirOptMain.h:96
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:87
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:83
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:229
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:47
RemarkFormat
Definition MlirOptMain.h:41
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:35
LogicalResult verify(Operation *op, bool verifyRecursively=true)
Perform (potentially expensive) checks of invariants, used to detect compiler bugs,...
Definition Verifier.cpp:423