1 //===- toyc.cpp - The Toy Compiler ----------------------------------------===//
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 entry point for the Toy compiler.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "toy/Dialect.h"
14 #include "toy/MLIRGen.h"
15 #include "toy/Parser.h"
16 #include "toy/Passes.h"
17 
18 #include "mlir/Dialect/Affine/Passes.h"
19 #include "mlir/IR/AsmState.h"
20 #include "mlir/IR/BuiltinOps.h"
21 #include "mlir/IR/MLIRContext.h"
22 #include "mlir/IR/Verifier.h"
23 #include "mlir/InitAllDialects.h"
24 #include "mlir/Parser/Parser.h"
25 #include "mlir/Pass/Pass.h"
26 #include "mlir/Pass/PassManager.h"
27 #include "mlir/Transforms/Passes.h"
28 
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/ErrorOr.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/SourceMgr.h"
34 #include "llvm/Support/raw_ostream.h"
35 
36 using namespace toy;
37 namespace cl = llvm::cl;
38 
39 static cl::opt<std::string> inputFilename(cl::Positional,
40                                           cl::desc("<input toy file>"),
41                                           cl::init("-"),
42                                           cl::value_desc("filename"));
43 
44 namespace {
45 enum InputType { Toy, MLIR };
46 } // namespace
47 static cl::opt<enum InputType> inputType(
48     "x", cl::init(Toy), cl::desc("Decided the kind of output desired"),
49     cl::values(clEnumValN(Toy, "toy", "load the input file as a Toy source.")),
50     cl::values(clEnumValN(MLIR, "mlir",
51                           "load the input file as an MLIR file")));
52 
53 namespace {
54 enum Action { None, DumpAST, DumpMLIR, DumpMLIRAffine };
55 } // namespace
56 static cl::opt<enum Action> emitAction(
57     "emit", cl::desc("Select the kind of output desired"),
58     cl::values(clEnumValN(DumpAST, "ast", "output the AST dump")),
59     cl::values(clEnumValN(DumpMLIR, "mlir", "output the MLIR dump")),
60     cl::values(clEnumValN(DumpMLIRAffine, "mlir-affine",
61                           "output the MLIR dump after affine lowering")));
62 
63 static cl::opt<bool> enableOpt("opt", cl::desc("Enable optimizations"));
64 
65 /// Returns a Toy AST resulting from parsing the file or a nullptr on error.
66 std::unique_ptr<toy::ModuleAST> parseInputFile(llvm::StringRef filename) {
67   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> fileOrErr =
68       llvm::MemoryBuffer::getFileOrSTDIN(filename);
69   if (std::error_code ec = fileOrErr.getError()) {
70     llvm::errs() << "Could not open input file: " << ec.message() << "\n";
71     return nullptr;
72   }
73   auto buffer = fileOrErr.get()->getBuffer();
74   LexerBuffer lexer(buffer.begin(), buffer.end(), std::string(filename));
75   Parser parser(lexer);
76   return parser.parseModule();
77 }
78 
79 int loadMLIR(llvm::SourceMgr &sourceMgr, mlir::MLIRContext &context,
80              mlir::OwningOpRef<mlir::ModuleOp> &module) {
81   // Handle '.toy' input to the compiler.
82   if (inputType != InputType::MLIR &&
83       !llvm::StringRef(inputFilename).endswith(".mlir")) {
84     auto moduleAST = parseInputFile(inputFilename);
85     if (!moduleAST)
86       return 6;
87     module = mlirGen(context, *moduleAST);
88     return !module ? 1 : 0;
89   }
90 
91   // Otherwise, the input is '.mlir'.
92   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> fileOrErr =
93       llvm::MemoryBuffer::getFileOrSTDIN(inputFilename);
94   if (std::error_code ec = fileOrErr.getError()) {
95     llvm::errs() << "Could not open input file: " << ec.message() << "\n";
96     return -1;
97   }
98 
99   // Parse the input mlir.
100   sourceMgr.AddNewSourceBuffer(std::move(*fileOrErr), llvm::SMLoc());
101   module = mlir::parseSourceFile<mlir::ModuleOp>(sourceMgr, &context);
102   if (!module) {
103     llvm::errs() << "Error can't load file " << inputFilename << "\n";
104     return 3;
105   }
106   return 0;
107 }
108 
109 int dumpMLIR() {
110   mlir::MLIRContext context;
111   // Load our Dialect in this MLIR Context.
112   context.getOrLoadDialect<mlir::toy::ToyDialect>();
113 
114   mlir::OwningOpRef<mlir::ModuleOp> module;
115   llvm::SourceMgr sourceMgr;
116   mlir::SourceMgrDiagnosticHandler sourceMgrHandler(sourceMgr, &context);
117   if (int error = loadMLIR(sourceMgr, context, module))
118     return error;
119 
120   mlir::PassManager pm(&context);
121   // Apply any generic pass manager command line options and run the pipeline.
122   applyPassManagerCLOptions(pm);
123 
124   // Check to see what granularity of MLIR we are compiling to.
125   bool isLoweringToAffine = emitAction >= Action::DumpMLIRAffine;
126 
127   if (enableOpt || isLoweringToAffine) {
128     // Inline all functions into main and then delete them.
129     pm.addPass(mlir::createInlinerPass());
130 
131     // Now that there is only one function, we can infer the shapes of each of
132     // the operations.
133     mlir::OpPassManager &optPM = pm.nest<mlir::toy::FuncOp>();
134     optPM.addPass(mlir::toy::createShapeInferencePass());
135     optPM.addPass(mlir::createCanonicalizerPass());
136     optPM.addPass(mlir::createCSEPass());
137   }
138 
139   if (isLoweringToAffine) {
140     // Partially lower the toy dialect.
141     pm.addPass(mlir::toy::createLowerToAffinePass());
142 
143     // Add a few cleanups post lowering.
144     mlir::OpPassManager &optPM = pm.nest<mlir::func::FuncOp>();
145     optPM.addPass(mlir::createCanonicalizerPass());
146     optPM.addPass(mlir::createCSEPass());
147 
148     // Add optimizations if enabled.
149     if (enableOpt) {
150       optPM.addPass(mlir::createLoopFusionPass());
151       optPM.addPass(mlir::createAffineScalarReplacementPass());
152     }
153   }
154 
155   if (mlir::failed(pm.run(*module)))
156     return 4;
157 
158   module->dump();
159   return 0;
160 }
161 
162 int dumpAST() {
163   if (inputType == InputType::MLIR) {
164     llvm::errs() << "Can't dump a Toy AST when the input is MLIR\n";
165     return 5;
166   }
167 
168   auto moduleAST = parseInputFile(inputFilename);
169   if (!moduleAST)
170     return 1;
171 
172   dump(*moduleAST);
173   return 0;
174 }
175 
176 int main(int argc, char **argv) {
177   // Register any command line options.
178   mlir::registerAsmPrinterCLOptions();
179   mlir::registerMLIRContextCLOptions();
180   mlir::registerPassManagerCLOptions();
181 
182   cl::ParseCommandLineOptions(argc, argv, "toy compiler\n");
183 
184   switch (emitAction) {
185   case Action::DumpAST:
186     return dumpAST();
187   case Action::DumpMLIR:
188   case Action::DumpMLIRAffine:
189     return dumpMLIR();
190   default:
191     llvm::errs() << "No action specified (parsing only?), use -emit=<action>\n";
192   }
193 
194   return 0;
195 }
196