blob: 3db030b2852ea809a202a246346bdc554b74d1ae [file] [log] [blame]
Chris Lattner4c95a502018-06-23 16:03:42 -07001//===- AsmPrinter.cpp - MLIR Assembly Printer Implementation --------------===//
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 file implements the MLIR AsmPrinter class, which is used to implement
19// the various print() methods on the core IR objects.
20//
21//===----------------------------------------------------------------------===//
22
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -070023#include "mlir/IR/AffineExpr.h"
24#include "mlir/IR/AffineMap.h"
Chris Lattner7121b802018-07-04 20:45:39 -070025#include "mlir/IR/Attributes.h"
Chris Lattner4c95a502018-06-23 16:03:42 -070026#include "mlir/IR/CFGFunction.h"
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -070027#include "mlir/IR/MLFunction.h"
Chris Lattner4c95a502018-06-23 16:03:42 -070028#include "mlir/IR/Module.h"
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -070029#include "mlir/IR/OpImplementation.h"
Chris Lattnerff0d5902018-07-05 09:12:11 -070030#include "mlir/IR/OperationSet.h"
Chris Lattnerd4964212018-08-01 10:43:18 -070031#include "mlir/IR/StandardOps.h"
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -070032#include "mlir/IR/Statements.h"
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -070033#include "mlir/IR/StmtVisitor.h"
Chris Lattner4c95a502018-06-23 16:03:42 -070034#include "mlir/IR/Types.h"
35#include "mlir/Support/STLExtras.h"
Chris Lattner4c95a502018-06-23 16:03:42 -070036#include "llvm/ADT/DenseMap.h"
Chris Lattnerd4964212018-08-01 10:43:18 -070037#include "llvm/ADT/SmallString.h"
38#include "llvm/ADT/StringExtras.h"
39#include "llvm/ADT/StringSet.h"
Chris Lattner4c95a502018-06-23 16:03:42 -070040using namespace mlir;
41
MLIR Team54b55a22018-07-18 10:16:05 -070042void Identifier::print(raw_ostream &os) const { os << str(); }
Chris Lattner4c95a502018-06-23 16:03:42 -070043
MLIR Team54b55a22018-07-18 10:16:05 -070044void Identifier::dump() const { print(llvm::errs()); }
Chris Lattner7121b802018-07-04 20:45:39 -070045
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -070046OpAsmPrinter::~OpAsmPrinter() {}
47
Chris Lattner4c95a502018-06-23 16:03:42 -070048//===----------------------------------------------------------------------===//
Chris Lattner4fd59b02018-07-20 09:35:47 -070049// ModuleState
MLIR Team4718bc92018-07-17 16:56:54 -070050//===----------------------------------------------------------------------===//
51
52namespace {
MLIR Team54b55a22018-07-18 10:16:05 -070053class ModuleState {
54public:
Chris Lattner4fd59b02018-07-20 09:35:47 -070055 /// This is the operation set for the current context if it is knowable (a
56 /// context could be determined), otherwise this is null.
57 OperationSet *const operationSet;
MLIR Team4718bc92018-07-17 16:56:54 -070058
Chris Lattner4fd59b02018-07-20 09:35:47 -070059 explicit ModuleState(MLIRContext *context)
60 : operationSet(context ? &OperationSet::get(context) : nullptr) {}
61
62 // Initializes module state, populating affine map state.
MLIR Team4718bc92018-07-17 16:56:54 -070063 void initialize(const Module *module);
64
MLIR Team54b55a22018-07-18 10:16:05 -070065 int getAffineMapId(const AffineMap *affineMap) const {
MLIR Team4718bc92018-07-17 16:56:54 -070066 auto it = affineMapIds.find(affineMap);
67 if (it == affineMapIds.end()) {
68 return -1;
69 }
70 return it->second;
71 }
72
James Molloyc4666722018-07-24 09:48:31 -070073 ArrayRef<const AffineMap *> getAffineMapIds() const { return affineMapsById; }
Chris Lattner4fd59b02018-07-20 09:35:47 -070074
MLIR Team54b55a22018-07-18 10:16:05 -070075private:
Chris Lattner4fd59b02018-07-20 09:35:47 -070076 void recordAffineMapReference(const AffineMap *affineMap) {
77 if (affineMapIds.count(affineMap) == 0) {
James Molloyc4666722018-07-24 09:48:31 -070078 affineMapIds[affineMap] = affineMapsById.size();
79 affineMapsById.push_back(affineMap);
Chris Lattner4fd59b02018-07-20 09:35:47 -070080 }
81 }
82
MLIR Team4718bc92018-07-17 16:56:54 -070083 // Visit functions.
84 void visitFunction(const Function *fn);
85 void visitExtFunction(const ExtFunction *fn);
86 void visitCFGFunction(const CFGFunction *fn);
87 void visitMLFunction(const MLFunction *fn);
88 void visitType(const Type *type);
MLIR Teamb61885d2018-07-18 16:29:21 -070089 void visitAttribute(const Attribute *attr);
90 void visitOperation(const Operation *op);
91
MLIR Team54b55a22018-07-18 10:16:05 -070092 DenseMap<const AffineMap *, int> affineMapIds;
James Molloyc4666722018-07-24 09:48:31 -070093 std::vector<const AffineMap *> affineMapsById;
MLIR Team4718bc92018-07-17 16:56:54 -070094};
James Molloy87d81022018-07-23 11:44:40 -070095} // end anonymous namespace
MLIR Team4718bc92018-07-17 16:56:54 -070096
97// TODO Support visiting other types/instructions when implemented.
98void ModuleState::visitType(const Type *type) {
Chris Lattner3164ae62018-07-28 09:36:25 -070099 if (auto *funcType = dyn_cast<FunctionType>(type)) {
MLIR Team4718bc92018-07-17 16:56:54 -0700100 // Visit input and result types for functions.
Chris Lattner3164ae62018-07-28 09:36:25 -0700101 for (auto *input : funcType->getInputs())
MLIR Team4718bc92018-07-17 16:56:54 -0700102 visitType(input);
Chris Lattner3164ae62018-07-28 09:36:25 -0700103 for (auto *result : funcType->getResults())
MLIR Team4718bc92018-07-17 16:56:54 -0700104 visitType(result);
Chris Lattner3164ae62018-07-28 09:36:25 -0700105 } else if (auto *memref = dyn_cast<MemRefType>(type)) {
MLIR Team4718bc92018-07-17 16:56:54 -0700106 // Visit affine maps in memref type.
Chris Lattner3164ae62018-07-28 09:36:25 -0700107 for (auto *map : memref->getAffineMaps()) {
MLIR Team4718bc92018-07-17 16:56:54 -0700108 recordAffineMapReference(map);
109 }
110 }
111}
112
MLIR Teamb61885d2018-07-18 16:29:21 -0700113void ModuleState::visitAttribute(const Attribute *attr) {
Chris Lattner3164ae62018-07-28 09:36:25 -0700114 if (auto *mapAttr = dyn_cast<AffineMapAttr>(attr)) {
115 recordAffineMapReference(mapAttr->getValue());
116 } else if (auto *array = dyn_cast<ArrayAttr>(attr)) {
117 for (auto elt : array->getValue()) {
MLIR Teamb61885d2018-07-18 16:29:21 -0700118 visitAttribute(elt);
119 }
120 }
121}
122
123void ModuleState::visitOperation(const Operation *op) {
Chris Lattnerca2ee872018-07-31 18:32:59 -0700124 // Visit all the types used in the operation.
125 for (auto *operand : op->getOperands())
126 visitType(operand->getType());
127 for (auto *result : op->getResults())
128 visitType(result->getType());
129
130 // Visit each of the attributes.
131 for (auto elt : op->getAttrs())
MLIR Teamb61885d2018-07-18 16:29:21 -0700132 visitAttribute(elt.second);
MLIR Teamb61885d2018-07-18 16:29:21 -0700133}
134
MLIR Team4718bc92018-07-17 16:56:54 -0700135void ModuleState::visitExtFunction(const ExtFunction *fn) {
136 visitType(fn->getType());
137}
138
139void ModuleState::visitCFGFunction(const CFGFunction *fn) {
140 visitType(fn->getType());
MLIR Teamb61885d2018-07-18 16:29:21 -0700141 for (auto &block : *fn) {
142 for (auto &op : block.getOperations()) {
143 visitOperation(&op);
144 }
145 }
MLIR Team4718bc92018-07-17 16:56:54 -0700146}
147
148void ModuleState::visitMLFunction(const MLFunction *fn) {
149 visitType(fn->getType());
MLIR Teamb61885d2018-07-18 16:29:21 -0700150 // TODO Visit function body statements (and attributes if required).
MLIR Team4718bc92018-07-17 16:56:54 -0700151}
152
153void ModuleState::visitFunction(const Function *fn) {
154 switch (fn->getKind()) {
MLIR Team54b55a22018-07-18 10:16:05 -0700155 case Function::Kind::ExtFunc:
156 return visitExtFunction(cast<ExtFunction>(fn));
157 case Function::Kind::CFGFunc:
158 return visitCFGFunction(cast<CFGFunction>(fn));
159 case Function::Kind::MLFunc:
160 return visitMLFunction(cast<MLFunction>(fn));
MLIR Team4718bc92018-07-17 16:56:54 -0700161 }
162}
163
Chris Lattner4fd59b02018-07-20 09:35:47 -0700164// Initializes module state, populating affine map state.
165void ModuleState::initialize(const Module *module) {
Chris Lattnera8e47672018-07-25 14:08:16 -0700166 for (auto &fn : *module) {
167 visitFunction(&fn);
Chris Lattner4fd59b02018-07-20 09:35:47 -0700168 }
169}
170
171//===----------------------------------------------------------------------===//
172// ModulePrinter
173//===----------------------------------------------------------------------===//
174
175namespace {
176class ModulePrinter {
177public:
178 ModulePrinter(raw_ostream &os, ModuleState &state) : os(os), state(state) {}
179 explicit ModulePrinter(const ModulePrinter &printer)
180 : os(printer.os), state(printer.state) {}
181
182 template <typename Container, typename UnaryFunctor>
183 inline void interleaveComma(const Container &c, UnaryFunctor each_fn) const {
184 interleave(c.begin(), c.end(), each_fn, [&]() { os << ", "; });
185 }
186
187 void print(const Module *module);
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700188 void printAttribute(const Attribute *attr);
189 void printType(const Type *type);
Chris Lattner4fd59b02018-07-20 09:35:47 -0700190 void print(const Function *fn);
191 void print(const ExtFunction *fn);
192 void print(const CFGFunction *fn);
193 void print(const MLFunction *fn);
194
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700195 void printAffineMap(const AffineMap *map);
196 void printAffineExpr(const AffineExpr *expr);
Chris Lattner4fd59b02018-07-20 09:35:47 -0700197
198protected:
199 raw_ostream &os;
200 ModuleState &state;
201
202 void printFunctionSignature(const Function *fn);
203 void printAffineMapId(int affineMapId) const;
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700204 void printAffineMapReference(const AffineMap *affineMap);
Chris Lattner4fd59b02018-07-20 09:35:47 -0700205
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700206 /// This enum is used to represent the binding stength of the enclosing
207 /// context that an AffineExpr is being printed in, so we can intelligently
208 /// produce parens.
209 enum class BindingStrength {
210 Weak, // + and -
211 Strong, // All other binary operators.
212 };
213 void printAffineExprInternal(const AffineExpr *expr,
214 BindingStrength enclosingTightness);
Chris Lattner4fd59b02018-07-20 09:35:47 -0700215};
216} // end anonymous namespace
217
MLIR Team4718bc92018-07-17 16:56:54 -0700218// Prints function with initialized module state.
Chris Lattner4fd59b02018-07-20 09:35:47 -0700219void ModulePrinter::print(const Function *fn) {
MLIR Team4718bc92018-07-17 16:56:54 -0700220 switch (fn->getKind()) {
MLIR Team54b55a22018-07-18 10:16:05 -0700221 case Function::Kind::ExtFunc:
222 return print(cast<ExtFunction>(fn));
223 case Function::Kind::CFGFunc:
224 return print(cast<CFGFunction>(fn));
225 case Function::Kind::MLFunc:
226 return print(cast<MLFunction>(fn));
MLIR Team4718bc92018-07-17 16:56:54 -0700227 }
228}
229
230// Prints affine map identifier.
Chris Lattner4fd59b02018-07-20 09:35:47 -0700231void ModulePrinter::printAffineMapId(int affineMapId) const {
MLIR Team4718bc92018-07-17 16:56:54 -0700232 os << "#map" << affineMapId;
233}
234
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700235void ModulePrinter::printAffineMapReference(const AffineMap *affineMap) {
Chris Lattner4fd59b02018-07-20 09:35:47 -0700236 int mapId = state.getAffineMapId(affineMap);
MLIR Teamb61885d2018-07-18 16:29:21 -0700237 if (mapId >= 0) {
238 // Map will be printed at top of module so print reference to its id.
239 printAffineMapId(mapId);
240 } else {
241 // Map not in module state so print inline.
242 affineMap->print(os);
243 }
244}
245
Chris Lattner4fd59b02018-07-20 09:35:47 -0700246void ModulePrinter::print(const Module *module) {
James Molloyc4666722018-07-24 09:48:31 -0700247 for (const auto &map : state.getAffineMapIds()) {
248 printAffineMapId(state.getAffineMapId(map));
MLIR Team4718bc92018-07-17 16:56:54 -0700249 os << " = ";
James Molloyc4666722018-07-24 09:48:31 -0700250 map->print(os);
MLIR Team4718bc92018-07-17 16:56:54 -0700251 os << '\n';
252 }
Chris Lattnera8e47672018-07-25 14:08:16 -0700253 for (auto const &fn : *module)
254 print(&fn);
MLIR Team4718bc92018-07-17 16:56:54 -0700255}
256
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700257void ModulePrinter::printAttribute(const Attribute *attr) {
MLIR Teamb61885d2018-07-18 16:29:21 -0700258 switch (attr->getKind()) {
259 case Attribute::Kind::Bool:
260 os << (cast<BoolAttr>(attr)->getValue() ? "true" : "false");
261 break;
262 case Attribute::Kind::Integer:
263 os << cast<IntegerAttr>(attr)->getValue();
264 break;
265 case Attribute::Kind::Float:
266 // FIXME: this isn't precise, we should print with a hex format.
267 os << cast<FloatAttr>(attr)->getValue();
268 break;
269 case Attribute::Kind::String:
270 // FIXME: should escape the string.
271 os << '"' << cast<StringAttr>(attr)->getValue() << '"';
272 break;
273 case Attribute::Kind::Array: {
274 auto elts = cast<ArrayAttr>(attr)->getValue();
275 os << '[';
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700276 interleaveComma(elts, [&](Attribute *attr) { printAttribute(attr); });
MLIR Teamb61885d2018-07-18 16:29:21 -0700277 os << ']';
278 break;
279 }
280 case Attribute::Kind::AffineMap:
281 printAffineMapReference(cast<AffineMapAttr>(attr)->getValue());
282 break;
283 }
284}
285
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700286void ModulePrinter::printType(const Type *type) {
MLIR Team4718bc92018-07-17 16:56:54 -0700287 switch (type->getKind()) {
MLIR Team54b55a22018-07-18 10:16:05 -0700288 case Type::Kind::AffineInt:
289 os << "affineint";
290 return;
291 case Type::Kind::BF16:
292 os << "bf16";
293 return;
294 case Type::Kind::F16:
295 os << "f16";
296 return;
297 case Type::Kind::F32:
298 os << "f32";
299 return;
300 case Type::Kind::F64:
301 os << "f64";
302 return;
Jacques Pienaarc0d69302018-07-27 11:07:12 -0700303 case Type::Kind::TFControl:
304 os << "tf_control";
305 return;
James Molloy72b0cbe2018-08-01 12:55:27 -0700306 case Type::Kind::TFString:
307 os << "tf_string";
308 return;
MLIR Team4718bc92018-07-17 16:56:54 -0700309
310 case Type::Kind::Integer: {
311 auto *integer = cast<IntegerType>(type);
312 os << 'i' << integer->getWidth();
313 return;
314 }
315 case Type::Kind::Function: {
316 auto *func = cast<FunctionType>(type);
317 os << '(';
Chris Lattner413db6a2018-07-25 12:55:50 -0700318 interleaveComma(func->getInputs(), [&](Type *type) { printType(type); });
MLIR Team4718bc92018-07-17 16:56:54 -0700319 os << ") -> ";
320 auto results = func->getResults();
321 if (results.size() == 1)
322 os << *results[0];
323 else {
324 os << '(';
Chris Lattner413db6a2018-07-25 12:55:50 -0700325 interleaveComma(results, [&](Type *type) { printType(type); });
MLIR Team4718bc92018-07-17 16:56:54 -0700326 os << ')';
327 }
328 return;
329 }
330 case Type::Kind::Vector: {
331 auto *v = cast<VectorType>(type);
332 os << "vector<";
James Molloy87d81022018-07-23 11:44:40 -0700333 for (auto dim : v->getShape())
334 os << dim << 'x';
MLIR Team4718bc92018-07-17 16:56:54 -0700335 os << *v->getElementType() << '>';
336 return;
337 }
338 case Type::Kind::RankedTensor: {
339 auto *v = cast<RankedTensorType>(type);
340 os << "tensor<";
341 for (auto dim : v->getShape()) {
342 if (dim < 0)
343 os << '?';
344 else
345 os << dim;
346 os << 'x';
347 }
348 os << *v->getElementType() << '>';
349 return;
350 }
351 case Type::Kind::UnrankedTensor: {
352 auto *v = cast<UnrankedTensorType>(type);
Chris Lattner413db6a2018-07-25 12:55:50 -0700353 os << "tensor<??";
354 printType(v->getElementType());
355 os << '>';
MLIR Team4718bc92018-07-17 16:56:54 -0700356 return;
357 }
358 case Type::Kind::MemRef: {
359 auto *v = cast<MemRefType>(type);
360 os << "memref<";
361 for (auto dim : v->getShape()) {
362 if (dim < 0)
363 os << '?';
364 else
365 os << dim;
366 os << 'x';
367 }
Chris Lattner413db6a2018-07-25 12:55:50 -0700368 printType(v->getElementType());
MLIR Team4718bc92018-07-17 16:56:54 -0700369 for (auto map : v->getAffineMaps()) {
370 os << ", ";
MLIR Teamb61885d2018-07-18 16:29:21 -0700371 printAffineMapReference(map);
MLIR Team4718bc92018-07-17 16:56:54 -0700372 }
Chris Lattner413db6a2018-07-25 12:55:50 -0700373 // Only print the memory space if it is the non-default one.
374 if (v->getMemorySpace())
375 os << ", " << v->getMemorySpace();
MLIR Team4718bc92018-07-17 16:56:54 -0700376 os << '>';
377 return;
378 }
379 }
380}
381
382//===----------------------------------------------------------------------===//
Chris Lattner4fd59b02018-07-20 09:35:47 -0700383// Affine expressions and maps
384//===----------------------------------------------------------------------===//
385
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700386void ModulePrinter::printAffineExpr(const AffineExpr *expr) {
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700387 printAffineExprInternal(expr, BindingStrength::Weak);
388}
389
390void ModulePrinter::printAffineExprInternal(
391 const AffineExpr *expr, BindingStrength enclosingTightness) {
392 const char *binopSpelling = nullptr;
Chris Lattner4fd59b02018-07-20 09:35:47 -0700393 switch (expr->getKind()) {
394 case AffineExpr::Kind::SymbolId:
395 os << 's' << cast<AffineSymbolExpr>(expr)->getPosition();
396 return;
397 case AffineExpr::Kind::DimId:
398 os << 'd' << cast<AffineDimExpr>(expr)->getPosition();
399 return;
400 case AffineExpr::Kind::Constant:
401 os << cast<AffineConstantExpr>(expr)->getValue();
402 return;
403 case AffineExpr::Kind::Add:
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700404 binopSpelling = " + ";
405 break;
Chris Lattner4fd59b02018-07-20 09:35:47 -0700406 case AffineExpr::Kind::Mul:
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700407 binopSpelling = " * ";
408 break;
Chris Lattner4fd59b02018-07-20 09:35:47 -0700409 case AffineExpr::Kind::FloorDiv:
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700410 binopSpelling = " floordiv ";
411 break;
Chris Lattner4fd59b02018-07-20 09:35:47 -0700412 case AffineExpr::Kind::CeilDiv:
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700413 binopSpelling = " ceildiv ";
414 break;
Chris Lattner4fd59b02018-07-20 09:35:47 -0700415 case AffineExpr::Kind::Mod:
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700416 binopSpelling = " mod ";
417 break;
Chris Lattner4fd59b02018-07-20 09:35:47 -0700418 }
Chris Lattner4fd59b02018-07-20 09:35:47 -0700419
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700420 auto *binOp = cast<AffineBinaryOpExpr>(expr);
Chris Lattner4fd59b02018-07-20 09:35:47 -0700421
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700422 // Handle tightly binding binary operators.
423 if (binOp->getKind() != AffineExpr::Kind::Add) {
424 if (enclosingTightness == BindingStrength::Strong)
425 os << '(';
426
427 printAffineExprInternal(binOp->getLHS(), BindingStrength::Strong);
428 os << binopSpelling;
429 printAffineExprInternal(binOp->getRHS(), BindingStrength::Strong);
430
431 if (enclosingTightness == BindingStrength::Strong)
432 os << ')';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700433 return;
434 }
435
436 // Print out special "pretty" forms for add.
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700437 if (enclosingTightness == BindingStrength::Strong)
438 os << '(';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700439
440 // Pretty print addition to a product that has a negative operand as a
441 // subtraction.
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700442 if (auto *rhs = dyn_cast<AffineBinaryOpExpr>(binOp->getRHS())) {
Chris Lattner4fd59b02018-07-20 09:35:47 -0700443 if (rhs->getKind() == AffineExpr::Kind::Mul) {
444 if (auto *rrhs = dyn_cast<AffineConstantExpr>(rhs->getRHS())) {
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700445 if (rrhs->getValue() == -1) {
446 printAffineExprInternal(binOp->getLHS(), BindingStrength::Weak);
447 os << " - ";
448 printAffineExprInternal(rhs->getLHS(), BindingStrength::Weak);
449
450 if (enclosingTightness == BindingStrength::Strong)
451 os << ')';
452 return;
453 }
454
455 if (rrhs->getValue() < -1) {
456 printAffineExprInternal(binOp->getLHS(), BindingStrength::Weak);
Uday Bondhugula970f5b82018-08-01 22:02:00 -0700457 os << " - ";
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700458 printAffineExprInternal(rhs->getLHS(), BindingStrength::Strong);
Uday Bondhugula970f5b82018-08-01 22:02:00 -0700459 os << " * " << -rrhs->getValue();
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700460 if (enclosingTightness == BindingStrength::Strong)
461 os << ')';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700462 return;
463 }
464 }
465 }
466 }
467
468 // Pretty print addition to a negative number as a subtraction.
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700469 if (auto *rhs = dyn_cast<AffineConstantExpr>(binOp->getRHS())) {
Chris Lattner4fd59b02018-07-20 09:35:47 -0700470 if (rhs->getValue() < 0) {
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700471 printAffineExprInternal(binOp->getLHS(), BindingStrength::Weak);
472 os << " - " << -rhs->getValue() << ')';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700473 return;
474 }
475 }
476
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700477 printAffineExprInternal(binOp->getLHS(), BindingStrength::Weak);
Chris Lattner4fd59b02018-07-20 09:35:47 -0700478 os << " + ";
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700479 printAffineExprInternal(binOp->getRHS(), BindingStrength::Weak);
480
481 if (enclosingTightness == BindingStrength::Strong)
482 os << ')';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700483}
484
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700485void ModulePrinter::printAffineMap(const AffineMap *map) {
Chris Lattner4fd59b02018-07-20 09:35:47 -0700486 // Dimension identifiers.
487 os << '(';
Chris Lattnerdc3ba382018-07-29 14:13:03 -0700488 for (int i = 0; i < (int)map->getNumDims() - 1; ++i)
489 os << 'd' << i << ", ";
Chris Lattner4fd59b02018-07-20 09:35:47 -0700490 if (map->getNumDims() >= 1)
Chris Lattnerdc3ba382018-07-29 14:13:03 -0700491 os << 'd' << map->getNumDims() - 1;
492 os << ')';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700493
494 // Symbolic identifiers.
Chris Lattnerdc3ba382018-07-29 14:13:03 -0700495 if (map->getNumSymbols() != 0) {
496 os << '[';
497 for (unsigned i = 0; i < map->getNumSymbols() - 1; ++i)
498 os << 's' << i << ", ";
Chris Lattner4fd59b02018-07-20 09:35:47 -0700499 if (map->getNumSymbols() >= 1)
Chris Lattnerdc3ba382018-07-29 14:13:03 -0700500 os << 's' << map->getNumSymbols() - 1;
501 os << ']';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700502 }
503
504 // AffineMap should have at least one result.
505 assert(!map->getResults().empty());
506 // Result affine expressions.
507 os << " -> (";
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700508 interleaveComma(map->getResults(),
509 [&](AffineExpr *expr) { printAffineExpr(expr); });
Chris Lattnerdc3ba382018-07-29 14:13:03 -0700510 os << ')';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700511
512 if (!map->isBounded()) {
513 return;
514 }
515
516 // Print range sizes for bounded affine maps.
517 os << " size (";
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700518 interleaveComma(map->getRangeSizes(),
519 [&](AffineExpr *expr) { printAffineExpr(expr); });
Chris Lattnerdc3ba382018-07-29 14:13:03 -0700520 os << ')';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700521}
522
523//===----------------------------------------------------------------------===//
Chris Lattner4c95a502018-06-23 16:03:42 -0700524// Function printing
525//===----------------------------------------------------------------------===//
526
Chris Lattner4fd59b02018-07-20 09:35:47 -0700527void ModulePrinter::printFunctionSignature(const Function *fn) {
Chris Lattner4c95a502018-06-23 16:03:42 -0700528 auto type = fn->getType();
529
530 os << "@" << fn->getName() << '(';
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700531 interleaveComma(type->getInputs(),
532 [&](Type *eltType) { printType(eltType); });
Chris Lattner4c95a502018-06-23 16:03:42 -0700533 os << ')';
534
535 switch (type->getResults().size()) {
MLIR Team54b55a22018-07-18 10:16:05 -0700536 case 0:
537 break;
Chris Lattner4c95a502018-06-23 16:03:42 -0700538 case 1:
MLIR Team4718bc92018-07-17 16:56:54 -0700539 os << " -> ";
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700540 printType(type->getResults()[0]);
Chris Lattner4c95a502018-06-23 16:03:42 -0700541 break;
542 default:
543 os << " -> (";
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700544 interleaveComma(type->getResults(),
545 [&](Type *eltType) { printType(eltType); });
Chris Lattner4c95a502018-06-23 16:03:42 -0700546 os << ')';
547 break;
548 }
549}
550
Chris Lattner4fd59b02018-07-20 09:35:47 -0700551void ModulePrinter::print(const ExtFunction *fn) {
Chris Lattner4c95a502018-06-23 16:03:42 -0700552 os << "extfunc ";
Chris Lattner4fd59b02018-07-20 09:35:47 -0700553 printFunctionSignature(fn);
MLIR Team54b55a22018-07-18 10:16:05 -0700554 os << '\n';
Chris Lattner4c95a502018-06-23 16:03:42 -0700555}
556
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700557namespace {
558
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700559// FunctionPrinter contains common functionality for printing
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700560// CFG and ML functions.
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700561class FunctionPrinter : public ModulePrinter, private OpAsmPrinter {
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700562public:
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700563 FunctionPrinter(const ModulePrinter &other) : ModulePrinter(other) {}
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700564
565 void printOperation(const Operation *op);
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700566 void printDefaultOp(const Operation *op);
567
568 // Implement OpAsmPrinter.
569 raw_ostream &getStream() const { return os; }
570 void printType(const Type *type) { ModulePrinter::printType(type); }
571 void printAttribute(const Attribute *attr) {
572 ModulePrinter::printAttribute(attr);
573 }
574 void printAffineMap(const AffineMap *map) {
Chris Lattner3164ae62018-07-28 09:36:25 -0700575 return ModulePrinter::printAffineMapReference(map);
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700576 }
577 void printAffineExpr(const AffineExpr *expr) {
578 return ModulePrinter::printAffineExpr(expr);
579 }
580
581 void printOperand(const SSAValue *value) { printValueID(value); }
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700582
Chris Lattnerd4964212018-08-01 10:43:18 -0700583 enum { nameSentinel = ~0U };
584
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700585protected:
Chris Lattnerf8cce872018-07-20 09:28:54 -0700586 void numberValueID(const SSAValue *value) {
587 assert(!valueIDs.count(value) && "Value numbered multiple times");
Chris Lattnerd4964212018-08-01 10:43:18 -0700588
589 SmallString<32> specialNameBuffer;
590 llvm::raw_svector_ostream specialName(specialNameBuffer);
591
592 // Give constant integers special names.
593 if (auto *op = value->getDefiningOperation()) {
594 if (auto intOp = op->getAs<ConstantIntOp>()) {
595 specialName << 'c' << intOp->getValue();
596 if (!intOp->getType()->isAffineInt())
597 specialName << '_' << *intOp->getType();
598 }
Tatiana Shpeisman3838db72018-07-30 15:18:10 -0700599 }
Chris Lattnerd4964212018-08-01 10:43:18 -0700600
601 if (specialNameBuffer.empty()) {
602 switch (value->getKind()) {
603 case SSAValueKind::BBArgument:
604 // If this is an argument to the function, give it an 'arg' name.
605 if (auto *bb = cast<BBArgument>(value)->getOwner())
606 if (auto *fn = bb->getFunction())
607 if (&fn->front() == bb) {
608 specialName << "arg" << nextArgumentID++;
609 break;
610 }
611 // Otherwise number it normally.
612 LLVM_FALLTHROUGH;
613 case SSAValueKind::InstResult:
614 case SSAValueKind::StmtResult:
615 // This is an uninteresting result, give it a boring number and be
616 // done with it.
617 valueIDs[value] = nextValueID++;
618 return;
619 case SSAValueKind::FnArgument:
620 specialName << "arg" << nextArgumentID++;
621 break;
622 case SSAValueKind::ForStmt:
623 specialName << 'i' << nextLoopID++;
624 break;
625 }
626 }
627
628 // Ok, this value had an interesting name. Remember it with a sentinel.
629 valueIDs[value] = nameSentinel;
630
631 // Remember that we've used this name, checking to see if we had a conflict.
632 auto insertRes = usedNames.insert(specialName.str());
633 if (insertRes.second) {
634 // If this is the first use of the name, then we're successful!
635 valueNames[value] = insertRes.first->first();
636 return;
637 }
638
639 // Otherwise, we had a conflict - probe until we find a unique name. This
640 // is guaranteed to terminate (and usually in a single iteration) because it
641 // generates new names by incrementing nextConflictID.
642 while (1) {
643 std::string probeName =
644 specialName.str().str() + "_" + llvm::utostr(nextConflictID++);
645 insertRes = usedNames.insert(probeName);
646 if (insertRes.second) {
647 // If this is the first use of the name, then we're successful!
648 valueNames[value] = insertRes.first->first();
649 return;
650 }
651 }
Chris Lattnerf8cce872018-07-20 09:28:54 -0700652 }
653
Tatiana Shpeisman3838db72018-07-30 15:18:10 -0700654 void printValueID(const SSAValue *value, bool printResultNo = true) const {
Chris Lattner6119d382018-07-20 18:41:34 -0700655 int resultNo = -1;
656 auto lookupValue = value;
657
Tatiana Shpeisman3838db72018-07-30 15:18:10 -0700658 // If this is a reference to the result of a multi-result instruction or
659 // statement, print out the # identifier and make sure to map our lookup
660 // to the first result of the instruction.
Chris Lattner6119d382018-07-20 18:41:34 -0700661 if (auto *result = dyn_cast<InstResult>(value)) {
662 if (result->getOwner()->getNumResults() != 1) {
663 resultNo = result->getResultNumber();
664 lookupValue = result->getOwner()->getResult(0);
665 }
Tatiana Shpeisman3838db72018-07-30 15:18:10 -0700666 } else if (auto *result = dyn_cast<StmtResult>(value)) {
667 if (result->getOwner()->getNumResults() != 1) {
668 resultNo = result->getResultNumber();
669 lookupValue = result->getOwner()->getResult(0);
670 }
Chris Lattner6119d382018-07-20 18:41:34 -0700671 }
672
673 auto it = valueIDs.find(lookupValue);
674 if (it == valueIDs.end()) {
Chris Lattnerf8cce872018-07-20 09:28:54 -0700675 os << "<<INVALID SSA VALUE>>";
Chris Lattner6119d382018-07-20 18:41:34 -0700676 return;
677 }
678
Tatiana Shpeisman3838db72018-07-30 15:18:10 -0700679 os << '%';
Chris Lattnerd4964212018-08-01 10:43:18 -0700680 if (it->second != nameSentinel) {
681 os << it->second;
682 } else {
683 auto nameIt = valueNames.find(lookupValue);
684 assert(nameIt != valueNames.end() && "Didn't have a name entry?");
685 os << nameIt->second;
686 }
Tatiana Shpeisman3838db72018-07-30 15:18:10 -0700687
Tatiana Shpeisman3838db72018-07-30 15:18:10 -0700688 if (resultNo != -1 && printResultNo)
Chris Lattner6119d382018-07-20 18:41:34 -0700689 os << '#' << resultNo;
Chris Lattnerf8cce872018-07-20 09:28:54 -0700690 }
691
692private:
Chris Lattnerd4964212018-08-01 10:43:18 -0700693 /// This is the value ID for each SSA value in the current function. If this
694 /// returns ~0, then the valueID has an entry in valueNames.
Chris Lattnerf8cce872018-07-20 09:28:54 -0700695 DenseMap<const SSAValue *, unsigned> valueIDs;
Chris Lattnerd4964212018-08-01 10:43:18 -0700696 DenseMap<const SSAValue *, StringRef> valueNames;
697
698 /// This keeps track of all of the non-numeric names that are in flight,
699 /// allowing us to check for duplicates.
700 llvm::StringSet<> usedNames;
701
702 /// This is the next value ID to assign in numbering.
Chris Lattnerf8cce872018-07-20 09:28:54 -0700703 unsigned nextValueID = 0;
Chris Lattnerd4964212018-08-01 10:43:18 -0700704 /// This is the ID to assign to the next induction variable.
Tatiana Shpeismanc9c4b342018-07-31 07:40:14 -0700705 unsigned nextLoopID = 0;
Chris Lattnerd4964212018-08-01 10:43:18 -0700706 /// This is the next ID to assign to an MLFunction argument.
707 unsigned nextArgumentID = 0;
708
709 /// This is the next ID to assign when a name conflict is detected.
710 unsigned nextConflictID = 0;
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700711};
James Molloy87d81022018-07-23 11:44:40 -0700712} // end anonymous namespace
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700713
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700714void FunctionPrinter::printOperation(const Operation *op) {
Chris Lattnerac591f12018-07-22 21:02:26 -0700715 if (op->getNumResults()) {
Tatiana Shpeisman3838db72018-07-30 15:18:10 -0700716 printValueID(op->getResult(0), /*printResultNo=*/false);
Chris Lattnerac591f12018-07-22 21:02:26 -0700717 os << " = ";
Chris Lattnerf8cce872018-07-20 09:28:54 -0700718 }
719
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700720 // Check to see if this is a known operation. If so, use the registered
721 // custom printer hook.
Chris Lattner4fd59b02018-07-20 09:35:47 -0700722 if (auto opInfo = state.operationSet->lookup(op->getName().str())) {
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700723 opInfo->printAssembly(op, this);
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700724 return;
725 }
726
Chris Lattnerf8cce872018-07-20 09:28:54 -0700727 // Otherwise use the standard verbose printing approach.
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700728 printDefaultOp(op);
729}
Chris Lattnerf8cce872018-07-20 09:28:54 -0700730
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700731void FunctionPrinter::printDefaultOp(const Operation *op) {
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700732 // TODO: escape name if necessary.
Chris Lattnerf8cce872018-07-20 09:28:54 -0700733 os << "\"" << op->getName().str() << "\"(";
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700734
Chris Lattnerac591f12018-07-22 21:02:26 -0700735 interleaveComma(op->getOperands(),
736 [&](const SSAValue *value) { printValueID(value); });
Chris Lattner7f9cc272018-07-19 08:35:28 -0700737
Chris Lattnerf8cce872018-07-20 09:28:54 -0700738 os << ')';
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700739 auto attrs = op->getAttrs();
740 if (!attrs.empty()) {
741 os << '{';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700742 interleaveComma(attrs, [&](NamedAttribute attr) {
Chris Lattnerf8cce872018-07-20 09:28:54 -0700743 os << attr.first << ": ";
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700744 printAttribute(attr.second);
Chris Lattnerf8cce872018-07-20 09:28:54 -0700745 });
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700746 os << '}';
747 }
Chris Lattner3b2ef762018-07-18 15:31:25 -0700748
Chris Lattnerac591f12018-07-22 21:02:26 -0700749 // Print the type signature of the operation.
750 os << " : (";
751 interleaveComma(op->getOperands(),
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700752 [&](const SSAValue *value) { printType(value->getType()); });
Chris Lattnerac591f12018-07-22 21:02:26 -0700753 os << ") -> ";
Chris Lattnerf8cce872018-07-20 09:28:54 -0700754
Chris Lattnerac591f12018-07-22 21:02:26 -0700755 if (op->getNumResults() == 1) {
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700756 printType(op->getResult(0)->getType());
Chris Lattnerac591f12018-07-22 21:02:26 -0700757 } else {
758 os << '(';
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700759 interleaveComma(op->getResults(), [&](const SSAValue *result) {
760 printType(result->getType());
761 });
Chris Lattnerac591f12018-07-22 21:02:26 -0700762 os << ')';
Chris Lattnerf8cce872018-07-20 09:28:54 -0700763 }
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700764}
765
Chris Lattner4c95a502018-06-23 16:03:42 -0700766//===----------------------------------------------------------------------===//
767// CFG Function printing
768//===----------------------------------------------------------------------===//
769
770namespace {
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700771class CFGFunctionPrinter : public FunctionPrinter {
Chris Lattner4c95a502018-06-23 16:03:42 -0700772public:
Chris Lattner4fd59b02018-07-20 09:35:47 -0700773 CFGFunctionPrinter(const CFGFunction *function, const ModulePrinter &other);
Chris Lattner4c95a502018-06-23 16:03:42 -0700774
775 const CFGFunction *getFunction() const { return function; }
776
777 void print();
778 void print(const BasicBlock *block);
Chris Lattnered65a732018-06-28 20:45:33 -0700779
780 void print(const Instruction *inst);
781 void print(const OperationInst *inst);
782 void print(const ReturnInst *inst);
783 void print(const BranchInst *inst);
James Molloy4f788372018-07-24 15:01:27 -0700784 void print(const CondBranchInst *inst);
Chris Lattner4c95a502018-06-23 16:03:42 -0700785
786 unsigned getBBID(const BasicBlock *block) {
787 auto it = basicBlockIDs.find(block);
788 assert(it != basicBlockIDs.end() && "Block not in this function?");
789 return it->second;
790 }
791
792private:
793 const CFGFunction *function;
MLIR Team54b55a22018-07-18 10:16:05 -0700794 DenseMap<const BasicBlock *, unsigned> basicBlockIDs;
Chris Lattnerf8cce872018-07-20 09:28:54 -0700795
Chris Lattner4fd59b02018-07-20 09:35:47 -0700796 void numberValuesInBlock(const BasicBlock *block);
Chris Lattner4c95a502018-06-23 16:03:42 -0700797};
James Molloy87d81022018-07-23 11:44:40 -0700798} // end anonymous namespace
Chris Lattner4c95a502018-06-23 16:03:42 -0700799
Chris Lattner4fd59b02018-07-20 09:35:47 -0700800CFGFunctionPrinter::CFGFunctionPrinter(const CFGFunction *function,
801 const ModulePrinter &other)
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700802 : FunctionPrinter(other), function(function) {
Chris Lattner4c95a502018-06-23 16:03:42 -0700803 // Each basic block gets a unique ID per function.
804 unsigned blockID = 0;
Chris Lattnerf8cce872018-07-20 09:28:54 -0700805 for (auto &block : *function) {
806 basicBlockIDs[&block] = blockID++;
Chris Lattner4fd59b02018-07-20 09:35:47 -0700807 numberValuesInBlock(&block);
Chris Lattnerf8cce872018-07-20 09:28:54 -0700808 }
809}
810
811/// Number all of the SSA values in the specified basic block.
Chris Lattner4fd59b02018-07-20 09:35:47 -0700812void CFGFunctionPrinter::numberValuesInBlock(const BasicBlock *block) {
James Molloy61a656c2018-07-22 15:45:24 -0700813 for (auto *arg : block->getArguments()) {
814 numberValueID(arg);
815 }
Chris Lattnerf8cce872018-07-20 09:28:54 -0700816 for (auto &op : *block) {
817 // We number instruction that have results, and we only number the first
818 // result.
819 if (op.getNumResults() != 0)
820 numberValueID(op.getResult(0));
821 }
822
823 // Terminators do not define values.
Chris Lattner4c95a502018-06-23 16:03:42 -0700824}
825
Chris Lattner4fd59b02018-07-20 09:35:47 -0700826void CFGFunctionPrinter::print() {
Chris Lattner4c95a502018-06-23 16:03:42 -0700827 os << "cfgfunc ";
Chris Lattner4fd59b02018-07-20 09:35:47 -0700828 printFunctionSignature(getFunction());
Chris Lattner4c95a502018-06-23 16:03:42 -0700829 os << " {\n";
830
James Molloy87d81022018-07-23 11:44:40 -0700831 for (auto &block : *function)
832 print(&block);
Chris Lattner4c95a502018-06-23 16:03:42 -0700833 os << "}\n\n";
834}
835
Chris Lattner4fd59b02018-07-20 09:35:47 -0700836void CFGFunctionPrinter::print(const BasicBlock *block) {
James Molloy61a656c2018-07-22 15:45:24 -0700837 os << "bb" << getBBID(block);
Chris Lattner4c95a502018-06-23 16:03:42 -0700838
James Molloy61a656c2018-07-22 15:45:24 -0700839 if (!block->args_empty()) {
840 os << '(';
841 interleaveComma(block->getArguments(), [&](const BBArgument *arg) {
842 printValueID(arg);
843 os << ": ";
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700844 printType(arg->getType());
James Molloy61a656c2018-07-22 15:45:24 -0700845 });
846 os << ')';
847 }
Chris Lattner25ce3062018-07-27 11:10:12 -0700848 os << ':';
849
850 // Print out some context information about the predecessors of this block.
851 if (!block->getFunction()) {
852 os << "\t// block is not in a function!";
853 } else if (block->hasNoPredecessors()) {
854 // Don't print "no predecessors" for the entry block.
855 if (block != &block->getFunction()->front())
856 os << "\t// no predecessors";
857 } else if (auto *pred = block->getSinglePredecessor()) {
858 os << "\t// pred: bb" << getBBID(pred);
859 } else {
860 // We want to print the predecessors in increasing numeric order, not in
861 // whatever order the use-list is in, so gather and sort them.
862 SmallVector<unsigned, 4> predIDs;
863 for (auto *pred : block->getPredecessors())
864 predIDs.push_back(getBBID(pred));
865 llvm::array_pod_sort(predIDs.begin(), predIDs.end());
866
867 os << "\t// " << predIDs.size() << " preds: ";
868
869 interleaveComma(predIDs, [&](unsigned predID) { os << "bb" << predID; });
870 }
871 os << '\n';
James Molloy61a656c2018-07-22 15:45:24 -0700872
Jacques Pienaarb020c542018-07-15 00:06:54 -0700873 for (auto &inst : block->getOperations()) {
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -0700874 os << " ";
Chris Lattner3a467cc2018-07-01 20:28:00 -0700875 print(&inst);
James Molloy61a656c2018-07-22 15:45:24 -0700876 os << '\n';
Jacques Pienaarb020c542018-07-15 00:06:54 -0700877 }
Chris Lattner4c95a502018-06-23 16:03:42 -0700878
879 print(block->getTerminator());
James Molloy61a656c2018-07-22 15:45:24 -0700880 os << '\n';
Chris Lattner4c95a502018-06-23 16:03:42 -0700881}
882
Chris Lattner4fd59b02018-07-20 09:35:47 -0700883void CFGFunctionPrinter::print(const Instruction *inst) {
Chris Lattner4c95a502018-06-23 16:03:42 -0700884 switch (inst->getKind()) {
Chris Lattnered65a732018-06-28 20:45:33 -0700885 case Instruction::Kind::Operation:
886 return print(cast<OperationInst>(inst));
Chris Lattnerf6d80a02018-06-24 11:18:29 -0700887 case TerminatorInst::Kind::Branch:
Chris Lattnered65a732018-06-28 20:45:33 -0700888 return print(cast<BranchInst>(inst));
James Molloy4f788372018-07-24 15:01:27 -0700889 case TerminatorInst::Kind::CondBranch:
890 return print(cast<CondBranchInst>(inst));
Chris Lattner4c95a502018-06-23 16:03:42 -0700891 case TerminatorInst::Kind::Return:
Chris Lattnered65a732018-06-28 20:45:33 -0700892 return print(cast<ReturnInst>(inst));
Chris Lattner4c95a502018-06-23 16:03:42 -0700893 }
894}
895
Chris Lattner4fd59b02018-07-20 09:35:47 -0700896void CFGFunctionPrinter::print(const OperationInst *inst) {
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700897 printOperation(inst);
Chris Lattner3b2ef762018-07-18 15:31:25 -0700898}
Chris Lattner1604e472018-07-23 08:42:19 -0700899
Chris Lattner4fd59b02018-07-20 09:35:47 -0700900void CFGFunctionPrinter::print(const BranchInst *inst) {
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -0700901 os << "br bb" << getBBID(inst->getDest());
Chris Lattner1604e472018-07-23 08:42:19 -0700902
903 if (inst->getNumOperands() != 0) {
904 os << '(';
905 // TODO: Use getOperands() when we have it.
906 interleaveComma(inst->getInstOperands(), [&](const InstOperand &operand) {
907 printValueID(operand.get());
908 });
909 os << ") : ";
910 interleaveComma(inst->getInstOperands(), [&](const InstOperand &operand) {
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700911 printType(operand.get()->getType());
Chris Lattner1604e472018-07-23 08:42:19 -0700912 });
913 }
Chris Lattnered65a732018-06-28 20:45:33 -0700914}
Chris Lattner1604e472018-07-23 08:42:19 -0700915
James Molloy4f788372018-07-24 15:01:27 -0700916void CFGFunctionPrinter::print(const CondBranchInst *inst) {
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -0700917 os << "cond_br ";
James Molloy4f788372018-07-24 15:01:27 -0700918 printValueID(inst->getCondition());
919
920 os << ", bb" << getBBID(inst->getTrueDest());
921 if (inst->getNumTrueOperands() != 0) {
922 os << '(';
923 interleaveComma(inst->getTrueOperands(),
924 [&](const CFGValue *operand) { printValueID(operand); });
925 os << " : ";
926 interleaveComma(inst->getTrueOperands(), [&](const CFGValue *operand) {
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700927 printType(operand->getType());
James Molloy4f788372018-07-24 15:01:27 -0700928 });
929 os << ")";
930 }
931
932 os << ", bb" << getBBID(inst->getFalseDest());
933 if (inst->getNumFalseOperands() != 0) {
934 os << '(';
935 interleaveComma(inst->getFalseOperands(),
936 [&](const CFGValue *operand) { printValueID(operand); });
937 os << " : ";
938 interleaveComma(inst->getFalseOperands(), [&](const CFGValue *operand) {
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700939 printType(operand->getType());
James Molloy4f788372018-07-24 15:01:27 -0700940 });
941 os << ")";
942 }
943}
944
Chris Lattner40746442018-07-21 14:32:09 -0700945void CFGFunctionPrinter::print(const ReturnInst *inst) {
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -0700946 os << "return";
Chris Lattner40746442018-07-21 14:32:09 -0700947
948 if (inst->getNumOperands() != 0)
949 os << ' ';
950
James Molloy4f788372018-07-24 15:01:27 -0700951 interleaveComma(inst->getOperands(),
952 [&](const CFGValue *operand) { printValueID(operand); });
953 os << " : ";
Chris Lattnerac591f12018-07-22 21:02:26 -0700954 interleaveComma(inst->getOperands(), [&](const CFGValue *operand) {
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700955 printType(operand->getType());
Chris Lattner40746442018-07-21 14:32:09 -0700956 });
957}
MLIR Team54b55a22018-07-18 10:16:05 -0700958
Chris Lattner4fd59b02018-07-20 09:35:47 -0700959void ModulePrinter::print(const CFGFunction *fn) {
960 CFGFunctionPrinter(fn, *this).print();
Chris Lattnered65a732018-06-28 20:45:33 -0700961}
962
Chris Lattner4c95a502018-06-23 16:03:42 -0700963//===----------------------------------------------------------------------===//
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -0700964// ML Function printing
Chris Lattner4c95a502018-06-23 16:03:42 -0700965//===----------------------------------------------------------------------===//
966
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -0700967namespace {
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700968class MLFunctionPrinter : public FunctionPrinter {
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -0700969public:
Chris Lattner4fd59b02018-07-20 09:35:47 -0700970 MLFunctionPrinter(const MLFunction *function, const ModulePrinter &other);
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -0700971
972 const MLFunction *getFunction() const { return function; }
973
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -0700974 // Prints ML function
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -0700975 void print();
976
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -0700977 // Methods to print ML function statements
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -0700978 void print(const Statement *stmt);
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700979 void print(const OperationStmt *stmt);
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -0700980 void print(const ForStmt *stmt);
981 void print(const IfStmt *stmt);
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -0700982 void print(const StmtBlock *block);
983
984 // Number of spaces used for indenting nested statements
985 const static unsigned indentWidth = 2;
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -0700986
987private:
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -0700988 void numberValues();
989
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -0700990 const MLFunction *function;
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -0700991 int numSpaces;
992};
James Molloy87d81022018-07-23 11:44:40 -0700993} // end anonymous namespace
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -0700994
Chris Lattner4fd59b02018-07-20 09:35:47 -0700995MLFunctionPrinter::MLFunctionPrinter(const MLFunction *function,
996 const ModulePrinter &other)
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -0700997 : FunctionPrinter(other), function(function), numSpaces(0) {
998 numberValues();
999}
1000
1001/// Number all of the SSA values in this ML function.
1002void MLFunctionPrinter::numberValues() {
1003 // Visits all operation statements and numbers the first result.
Uday Bondhugula081d9e72018-07-27 10:58:14 -07001004 struct NumberValuesPass : public StmtWalker<NumberValuesPass> {
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -07001005 NumberValuesPass(MLFunctionPrinter *printer) : printer(printer) {}
1006 void visitOperationStmt(OperationStmt *stmt) {
1007 if (stmt->getNumResults() != 0)
1008 printer->numberValueID(stmt->getResult(0));
1009 }
Tatiana Shpeismanc9c4b342018-07-31 07:40:14 -07001010 void visitForStmt(ForStmt *stmt) { printer->numberValueID(stmt); }
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -07001011 MLFunctionPrinter *printer;
1012 };
1013
1014 NumberValuesPass pass(this);
1015 // TODO: it'd be cleaner to have constant visitor istead of using const_cast.
Uday Bondhugula081d9e72018-07-27 10:58:14 -07001016 pass.walk(const_cast<MLFunction *>(function));
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -07001017}
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001018
Chris Lattner4fd59b02018-07-20 09:35:47 -07001019void MLFunctionPrinter::print() {
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001020 os << "mlfunc ";
1021 // FIXME: should print argument names rather than just signature
Chris Lattner4fd59b02018-07-20 09:35:47 -07001022 printFunctionSignature(function);
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001023 os << " {\n";
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001024 print(function);
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001025 os << " return\n";
1026 os << "}\n\n";
1027}
1028
Chris Lattner4fd59b02018-07-20 09:35:47 -07001029void MLFunctionPrinter::print(const StmtBlock *block) {
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001030 numSpaces += indentWidth;
Jacques Pienaarb020c542018-07-15 00:06:54 -07001031 for (auto &stmt : block->getStatements()) {
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001032 print(&stmt);
Jacques Pienaarb020c542018-07-15 00:06:54 -07001033 os << "\n";
1034 }
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001035 numSpaces -= indentWidth;
1036}
1037
Chris Lattner4fd59b02018-07-20 09:35:47 -07001038void MLFunctionPrinter::print(const Statement *stmt) {
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001039 switch (stmt->getKind()) {
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001040 case Statement::Kind::Operation:
1041 return print(cast<OperationStmt>(stmt));
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001042 case Statement::Kind::For:
1043 return print(cast<ForStmt>(stmt));
1044 case Statement::Kind::If:
1045 return print(cast<IfStmt>(stmt));
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001046 }
1047}
1048
Chris Lattner4fd59b02018-07-20 09:35:47 -07001049void MLFunctionPrinter::print(const OperationStmt *stmt) {
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -07001050 os.indent(numSpaces);
Chris Lattner4fd59b02018-07-20 09:35:47 -07001051 printOperation(stmt);
1052}
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001053
Chris Lattner4fd59b02018-07-20 09:35:47 -07001054void MLFunctionPrinter::print(const ForStmt *stmt) {
Tatiana Shpeisman3838db72018-07-30 15:18:10 -07001055 os.indent(numSpaces) << "for ";
Tatiana Shpeismanc9c4b342018-07-31 07:40:14 -07001056 printOperand(stmt);
Tatiana Shpeisman3838db72018-07-30 15:18:10 -07001057 os << " = " << *stmt->getLowerBound();
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07001058 os << " to " << *stmt->getUpperBound();
1059 if (stmt->getStep()->getValue() != 1)
1060 os << " step " << *stmt->getStep();
1061
1062 os << " {\n";
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001063 print(static_cast<const StmtBlock *>(stmt));
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001064 os.indent(numSpaces) << "}";
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001065}
1066
Chris Lattner4fd59b02018-07-20 09:35:47 -07001067void MLFunctionPrinter::print(const IfStmt *stmt) {
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001068 os.indent(numSpaces) << "if () {\n";
1069 print(stmt->getThenClause());
1070 os.indent(numSpaces) << "}";
1071 if (stmt->hasElseClause()) {
1072 os << " else {\n";
1073 print(stmt->getElseClause());
1074 os.indent(numSpaces) << "}";
1075 }
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001076}
1077
Chris Lattner4fd59b02018-07-20 09:35:47 -07001078void ModulePrinter::print(const MLFunction *fn) {
1079 MLFunctionPrinter(fn, *this).print();
MLIR Team4718bc92018-07-17 16:56:54 -07001080}
1081
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001082//===----------------------------------------------------------------------===//
1083// print and dump methods
1084//===----------------------------------------------------------------------===//
Chris Lattnered65a732018-06-28 20:45:33 -07001085
MLIR Teamb61885d2018-07-18 16:29:21 -07001086void Attribute::print(raw_ostream &os) const {
Chris Lattner4fd59b02018-07-20 09:35:47 -07001087 ModuleState state(/*no context is known*/ nullptr);
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -07001088 ModulePrinter(os, state).printAttribute(this);
MLIR Teamb61885d2018-07-18 16:29:21 -07001089}
1090
James Molloy87d81022018-07-23 11:44:40 -07001091void Attribute::dump() const { print(llvm::errs()); }
MLIR Teamb61885d2018-07-18 16:29:21 -07001092
MLIR Team4718bc92018-07-17 16:56:54 -07001093void Type::print(raw_ostream &os) const {
Chris Lattner4fd59b02018-07-20 09:35:47 -07001094 ModuleState state(getContext());
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -07001095 ModulePrinter(os, state).printType(this);
MLIR Team4718bc92018-07-17 16:56:54 -07001096}
1097
MLIR Team54b55a22018-07-18 10:16:05 -07001098void Type::dump() const { print(llvm::errs()); }
MLIR Team4718bc92018-07-17 16:56:54 -07001099
MLIR Team718c82f2018-07-16 09:45:22 -07001100void AffineMap::dump() const {
1101 print(llvm::errs());
1102 llvm::errs() << "\n";
1103}
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001104
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001105void AffineExpr::dump() const {
1106 print(llvm::errs());
1107 llvm::errs() << "\n";
1108}
1109
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001110void AffineExpr::print(raw_ostream &os) const {
Chris Lattner4fd59b02018-07-20 09:35:47 -07001111 ModuleState state(/*no context is known*/ nullptr);
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -07001112 ModulePrinter(os, state).printAffineExpr(this);
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001113}
1114
1115void AffineMap::print(raw_ostream &os) const {
Chris Lattner4fd59b02018-07-20 09:35:47 -07001116 ModuleState state(/*no context is known*/ nullptr);
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -07001117 ModulePrinter(os, state).printAffineMap(this);
Chris Lattner4fd59b02018-07-20 09:35:47 -07001118}
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001119
Chris Lattner4fd59b02018-07-20 09:35:47 -07001120void Instruction::print(raw_ostream &os) const {
1121 ModuleState state(getFunction()->getContext());
1122 ModulePrinter modulePrinter(os, state);
1123 CFGFunctionPrinter(getFunction(), modulePrinter).print(this);
1124}
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001125
Chris Lattner4fd59b02018-07-20 09:35:47 -07001126void Instruction::dump() const {
1127 print(llvm::errs());
1128 llvm::errs() << "\n";
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001129}
1130
Chris Lattner4c95a502018-06-23 16:03:42 -07001131void BasicBlock::print(raw_ostream &os) const {
Chris Lattner4fd59b02018-07-20 09:35:47 -07001132 ModuleState state(getFunction()->getContext());
1133 ModulePrinter modulePrinter(os, state);
1134 CFGFunctionPrinter(getFunction(), modulePrinter).print(this);
Chris Lattner4c95a502018-06-23 16:03:42 -07001135}
1136
MLIR Team54b55a22018-07-18 10:16:05 -07001137void BasicBlock::dump() const { print(llvm::errs()); }
Chris Lattner4c95a502018-06-23 16:03:42 -07001138
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001139void Statement::print(raw_ostream &os) const {
Tatiana Shpeismand880b352018-07-31 23:14:16 -07001140 MLFunction *function = findFunction();
1141 ModuleState state(function->getContext());
Chris Lattner4fd59b02018-07-20 09:35:47 -07001142 ModulePrinter modulePrinter(os, state);
Tatiana Shpeismand880b352018-07-31 23:14:16 -07001143 MLFunctionPrinter(function, modulePrinter).print(this);
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07001144}
1145
MLIR Team54b55a22018-07-18 10:16:05 -07001146void Statement::dump() const { print(llvm::errs()); }
Jacques Pienaarb020c542018-07-15 00:06:54 -07001147
Chris Lattner4c95a502018-06-23 16:03:42 -07001148void Function::print(raw_ostream &os) const {
Chris Lattner4fd59b02018-07-20 09:35:47 -07001149 ModuleState state(getContext());
1150 ModulePrinter(os, state).print(this);
Chris Lattner4c95a502018-06-23 16:03:42 -07001151}
1152
MLIR Team54b55a22018-07-18 10:16:05 -07001153void Function::dump() const { print(llvm::errs()); }
1154
Chris Lattner4c95a502018-06-23 16:03:42 -07001155void Module::print(raw_ostream &os) const {
Chris Lattner4fd59b02018-07-20 09:35:47 -07001156 ModuleState state(getContext());
1157 state.initialize(this);
1158 ModulePrinter(os, state).print(this);
Chris Lattner4c95a502018-06-23 16:03:42 -07001159}
1160
MLIR Team54b55a22018-07-18 10:16:05 -07001161void Module::dump() const { print(llvm::errs()); }