MLIR  22.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 
24 namespace llvm {
25 class raw_ostream;
26 class MemoryBuffer;
27 } // namespace llvm
28 
29 namespace mlir {
30 class DialectRegistry;
31 class PassPipelineCLParser;
32 class PassManager;
33 
34 /// enum class to indicate the verbosity level of the diagnostic filter.
35 enum class VerbosityLevel {
36  ErrorsOnly = 0,
39 };
40 
41 enum class RemarkFormat {
45 };
46 
47 /// Configuration options for the mlir-opt tool.
48 /// This is intended to help building tools like mlir-opt by collecting the
49 /// supported options.
50 /// The API is fluent, and the options are sorted in alphabetical order below.
51 /// The options can be exposed to the LLVM command line by registering them
52 /// with `MlirOptMainConfig::registerCLOptions(DialectRegistry &);` and creating
53 /// a config using `auto config = MlirOptMainConfig::createFromCLOptions();`.
55 public:
56  /// Register the options as global LLVM command line options.
57  static void registerCLOptions(DialectRegistry &dialectRegistry);
58 
59  /// Create a new config with the default set from the CL options.
61 
62  ///
63  /// Options.
64  ///
65 
66  /// Allow operation with no registered dialects.
67  /// This option is for convenience during testing only and discouraged in
68  /// general.
71  return *this;
72  }
75  }
76 
77  /// Set the debug configuration to use.
79  debugConfig = std::move(config);
80  return *this;
81  }
83  const tracing::DebugConfig &getDebugConfig() const { return debugConfig; }
84 
85  /// Print the pass-pipeline as text before executing.
87  dumpPassPipelineFlag = dump;
88  return *this;
89  }
90 
93  }
94 
96 
97  /// Set the output format to bytecode instead of textual IR.
100  return *this;
101  }
102  bool shouldEmitBytecode() const { return emitBytecodeFlag; }
103 
106  }
107 
108  bool shouldShowNotes() const { return !disableDiagnosticNotesFlag; }
109 
110  /// Set the IRDL file to load before processing the input.
111  MlirOptMainConfig &setIrdlFile(StringRef file) {
112  irdlFileFlag = file;
113  return *this;
114  }
115  StringRef getIrdlFile() const { return irdlFileFlag; }
116 
117  /// Set the bytecode version to emit.
119  emitBytecodeVersion = version;
120  return *this;
121  }
122  std::optional<int64_t> bytecodeVersionToEmit() const {
123  return emitBytecodeVersion;
124  }
125 
126  /// Set the callback to populate the pass manager.
128  setPassPipelineSetupFn(std::function<LogicalResult(PassManager &)> callback) {
129  passPipelineCallback = std::move(callback);
130  return *this;
131  }
132 
133  /// Set the parser to use to populate the pass manager.
135 
136  /// Populate the passmanager, if any callback was set.
137  LogicalResult setupPassPipeline(PassManager &pm) const {
139  return passPipelineCallback(pm);
140  return success();
141  }
142 
143  /// List the registered passes and return.
145  listPassesFlag = list;
146  return *this;
147  }
148  bool shouldListPasses() const { return listPassesFlag; }
149 
150  /// Enable running the reproducer information stored in resources (if
151  /// present).
152  MlirOptMainConfig &runReproducer(bool enableReproducer) {
153  runReproducerFlag = enableReproducer;
154  return *this;
155  };
156 
157  /// Return true if the reproducer should be run.
158  bool shouldRunReproducer() const { return runReproducerFlag; }
159 
160  /// Show the registered dialects before trying to load the input file.
162  showDialectsFlag = show;
163  return *this;
164  }
165  bool shouldShowDialects() const { return showDialectsFlag; }
166 
167  /// Set the marker on which to split the input into chunks and process each
168  /// chunk independently. Input is not split if empty.
170  splitInputFile(std::string splitMarker = kDefaultSplitMarker) {
171  splitInputFileFlag = std::move(splitMarker);
172  return *this;
173  }
174  StringRef inputSplitMarker() const { return splitInputFileFlag; }
175 
176  /// Set whether to merge the output chunks into one file using the given
177  /// marker.
179  outputSplitMarker(std::string splitMarker = kDefaultSplitMarker) {
180  outputSplitMarkerFlag = std::move(splitMarker);
181  return *this;
182  }
183  StringRef outputSplitMarker() const { return outputSplitMarkerFlag; }
184 
185  /// Disable implicit addition of a top-level module op during parsing.
188  return *this;
189  }
191 
192  /// Set whether to check that emitted diagnostics match `expected-*` lines on
193  /// the corresponding line. This is meant for implementing diagnostic tests.
197  return *this;
198  }
199 
200  bool shouldVerifyDiagnostics() const {
201  return verifyDiagnosticsFlag !=
203  }
204 
206  return verifyDiagnosticsFlag;
207  }
208 
209  /// Set whether to run the verifier after each transformation pass.
212  return *this;
213  }
214  bool shouldVerifyPasses() const { return verifyPassesFlag; }
215 
216  /// Set whether to run the verifier on parsing.
219  return *this;
220  }
222 
223  /// Set whether to run the verifier after each transformation pass.
226  return *this;
227  }
229 
230  /// Checks if any remark filters are set.
231  bool shouldEmitRemarks() const {
232  // Emit all remarks only when no filters are specified.
233  const bool hasFilters =
234  !getRemarksAllFilter().empty() || !getRemarksPassedFilter().empty() ||
235  !getRemarksFailedFilter().empty() ||
236  !getRemarksMissedFilter().empty() || !getRemarksAnalyseFilter().empty();
237  return hasFilters;
238  }
239 
240  /// Reproducer file generation (no crash required).
241  StringRef getReproducerFilename() const { return generateReproducerFileFlag; }
242 
243  /// Set the reproducer output filename
245  /// Set the remark format to use.
246  std::string getRemarksAllFilter() const { return remarksAllFilterFlag; }
247  /// Set the remark output file.
248  std::string getRemarksOutputFile() const { return remarksOutputFileFlag; }
249  /// Set the remark passed filters.
250  std::string getRemarksPassedFilter() const { return remarksPassedFilterFlag; }
251  /// Set the remark failed filters.
252  std::string getRemarksFailedFilter() const { return remarksFailedFilterFlag; }
253  /// Set the remark missed filters.
254  std::string getRemarksMissedFilter() const { return remarksMissedFilterFlag; }
255  /// Set the remark analyse filters.
256  std::string getRemarksAnalyseFilter() const {
258  }
259 
260 protected:
261  /// Allow operation with no registered dialects.
262  /// This option is for convenience during testing only and discouraged in
263  /// general.
265 
266  /// Remark format
268  /// Remark file to output to
269  std::string remarksOutputFileFlag = "";
270  /// Remark filters
271  std::string remarksAllFilterFlag = "";
272  std::string remarksPassedFilterFlag = "";
273  std::string remarksFailedFilterFlag = "";
274  std::string remarksMissedFilterFlag = "";
275  std::string remarksAnalyseFilterFlag = "";
276 
277  /// Configuration for the debugging hooks.
279 
280  /// Verbosity level of diagnostic information. 0: Errors only,
281  /// 1: Errors and warnings, 2: Errors, warnings and remarks.
284 
285  /// Print the pipeline that will be run.
286  bool dumpPassPipelineFlag = false;
287 
288  /// Emit bytecode instead of textual assembly when generating output.
289  bool emitBytecodeFlag = false;
290 
291  /// Elide resources when generating bytecode.
293 
294  /// IRDL file to register before processing the input.
295  std::string irdlFileFlag = "";
296 
297  /// Location Breakpoints to filter the action logging.
298  std::vector<tracing::BreakpointManager *> logActionLocationFilter;
299 
300  /// Emit bytecode at given version.
301  std::optional<int64_t> emitBytecodeVersion = std::nullopt;
302 
303  /// The callback to populate the pass manager.
304  std::function<LogicalResult(PassManager &)> passPipelineCallback;
305 
306  /// List the registered passes and return.
307  bool listPassesFlag = false;
308 
309  /// Enable running the reproducer.
310  bool runReproducerFlag = false;
311 
312  /// Show the registered dialects before trying to load the input file.
313  bool showDialectsFlag = false;
314 
315  /// Show the notes in diagnostic information. Notes can be included in
316  /// any diagnostic information, so it is not specified in the verbosity
317  /// level.
319 
320  /// Split the input file based on the given marker into chunks and process
321  /// each chunk independently. Input is not split if empty.
322  std::string splitInputFileFlag = "";
323 
324  /// Merge output chunks into one file using the given marker.
325  std::string outputSplitMarkerFlag = "";
326 
327  /// Use an explicit top-level module op during parsing.
328  bool useExplicitModuleFlag = false;
329 
330  /// Set whether to check that emitted diagnostics match `expected-*` lines on
331  /// the corresponding line. This is meant for implementing diagnostic tests.
334 
335  /// Run the verifier after each transformation pass.
336  bool verifyPassesFlag = true;
337 
338  /// Disable the verifier on parsing.
340 
341  /// Verify that the input IR round-trips perfectly.
342  bool verifyRoundtripFlag = false;
343 
344  /// The reproducer output filename (no crash required).
345  std::string generateReproducerFileFlag = "";
346 };
347 
348 /// This defines the function type used to setup the pass manager. This can be
349 /// used to pass in a callback to setup a default pass pipeline to be applied on
350 /// the loaded IR.
351 using PassPipelineFn = llvm::function_ref<LogicalResult(PassManager &pm)>;
352 
353 /// Register and parse command line options.
354 /// - toolName is used for the header displayed by `--help`.
355 /// - registry should contain all the dialects that can be parsed in the source.
356 /// - return std::pair<std::string, std::string> for
357 /// inputFilename and outputFilename command line option values.
358 std::pair<std::string, std::string>
359 registerAndParseCLIOptions(int argc, char **argv, llvm::StringRef toolName,
360  DialectRegistry &registry);
361 
362 /// Perform the core processing behind `mlir-opt`.
363 /// - outputStream is the stream where the resulting IR is printed.
364 /// - buffer is the in-memory file to parser and process.
365 /// - registry should contain all the dialects that can be parsed in the source.
366 /// - config contains the configuration options for the tool.
367 LogicalResult MlirOptMain(llvm::raw_ostream &outputStream,
368  std::unique_ptr<llvm::MemoryBuffer> buffer,
369  DialectRegistry &registry,
370  const MlirOptMainConfig &config);
371 
372 /// Implementation for tools like `mlir-opt`.
373 /// - toolName is used for the header displayed by `--help`.
374 /// - registry should contain all the dialects that can be parsed in the source.
375 LogicalResult MlirOptMain(int argc, char **argv, llvm::StringRef toolName,
376  DialectRegistry &registry);
377 
378 /// Implementation for tools like `mlir-opt`.
379 /// This function can be used with registerAndParseCLIOptions so that
380 /// CLI options can be accessed before running MlirOptMain.
381 /// - inputFilename is the name of the input mlir file.
382 /// - outputFilename is the name of the output file.
383 /// - registry should contain all the dialects that can be parsed in the source.
384 LogicalResult MlirOptMain(int argc, char **argv, llvm::StringRef inputFilename,
385  llvm::StringRef outputFilename,
386  DialectRegistry &registry);
387 
388 /// Helper wrapper to return the result of MlirOptMain directly from main.
389 ///
390 /// Example:
391 ///
392 /// int main(int argc, char **argv) {
393 /// // ...
394 /// return mlir::asMainReturnCode(mlir::MlirOptMain(
395 /// argc, argv, /* ... */);
396 /// }
397 ///
398 inline int asMainReturnCode(LogicalResult r) {
399  return r.succeeded() ? EXIT_SUCCESS : EXIT_FAILURE;
400 }
401 
402 } // namespace mlir
403 
404 #endif // MLIR_TOOLS_MLIROPT_MLIROPTMAIN_H
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:54
tracing::DebugConfig & getDebugConfig()
Definition: MlirOptMain.h:82
std::string getRemarksAnalyseFilter() const
Set the remark analyse filters.
Definition: MlirOptMain.h:256
std::string getRemarksMissedFilter() const
Set the remark missed filters.
Definition: MlirOptMain.h:254
bool shouldEmitRemarks() const
Checks if any remark filters are set.
Definition: MlirOptMain.h:231
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.
Definition: MlirOptMain.h:322
bool shouldVerifyPasses() const
Definition: MlirOptMain.h:214
StringRef inputSplitMarker() const
Definition: MlirOptMain.h:174
bool shouldVerifyRoundtrip() const
Definition: MlirOptMain.h:228
SourceMgrDiagnosticVerifierHandler::Level verifyDiagnosticsLevel() const
Definition: MlirOptMain.h:205
std::optional< int64_t > bytecodeVersionToEmit() const
Definition: MlirOptMain.h:122
bool shouldShowNotes() const
Definition: MlirOptMain.h:108
bool disableVerifierOnParsingFlag
Disable the verifier on parsing.
Definition: MlirOptMain.h:339
std::optional< int64_t > emitBytecodeVersion
Emit bytecode at given version.
Definition: MlirOptMain.h:301
StringRef getReproducerFilename() const
Reproducer file generation (no crash required).
Definition: MlirOptMain.h:241
std::string irdlFileFlag
IRDL file to register before processing the input.
Definition: MlirOptMain.h:295
VerbosityLevel diagnosticVerbosityLevelFlag
Verbosity level of diagnostic information.
Definition: MlirOptMain.h:282
std::vector< tracing::BreakpointManager * > logActionLocationFilter
Location Breakpoints to filter the action logging.
Definition: MlirOptMain.h:298
bool emitBytecodeFlag
Emit bytecode instead of textual assembly when generating output.
Definition: MlirOptMain.h:289
std::string getRemarksOutputFile() const
Set the remark output file.
Definition: MlirOptMain.h:248
bool shouldShowDialects() const
Definition: MlirOptMain.h:165
MlirOptMainConfig & verifyDiagnostics(SourceMgrDiagnosticVerifierHandler::Level verify)
Set whether to check that emitted diagnostics match expected-* lines on the corresponding line.
Definition: MlirOptMain.h:195
MlirOptMainConfig & splitInputFile(std::string splitMarker=kDefaultSplitMarker)
Set the marker on which to split the input into chunks and process each chunk independently.
Definition: MlirOptMain.h:170
std::string getRemarksFailedFilter() const
Set the remark failed filters.
Definition: MlirOptMain.h:252
bool disableDiagnosticNotesFlag
Show the notes in diagnostic information.
Definition: MlirOptMain.h:318
std::string generateReproducerFileFlag
The reproducer output filename (no crash required).
Definition: MlirOptMain.h:345
MlirOptMainConfig & outputSplitMarker(std::string splitMarker=kDefaultSplitMarker)
Set whether to merge the output chunks into one file using the given marker.
Definition: MlirOptMain.h:179
SourceMgrDiagnosticVerifierHandler::Level verifyDiagnosticsFlag
Set whether to check that emitted diagnostics match expected-* lines on the corresponding line.
Definition: MlirOptMain.h:332
std::function< LogicalResult(PassManager &)> passPipelineCallback
The callback to populate the pass manager.
Definition: MlirOptMain.h:304
bool dumpPassPipelineFlag
Print the pipeline that will be run.
Definition: MlirOptMain.h:286
bool verifyPassesFlag
Run the verifier after each transformation pass.
Definition: MlirOptMain.h:336
MlirOptMainConfig & verifyRoundtrip(bool verify)
Set whether to run the verifier after each transformation pass.
Definition: MlirOptMain.h:224
MlirOptMainConfig & setIrdlFile(StringRef file)
Set the IRDL file to load before processing the input.
Definition: MlirOptMain.h:111
MlirOptMainConfig & verifyPasses(bool verify)
Set whether to run the verifier after each transformation pass.
Definition: MlirOptMain.h:210
std::string remarksOutputFileFlag
Remark file to output to.
Definition: MlirOptMain.h:269
bool shouldVerifyOnParsing() const
Definition: MlirOptMain.h:221
std::string getRemarksAllFilter() const
Set the remark format to use.
Definition: MlirOptMain.h:246
bool shouldElideResourceDataFromBytecode() const
Definition: MlirOptMain.h:104
bool shouldEmitBytecode() const
Definition: MlirOptMain.h:102
tracing::DebugConfig debugConfig
Configuration for the debugging hooks.
Definition: MlirOptMain.h:278
RemarkFormat remarkFormatFlag
Remark format.
Definition: MlirOptMain.h:267
StringRef outputSplitMarker() const
Definition: MlirOptMain.h:183
MlirOptMainConfig & setPassPipelineSetupFn(std::function< LogicalResult(PassManager &)> callback)
Set the callback to populate the pass manager.
Definition: MlirOptMain.h:128
RemarkFormat getRemarkFormat() const
Set the reproducer output filename.
Definition: MlirOptMain.h:244
MlirOptMainConfig & showDialects(bool show)
Show the registered dialects before trying to load the input file.
Definition: MlirOptMain.h:161
bool runReproducerFlag
Enable running the reproducer.
Definition: MlirOptMain.h:310
MlirOptMainConfig & dumpPassPipeline(bool dump)
Print the pass-pipeline as text before executing.
Definition: MlirOptMain.h:86
MlirOptMainConfig & verifyOnParsing(bool verify)
Set whether to run the verifier on parsing.
Definition: MlirOptMain.h:217
MlirOptMainConfig & runReproducer(bool enableReproducer)
Enable running the reproducer information stored in resources (if present).
Definition: MlirOptMain.h:152
std::string remarksAllFilterFlag
Remark filters.
Definition: MlirOptMain.h:271
bool verifyRoundtripFlag
Verify that the input IR round-trips perfectly.
Definition: MlirOptMain.h:342
std::string remarksPassedFilterFlag
Definition: MlirOptMain.h:272
bool allowUnregisteredDialectsFlag
Allow operation with no registered dialects.
Definition: MlirOptMain.h:264
MlirOptMainConfig & useExplicitModule(bool useExplicitModule)
Disable implicit addition of a top-level module op during parsing.
Definition: MlirOptMain.h:186
LogicalResult setupPassPipeline(PassManager &pm) const
Populate the passmanager, if any callback was set.
Definition: MlirOptMain.h:137
MlirOptMainConfig & setEmitBytecodeVersion(int64_t version)
Set the bytecode version to emit.
Definition: MlirOptMain.h:118
std::string remarksAnalyseFilterFlag
Definition: MlirOptMain.h:275
static void registerCLOptions(DialectRegistry &dialectRegistry)
Register the options as global LLVM command line options.
bool shouldAllowUnregisteredDialects() const
Definition: MlirOptMain.h:73
bool shouldUseExplicitModule() const
Definition: MlirOptMain.h:190
VerbosityLevel getDiagnosticVerbosityLevel() const
Definition: MlirOptMain.h:91
bool shouldRunReproducer() const
Return true if the reproducer should be run.
Definition: MlirOptMain.h:158
bool elideResourceDataFromBytecodeFlag
Elide resources when generating bytecode.
Definition: MlirOptMain.h:292
MlirOptMainConfig & allowUnregisteredDialects(bool allow)
Options.
Definition: MlirOptMain.h:69
std::string remarksFailedFilterFlag
Definition: MlirOptMain.h:273
bool shouldDumpPassPipeline() const
Definition: MlirOptMain.h:95
bool shouldVerifyDiagnostics() const
Definition: MlirOptMain.h:200
bool useExplicitModuleFlag
Use an explicit top-level module op during parsing.
Definition: MlirOptMain.h:328
const tracing::DebugConfig & getDebugConfig() const
Definition: MlirOptMain.h:83
std::string remarksMissedFilterFlag
Definition: MlirOptMain.h:274
std::string getRemarksPassedFilter() const
Set the remark passed filters.
Definition: MlirOptMain.h:250
bool shouldListPasses() const
Definition: MlirOptMain.h:148
bool showDialectsFlag
Show the registered dialects before trying to load the input file.
Definition: MlirOptMain.h:313
MlirOptMainConfig & listPasses(bool list)
List the registered passes and return.
Definition: MlirOptMain.h:144
MlirOptMainConfig & setDebugConfig(tracing::DebugConfig config)
Set the debug configuration to use.
Definition: MlirOptMain.h:78
StringRef getIrdlFile() const
Definition: MlirOptMain.h:115
bool listPassesFlag
List the registered passes and return.
Definition: MlirOptMain.h:307
std::string outputSplitMarkerFlag
Merge output chunks into one file using the given marker.
Definition: MlirOptMain.h:325
MlirOptMainConfig & emitBytecode(bool emit)
Set the output format to bytecode instead of textual IR.
Definition: MlirOptMain.h:98
MlirOptMainConfig & setPassPipelineParser(const PassPipelineCLParser &parser)
Set the parser to use to populate the pass manager.
The main pass manager and pipeline builder.
Definition: PassManager.h:232
This class implements a command-line parser for MLIR passes.
Definition: PassRegistry.h:247
The OpAsmOpInterface, see OpAsmInterface.td for more details.
Definition: CallGraph.h:229
Include the generated interface declarations.
const char *const kDefaultSplitMarker
int asMainReturnCode(LogicalResult r)
Helper wrapper to return the result of MlirOptMain directly from main.
Definition: MlirOptMain.h:398
const FrozenRewritePatternSet GreedyRewriteConfig config
LogicalResult MlirOptMain(llvm::raw_ostream &outputStream, std::unique_ptr< llvm::MemoryBuffer > buffer, DialectRegistry &registry, const MlirOptMainConfig &config)
Perform the core processing behind mlir-opt.
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