1//===- mlir-reduce.cpp - The MLIR reducer ---------------------------------===//
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 implements the general framework of the MLIR reducer tool. It
10// parses the command line arguments, parses the initial MLIR test case and sets
11// up the testing environment. It outputs the most reduced test case variant
12// after executing the reduction passes.
13//
14//===----------------------------------------------------------------------===//
15
16#include "mlir/Tools/mlir-reduce/MlirReduceMain.h"
17#include "mlir/Parser/Parser.h"
18#include "mlir/Pass/PassManager.h"
19#include "mlir/Reducer/Passes.h"
20#include "mlir/Support/FileUtilities.h"
21#include "mlir/Support/ToolUtilities.h"
22#include "mlir/Tools/ParseUtilities.h"
23#include "llvm/Support/InitLLVM.h"
24#include "llvm/Support/SourceMgr.h"
25#include "llvm/Support/ToolOutputFile.h"
26
27using namespace mlir;
28
29LogicalResult mlir::mlirReduceMain(int argc, char **argv,
30 MLIRContext &context) {
31 static llvm::cl::OptionCategory mlirReduceCategory("mlir-reduce options");
32
33 static llvm::cl::opt<std::string> inputFilename(
34 llvm::cl::Positional, llvm::cl::desc("<input file>"),
35 llvm::cl::cat(mlirReduceCategory));
36
37 static llvm::cl::opt<std::string> outputFilename(
38 "o", llvm::cl::desc("Output filename for the reduced test case"),
39 llvm::cl::init(Val: "-"), llvm::cl::cat(mlirReduceCategory));
40
41 static llvm::cl::opt<bool> noImplicitModule{
42 "no-implicit-module",
43 llvm::cl::desc(
44 "Disable implicit addition of a top-level module op during parsing"),
45 llvm::cl::init(Val: false)};
46
47 static llvm::cl::opt<bool> allowUnregisteredDialects(
48 "allow-unregistered-dialect",
49 llvm::cl::desc("Allow operation with no registered dialects"),
50 llvm::cl::init(Val: false));
51
52 static llvm::cl::opt<std::string> splitInputFile(
53 "split-input-file", llvm::cl::ValueOptional,
54 llvm::cl::callback(CB: [&](const std::string &str) {
55 // Implicit value: use default marker if flag was used without
56 // value.
57 if (str.empty())
58 splitInputFile.setValue(V: kDefaultSplitMarker);
59 }),
60 llvm::cl::desc("Split the input file into chunks using the given or "
61 "default marker and process each chunk independently"),
62 llvm::cl::init(Val: ""));
63
64 llvm::cl::HideUnrelatedOptions(Category&: mlirReduceCategory);
65
66 llvm::InitLLVM y(argc, argv);
67
68 registerReducerPasses();
69
70 PassPipelineCLParser parser("", "Reduction Passes to Run");
71 llvm::cl::ParseCommandLineOptions(argc, argv,
72 Overview: "MLIR test case reduction tool.\n");
73
74 if (allowUnregisteredDialects)
75 context.allowUnregisteredDialects();
76
77 std::string errorMessage;
78
79 auto output = openOutputFile(outputFilename, errorMessage: &errorMessage);
80 if (!output)
81 return failure();
82
83 std::unique_ptr<llvm::MemoryBuffer> input =
84 openInputFile(inputFilename, errorMessage: &errorMessage);
85 if (!input) {
86 llvm::errs() << errorMessage << "\n";
87 return failure();
88 }
89
90 auto errorHandler = [&](const Twine &msg) {
91 return emitError(loc: UnknownLoc::get(context: &context)) << msg;
92 };
93
94 auto chunkFn = [&](std::unique_ptr<llvm::MemoryBuffer> chunkBuffer,
95 raw_ostream &os) {
96 auto sourceMgr = std::make_shared<llvm::SourceMgr>();
97 sourceMgr->AddNewSourceBuffer(F: std::move(chunkBuffer), IncludeLoc: SMLoc());
98 OwningOpRef<Operation *> opRef =
99 parseSourceFileForTool(sourceMgr, config: &context, insertImplicitModule: !noImplicitModule);
100 if (!opRef)
101 return failure();
102 // Reduction pass pipeline.
103 PassManager pm(&context, opRef.get()->getName().getStringRef());
104 if (failed(Result: parser.addToPipeline(pm, errorHandler)))
105 return failure();
106
107 OwningOpRef<Operation *> op = opRef.get()->clone();
108
109 if (failed(Result: pm.run(op: op.get())))
110 return failure();
111 op.get()->print(os&: output->os());
112 output->keep();
113 return success();
114 };
115
116 auto &splitInputFileDelimiter = splitInputFile.getValue();
117 if (!splitInputFileDelimiter.empty())
118 return splitAndProcessBuffer(originalBuffer: std::move(input), processChunkBuffer: chunkFn, os&: output->os(),
119 inputSplitMarker: splitInputFileDelimiter,
120 outputSplitMarker: splitInputFileDelimiter);
121
122 return chunkFn(std::move(input), output->os());
123}
124