blob: 4f62b288159c54c691f3bf92bf2842619d996760 [file] [log] [blame]
Chris Lattnerc0c5e0f2018-06-21 09:49:33 -07001//===- mlir-opt.cpp - MLIR Optimizer Driver -------------------------------===//
2//
3// Copyright 2019 The MLIR Authors.
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16// =============================================================================
17//
18// This is a command line utility that parses an MLIR file, runs an optimization
19// pass, then prints the result back out. It is designed to support unit
20// testing.
21//
22//===----------------------------------------------------------------------===//
23
Uday Bondhugula0b4059b2018-07-24 20:01:16 -070024#include "mlir/IR/MLFunction.h"
Chris Lattnerf7e22732018-06-22 22:03:48 -070025#include "mlir/IR/MLIRContext.h"
Chris Lattnere2259872018-06-21 15:22:42 -070026#include "mlir/IR/Module.h"
Chris Lattnere79379a2018-06-22 10:39:19 -070027#include "mlir/Parser.h"
Uday Bondhugula0b4059b2018-07-24 20:01:16 -070028#include "mlir/Pass.h"
Tatiana Shpeisman6708b452018-07-24 10:15:13 -070029#include "mlir/Transforms/ConvertToCFG.h"
Uday Bondhugula0b4059b2018-07-24 20:01:16 -070030#include "mlir/Transforms/Loop.h"
Chris Lattnerc0c5e0f2018-06-21 09:49:33 -070031#include "llvm/Support/CommandLine.h"
Chris Lattnere2259872018-06-21 15:22:42 -070032#include "llvm/Support/FileUtilities.h"
Chris Lattnerc0c5e0f2018-06-21 09:49:33 -070033#include "llvm/Support/InitLLVM.h"
Jacques Pienaarca4c4a02018-06-25 08:10:46 -070034#include "llvm/Support/Regex.h"
Jacques Pienaar39ffa102018-07-07 19:12:22 -070035#include "llvm/Support/SourceMgr.h"
Chris Lattnere2259872018-06-21 15:22:42 -070036#include "llvm/Support/ToolOutputFile.h"
Chris Lattnerc0c5e0f2018-06-21 09:49:33 -070037using namespace mlir;
Chris Lattnere2259872018-06-21 15:22:42 -070038using namespace llvm;
39
40static cl::opt<std::string>
41inputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
42
43static cl::opt<std::string>
44outputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"),
45 cl::init("-"));
46
Jacques Pienaarbae40512018-06-24 09:10:36 -070047static cl::opt<bool>
48checkParserErrors("check-parser-errors", cl::desc("Check for parser errors"),
49 cl::init(false));
Chris Lattnere2259872018-06-21 15:22:42 -070050
Tatiana Shpeisman6708b452018-07-24 10:15:13 -070051static cl::opt<bool> convertToCFGOpt(
52 "convert-to-cfg",
53 cl::desc("Convert all ML functions in the module to CFG ones"));
54
Uday Bondhugula0b4059b2018-07-24 20:01:16 -070055static cl::opt<bool> unrollInnermostLoops("unroll-innermost-loops",
56 cl::desc("Unroll innermost loops"),
57 cl::init(false));
58
Jacques Pienaar7b829702018-07-03 13:24:09 -070059enum OptResult { OptSuccess, OptFailure };
60
Chris Lattnere2259872018-06-21 15:22:42 -070061/// Open the specified output file and return it, exiting if there is any I/O or
62/// other errors.
63static std::unique_ptr<ToolOutputFile> getOutputStream() {
64 std::error_code error;
65 auto result = make_unique<ToolOutputFile>(outputFilename, error,
66 sys::fs::F_None);
67 if (error) {
68 llvm::errs() << error.message() << '\n';
69 exit(1);
70 }
71
72 return result;
73}
Chris Lattnerc0c5e0f2018-06-21 09:49:33 -070074
Jacques Pienaarbae40512018-06-24 09:10:36 -070075/// Parses the memory buffer and, if successfully parsed, prints the parsed
Tatiana Shpeisman6708b452018-07-24 10:15:13 -070076/// output. Optionally, convert ML functions into CFG functions.
77/// TODO: pull parsing and printing into separate functions.
Jacques Pienaar7b829702018-07-03 13:24:09 -070078OptResult parseAndPrintMemoryBuffer(std::unique_ptr<MemoryBuffer> buffer) {
Jacques Pienaarbae40512018-06-24 09:10:36 -070079 // Tell sourceMgr about this buffer, which is what the parser will pick up.
80 SourceMgr sourceMgr;
81 sourceMgr.AddNewSourceBuffer(std::move(buffer), SMLoc());
82
Jacques Pienaar9c411be2018-06-24 19:17:35 -070083 // Parse the input file.
Jacques Pienaarbae40512018-06-24 09:10:36 -070084 MLIRContext context;
Jacques Pienaar7b829702018-07-03 13:24:09 -070085 std::unique_ptr<Module> module(parseSourceFile(sourceMgr, &context));
86 if (!module)
87 return OptFailure;
Jacques Pienaarbae40512018-06-24 09:10:36 -070088
Tatiana Shpeisman6708b452018-07-24 10:15:13 -070089 // Convert ML functions into CFG functions
90 if (convertToCFGOpt)
91 convertToCFG(module.get());
92
Uday Bondhugula0b4059b2018-07-24 20:01:16 -070093 if (unrollInnermostLoops) {
94 MLFunctionPass *loopUnroll = createLoopUnrollPass();
95 loopUnroll->runOnModule(module.get());
96 }
97
Jacques Pienaarbae40512018-06-24 09:10:36 -070098 // Print the output.
99 auto output = getOutputStream();
100 module->print(output->os());
101 output->keep();
102
Jacques Pienaar7b829702018-07-03 13:24:09 -0700103 return OptSuccess;
Jacques Pienaarbae40512018-06-24 09:10:36 -0700104}
105
106/// Split the memory buffer into multiple buffers using the marker -----.
Jacques Pienaar7b829702018-07-03 13:24:09 -0700107OptResult
108splitMemoryBufferForErrorChecking(std::unique_ptr<MemoryBuffer> buffer) {
Jacques Pienaarbae40512018-06-24 09:10:36 -0700109 const char marker[] = "-----";
110 SmallVector<StringRef, 2> sourceBuffers;
111 buffer->getBuffer().split(sourceBuffers, marker);
Jacques Pienaarbae40512018-06-24 09:10:36 -0700112
Jacques Pienaarca4c4a02018-06-25 08:10:46 -0700113 // Error reporter that verifies error reports matches expected error
114 // substring.
115 // TODO: Only checking for error cases below. Could be expanded to other kinds
116 // of diagnostics.
117 // TODO: Enable specifying errors on different lines (@-1).
118 // TODO: Currently only checking if substring matches, enable regex checking.
Jacques Pienaar7b829702018-07-03 13:24:09 -0700119 OptResult opt_result = OptSuccess;
Jacques Pienaarb2ddbb62018-06-26 08:56:55 -0700120 SourceMgr fileSourceMgr;
121 fileSourceMgr.AddNewSourceBuffer(std::move(buffer), SMLoc());
122
Jacques Pienaar39ffa102018-07-07 19:12:22 -0700123 // Record the expected errors's position, substring and whether it was seen.
124 struct ExpectedError {
125 int lineNo;
126 StringRef substring;
127 SMLoc fileLoc;
128 bool matched;
129 };
130
Jacques Pienaarb2ddbb62018-06-26 08:56:55 -0700131 // Tracks offset of subbuffer into original buffer.
132 const char *fileOffset =
133 fileSourceMgr.getMemoryBuffer(fileSourceMgr.getMainFileID())
134 ->getBufferStart();
135
Jacques Pienaar39ffa102018-07-07 19:12:22 -0700136 for (auto &subbuffer : sourceBuffers) {
Jacques Pienaarb2ddbb62018-06-26 08:56:55 -0700137 SourceMgr sourceMgr;
138 // Tell sourceMgr about this buffer, which is what the parser will pick up.
139 sourceMgr.AddNewSourceBuffer(MemoryBuffer::getMemBufferCopy(subbuffer),
140 SMLoc());
141
Jacques Pienaar39ffa102018-07-07 19:12:22 -0700142 // Extracing the expected errors.
James Molloy61a656c2018-07-22 15:45:24 -0700143 llvm::Regex expected("expected-error(@[+-][0-9]+)? *{{(.*)}}");
Jacques Pienaar39ffa102018-07-07 19:12:22 -0700144 SmallVector<ExpectedError, 2> expectedErrors;
145 SmallVector<StringRef, 100> lines;
146 subbuffer.split(lines, '\n');
147 size_t bufOffset = 0;
148 for (int lineNo = 0; lineNo < lines.size(); ++lineNo) {
149 SmallVector<StringRef, 3> matches;
150 if (expected.match(lines[lineNo], &matches)) {
151 // Point to the start of expected-error.
152 SMLoc errorStart =
153 SMLoc::getFromPointer(fileOffset + bufOffset +
154 lines[lineNo].size() - matches[2].size() - 2);
155 ExpectedError expErr{lineNo + 1, matches[2], errorStart, false};
156 int offset;
157 if (!matches[1].empty() &&
158 !matches[1].drop_front().getAsInteger(0, offset)) {
159 expErr.lineNo += offset;
160 }
161 expectedErrors.push_back(expErr);
162 }
163 bufOffset += lines[lineNo].size() + 1;
Jacques Pienaarca4c4a02018-06-25 08:10:46 -0700164 }
165
Jacques Pienaar39ffa102018-07-07 19:12:22 -0700166 // Error checker that verifies reported error was expected.
167 auto checker = [&](const SMDiagnostic &err) {
168 for (auto &e : expectedErrors) {
169 if (err.getLineNo() == e.lineNo &&
170 err.getMessage().contains(e.substring)) {
171 e.matched = true;
172 return;
173 }
174 }
175 // Report error if no match found.
176 const auto &sourceMgr = *err.getSourceMgr();
177 const char *bufferStart =
178 sourceMgr.getMemoryBuffer(sourceMgr.getMainFileID())
179 ->getBufferStart();
180
181 size_t offset = err.getLoc().getPointer() - bufferStart;
182 SMLoc loc = SMLoc::getFromPointer(fileOffset + offset);
183 fileSourceMgr.PrintMessage(loc, SourceMgr::DK_Error,
184 "unexpected error: " + err.getMessage());
185 opt_result = OptFailure;
186 };
187
Jacques Pienaarb2ddbb62018-06-26 08:56:55 -0700188 // Parse the input file.
189 MLIRContext context;
190 std::unique_ptr<Module> module(
191 parseSourceFile(sourceMgr, &context, checker));
Jacques Pienaarb2ddbb62018-06-26 08:56:55 -0700192
Jacques Pienaar39ffa102018-07-07 19:12:22 -0700193 // Verify that all expected errors were seen.
194 for (auto err : expectedErrors) {
195 if (!err.matched) {
196 SMRange range(err.fileLoc,
197 SMLoc::getFromPointer(err.fileLoc.getPointer() +
198 err.substring.size()));
199 fileSourceMgr.PrintMessage(
200 err.fileLoc, SourceMgr::DK_Error,
201 "expected error \"" + err.substring + "\" was not produced", range);
202 opt_result = OptFailure;
203 }
Jacques Pienaarca4c4a02018-06-25 08:10:46 -0700204 }
Jacques Pienaarb2ddbb62018-06-26 08:56:55 -0700205
206 fileOffset += subbuffer.size() + strlen(marker);
Jacques Pienaarca4c4a02018-06-25 08:10:46 -0700207 }
208
Jacques Pienaar7b829702018-07-03 13:24:09 -0700209 return opt_result;
Jacques Pienaarbae40512018-06-24 09:10:36 -0700210}
211
Chris Lattnerc0c5e0f2018-06-21 09:49:33 -0700212int main(int argc, char **argv) {
Chris Lattnere2259872018-06-21 15:22:42 -0700213 InitLLVM x(argc, argv);
Chris Lattnerc0c5e0f2018-06-21 09:49:33 -0700214
Chris Lattnere2259872018-06-21 15:22:42 -0700215 cl::ParseCommandLineOptions(argc, argv, "MLIR modular optimizer driver\n");
Chris Lattnerc0c5e0f2018-06-21 09:49:33 -0700216
Chris Lattnere79379a2018-06-22 10:39:19 -0700217 // Set up the input file.
218 auto fileOrErr = MemoryBuffer::getFileOrSTDIN(inputFilename);
219 if (std::error_code error = fileOrErr.getError()) {
220 llvm::errs() << argv[0] << ": could not open input file '" << inputFilename
221 << "': " << error.message() << "\n";
222 return 1;
223 }
224
Jacques Pienaarbae40512018-06-24 09:10:36 -0700225 if (checkParserErrors)
Jacques Pienaar7b829702018-07-03 13:24:09 -0700226 return splitMemoryBufferForErrorChecking(std::move(*fileOrErr));
Jacques Pienaarca4c4a02018-06-25 08:10:46 -0700227
Jacques Pienaar7b829702018-07-03 13:24:09 -0700228 return parseAndPrintMemoryBuffer(std::move(*fileOrErr));
Chris Lattnerc0c5e0f2018-06-21 09:49:33 -0700229}