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