blob: 9a94d6621c68e8752ee0944386cba3edc7af9d82 [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;
MLIR Team4718bc92018-07-17 16:56:54 -0700306
307 case Type::Kind::Integer: {
308 auto *integer = cast<IntegerType>(type);
309 os << 'i' << integer->getWidth();
310 return;
311 }
312 case Type::Kind::Function: {
313 auto *func = cast<FunctionType>(type);
314 os << '(';
Chris Lattner413db6a2018-07-25 12:55:50 -0700315 interleaveComma(func->getInputs(), [&](Type *type) { printType(type); });
MLIR Team4718bc92018-07-17 16:56:54 -0700316 os << ") -> ";
317 auto results = func->getResults();
318 if (results.size() == 1)
319 os << *results[0];
320 else {
321 os << '(';
Chris Lattner413db6a2018-07-25 12:55:50 -0700322 interleaveComma(results, [&](Type *type) { printType(type); });
MLIR Team4718bc92018-07-17 16:56:54 -0700323 os << ')';
324 }
325 return;
326 }
327 case Type::Kind::Vector: {
328 auto *v = cast<VectorType>(type);
329 os << "vector<";
James Molloy87d81022018-07-23 11:44:40 -0700330 for (auto dim : v->getShape())
331 os << dim << 'x';
MLIR Team4718bc92018-07-17 16:56:54 -0700332 os << *v->getElementType() << '>';
333 return;
334 }
335 case Type::Kind::RankedTensor: {
336 auto *v = cast<RankedTensorType>(type);
337 os << "tensor<";
338 for (auto dim : v->getShape()) {
339 if (dim < 0)
340 os << '?';
341 else
342 os << dim;
343 os << 'x';
344 }
345 os << *v->getElementType() << '>';
346 return;
347 }
348 case Type::Kind::UnrankedTensor: {
349 auto *v = cast<UnrankedTensorType>(type);
Chris Lattner413db6a2018-07-25 12:55:50 -0700350 os << "tensor<??";
351 printType(v->getElementType());
352 os << '>';
MLIR Team4718bc92018-07-17 16:56:54 -0700353 return;
354 }
355 case Type::Kind::MemRef: {
356 auto *v = cast<MemRefType>(type);
357 os << "memref<";
358 for (auto dim : v->getShape()) {
359 if (dim < 0)
360 os << '?';
361 else
362 os << dim;
363 os << 'x';
364 }
Chris Lattner413db6a2018-07-25 12:55:50 -0700365 printType(v->getElementType());
MLIR Team4718bc92018-07-17 16:56:54 -0700366 for (auto map : v->getAffineMaps()) {
367 os << ", ";
MLIR Teamb61885d2018-07-18 16:29:21 -0700368 printAffineMapReference(map);
MLIR Team4718bc92018-07-17 16:56:54 -0700369 }
Chris Lattner413db6a2018-07-25 12:55:50 -0700370 // Only print the memory space if it is the non-default one.
371 if (v->getMemorySpace())
372 os << ", " << v->getMemorySpace();
MLIR Team4718bc92018-07-17 16:56:54 -0700373 os << '>';
374 return;
375 }
376 }
377}
378
379//===----------------------------------------------------------------------===//
Chris Lattner4fd59b02018-07-20 09:35:47 -0700380// Affine expressions and maps
381//===----------------------------------------------------------------------===//
382
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700383void ModulePrinter::printAffineExpr(const AffineExpr *expr) {
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700384 printAffineExprInternal(expr, BindingStrength::Weak);
385}
386
387void ModulePrinter::printAffineExprInternal(
388 const AffineExpr *expr, BindingStrength enclosingTightness) {
389 const char *binopSpelling = nullptr;
Chris Lattner4fd59b02018-07-20 09:35:47 -0700390 switch (expr->getKind()) {
391 case AffineExpr::Kind::SymbolId:
392 os << 's' << cast<AffineSymbolExpr>(expr)->getPosition();
393 return;
394 case AffineExpr::Kind::DimId:
395 os << 'd' << cast<AffineDimExpr>(expr)->getPosition();
396 return;
397 case AffineExpr::Kind::Constant:
398 os << cast<AffineConstantExpr>(expr)->getValue();
399 return;
400 case AffineExpr::Kind::Add:
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700401 binopSpelling = " + ";
402 break;
Chris Lattner4fd59b02018-07-20 09:35:47 -0700403 case AffineExpr::Kind::Mul:
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700404 binopSpelling = " * ";
405 break;
Chris Lattner4fd59b02018-07-20 09:35:47 -0700406 case AffineExpr::Kind::FloorDiv:
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700407 binopSpelling = " floordiv ";
408 break;
Chris Lattner4fd59b02018-07-20 09:35:47 -0700409 case AffineExpr::Kind::CeilDiv:
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700410 binopSpelling = " ceildiv ";
411 break;
Chris Lattner4fd59b02018-07-20 09:35:47 -0700412 case AffineExpr::Kind::Mod:
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700413 binopSpelling = " mod ";
414 break;
Chris Lattner4fd59b02018-07-20 09:35:47 -0700415 }
Chris Lattner4fd59b02018-07-20 09:35:47 -0700416
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700417 auto *binOp = cast<AffineBinaryOpExpr>(expr);
Chris Lattner4fd59b02018-07-20 09:35:47 -0700418
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700419 // Handle tightly binding binary operators.
420 if (binOp->getKind() != AffineExpr::Kind::Add) {
421 if (enclosingTightness == BindingStrength::Strong)
422 os << '(';
423
424 printAffineExprInternal(binOp->getLHS(), BindingStrength::Strong);
425 os << binopSpelling;
426 printAffineExprInternal(binOp->getRHS(), BindingStrength::Strong);
427
428 if (enclosingTightness == BindingStrength::Strong)
429 os << ')';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700430 return;
431 }
432
433 // Print out special "pretty" forms for add.
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700434 if (enclosingTightness == BindingStrength::Strong)
435 os << '(';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700436
437 // Pretty print addition to a product that has a negative operand as a
438 // subtraction.
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700439 if (auto *rhs = dyn_cast<AffineBinaryOpExpr>(binOp->getRHS())) {
Chris Lattner4fd59b02018-07-20 09:35:47 -0700440 if (rhs->getKind() == AffineExpr::Kind::Mul) {
441 if (auto *rrhs = dyn_cast<AffineConstantExpr>(rhs->getRHS())) {
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700442 if (rrhs->getValue() == -1) {
443 printAffineExprInternal(binOp->getLHS(), BindingStrength::Weak);
444 os << " - ";
445 printAffineExprInternal(rhs->getLHS(), BindingStrength::Weak);
446
447 if (enclosingTightness == BindingStrength::Strong)
448 os << ')';
449 return;
450 }
451
452 if (rrhs->getValue() < -1) {
453 printAffineExprInternal(binOp->getLHS(), BindingStrength::Weak);
Chris Lattner4fd59b02018-07-20 09:35:47 -0700454 os << " - (";
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700455 printAffineExprInternal(rhs->getLHS(), BindingStrength::Strong);
456 os << " * " << -rrhs->getValue() << ')';
457 if (enclosingTightness == BindingStrength::Strong)
458 os << ')';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700459 return;
460 }
461 }
462 }
463 }
464
465 // Pretty print addition to a negative number as a subtraction.
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700466 if (auto *rhs = dyn_cast<AffineConstantExpr>(binOp->getRHS())) {
Chris Lattner4fd59b02018-07-20 09:35:47 -0700467 if (rhs->getValue() < 0) {
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700468 printAffineExprInternal(binOp->getLHS(), BindingStrength::Weak);
469 os << " - " << -rhs->getValue() << ')';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700470 return;
471 }
472 }
473
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700474 printAffineExprInternal(binOp->getLHS(), BindingStrength::Weak);
Chris Lattner4fd59b02018-07-20 09:35:47 -0700475 os << " + ";
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700476 printAffineExprInternal(binOp->getRHS(), BindingStrength::Weak);
477
478 if (enclosingTightness == BindingStrength::Strong)
479 os << ')';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700480}
481
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700482void ModulePrinter::printAffineMap(const AffineMap *map) {
Chris Lattner4fd59b02018-07-20 09:35:47 -0700483 // Dimension identifiers.
484 os << '(';
Chris Lattnerdc3ba382018-07-29 14:13:03 -0700485 for (int i = 0; i < (int)map->getNumDims() - 1; ++i)
486 os << 'd' << i << ", ";
Chris Lattner4fd59b02018-07-20 09:35:47 -0700487 if (map->getNumDims() >= 1)
Chris Lattnerdc3ba382018-07-29 14:13:03 -0700488 os << 'd' << map->getNumDims() - 1;
489 os << ')';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700490
491 // Symbolic identifiers.
Chris Lattnerdc3ba382018-07-29 14:13:03 -0700492 if (map->getNumSymbols() != 0) {
493 os << '[';
494 for (unsigned i = 0; i < map->getNumSymbols() - 1; ++i)
495 os << 's' << i << ", ";
Chris Lattner4fd59b02018-07-20 09:35:47 -0700496 if (map->getNumSymbols() >= 1)
Chris Lattnerdc3ba382018-07-29 14:13:03 -0700497 os << 's' << map->getNumSymbols() - 1;
498 os << ']';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700499 }
500
501 // AffineMap should have at least one result.
502 assert(!map->getResults().empty());
503 // Result affine expressions.
504 os << " -> (";
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700505 interleaveComma(map->getResults(),
506 [&](AffineExpr *expr) { printAffineExpr(expr); });
Chris Lattnerdc3ba382018-07-29 14:13:03 -0700507 os << ')';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700508
509 if (!map->isBounded()) {
510 return;
511 }
512
513 // Print range sizes for bounded affine maps.
514 os << " size (";
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700515 interleaveComma(map->getRangeSizes(),
516 [&](AffineExpr *expr) { printAffineExpr(expr); });
Chris Lattnerdc3ba382018-07-29 14:13:03 -0700517 os << ')';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700518}
519
520//===----------------------------------------------------------------------===//
Chris Lattner4c95a502018-06-23 16:03:42 -0700521// Function printing
522//===----------------------------------------------------------------------===//
523
Chris Lattner4fd59b02018-07-20 09:35:47 -0700524void ModulePrinter::printFunctionSignature(const Function *fn) {
Chris Lattner4c95a502018-06-23 16:03:42 -0700525 auto type = fn->getType();
526
527 os << "@" << fn->getName() << '(';
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700528 interleaveComma(type->getInputs(),
529 [&](Type *eltType) { printType(eltType); });
Chris Lattner4c95a502018-06-23 16:03:42 -0700530 os << ')';
531
532 switch (type->getResults().size()) {
MLIR Team54b55a22018-07-18 10:16:05 -0700533 case 0:
534 break;
Chris Lattner4c95a502018-06-23 16:03:42 -0700535 case 1:
MLIR Team4718bc92018-07-17 16:56:54 -0700536 os << " -> ";
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700537 printType(type->getResults()[0]);
Chris Lattner4c95a502018-06-23 16:03:42 -0700538 break;
539 default:
540 os << " -> (";
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700541 interleaveComma(type->getResults(),
542 [&](Type *eltType) { printType(eltType); });
Chris Lattner4c95a502018-06-23 16:03:42 -0700543 os << ')';
544 break;
545 }
546}
547
Chris Lattner4fd59b02018-07-20 09:35:47 -0700548void ModulePrinter::print(const ExtFunction *fn) {
Chris Lattner4c95a502018-06-23 16:03:42 -0700549 os << "extfunc ";
Chris Lattner4fd59b02018-07-20 09:35:47 -0700550 printFunctionSignature(fn);
MLIR Team54b55a22018-07-18 10:16:05 -0700551 os << '\n';
Chris Lattner4c95a502018-06-23 16:03:42 -0700552}
553
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700554namespace {
555
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700556// FunctionPrinter contains common functionality for printing
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700557// CFG and ML functions.
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700558class FunctionPrinter : public ModulePrinter, private OpAsmPrinter {
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700559public:
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700560 FunctionPrinter(const ModulePrinter &other) : ModulePrinter(other) {}
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700561
562 void printOperation(const Operation *op);
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700563 void printDefaultOp(const Operation *op);
564
565 // Implement OpAsmPrinter.
566 raw_ostream &getStream() const { return os; }
567 void printType(const Type *type) { ModulePrinter::printType(type); }
568 void printAttribute(const Attribute *attr) {
569 ModulePrinter::printAttribute(attr);
570 }
571 void printAffineMap(const AffineMap *map) {
Chris Lattner3164ae62018-07-28 09:36:25 -0700572 return ModulePrinter::printAffineMapReference(map);
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700573 }
574 void printAffineExpr(const AffineExpr *expr) {
575 return ModulePrinter::printAffineExpr(expr);
576 }
577
578 void printOperand(const SSAValue *value) { printValueID(value); }
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700579
Chris Lattnerd4964212018-08-01 10:43:18 -0700580 enum { nameSentinel = ~0U };
581
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700582protected:
Chris Lattnerf8cce872018-07-20 09:28:54 -0700583 void numberValueID(const SSAValue *value) {
584 assert(!valueIDs.count(value) && "Value numbered multiple times");
Chris Lattnerd4964212018-08-01 10:43:18 -0700585
586 SmallString<32> specialNameBuffer;
587 llvm::raw_svector_ostream specialName(specialNameBuffer);
588
589 // Give constant integers special names.
590 if (auto *op = value->getDefiningOperation()) {
591 if (auto intOp = op->getAs<ConstantIntOp>()) {
592 specialName << 'c' << intOp->getValue();
593 if (!intOp->getType()->isAffineInt())
594 specialName << '_' << *intOp->getType();
595 }
Tatiana Shpeisman3838db72018-07-30 15:18:10 -0700596 }
Chris Lattnerd4964212018-08-01 10:43:18 -0700597
598 if (specialNameBuffer.empty()) {
599 switch (value->getKind()) {
600 case SSAValueKind::BBArgument:
601 // If this is an argument to the function, give it an 'arg' name.
602 if (auto *bb = cast<BBArgument>(value)->getOwner())
603 if (auto *fn = bb->getFunction())
604 if (&fn->front() == bb) {
605 specialName << "arg" << nextArgumentID++;
606 break;
607 }
608 // Otherwise number it normally.
609 LLVM_FALLTHROUGH;
610 case SSAValueKind::InstResult:
611 case SSAValueKind::StmtResult:
612 // This is an uninteresting result, give it a boring number and be
613 // done with it.
614 valueIDs[value] = nextValueID++;
615 return;
616 case SSAValueKind::FnArgument:
617 specialName << "arg" << nextArgumentID++;
618 break;
619 case SSAValueKind::ForStmt:
620 specialName << 'i' << nextLoopID++;
621 break;
622 }
623 }
624
625 // Ok, this value had an interesting name. Remember it with a sentinel.
626 valueIDs[value] = nameSentinel;
627
628 // Remember that we've used this name, checking to see if we had a conflict.
629 auto insertRes = usedNames.insert(specialName.str());
630 if (insertRes.second) {
631 // If this is the first use of the name, then we're successful!
632 valueNames[value] = insertRes.first->first();
633 return;
634 }
635
636 // Otherwise, we had a conflict - probe until we find a unique name. This
637 // is guaranteed to terminate (and usually in a single iteration) because it
638 // generates new names by incrementing nextConflictID.
639 while (1) {
640 std::string probeName =
641 specialName.str().str() + "_" + llvm::utostr(nextConflictID++);
642 insertRes = usedNames.insert(probeName);
643 if (insertRes.second) {
644 // If this is the first use of the name, then we're successful!
645 valueNames[value] = insertRes.first->first();
646 return;
647 }
648 }
Chris Lattnerf8cce872018-07-20 09:28:54 -0700649 }
650
Tatiana Shpeisman3838db72018-07-30 15:18:10 -0700651 void printValueID(const SSAValue *value, bool printResultNo = true) const {
Chris Lattner6119d382018-07-20 18:41:34 -0700652 int resultNo = -1;
653 auto lookupValue = value;
654
Tatiana Shpeisman3838db72018-07-30 15:18:10 -0700655 // If this is a reference to the result of a multi-result instruction or
656 // statement, print out the # identifier and make sure to map our lookup
657 // to the first result of the instruction.
Chris Lattner6119d382018-07-20 18:41:34 -0700658 if (auto *result = dyn_cast<InstResult>(value)) {
659 if (result->getOwner()->getNumResults() != 1) {
660 resultNo = result->getResultNumber();
661 lookupValue = result->getOwner()->getResult(0);
662 }
Tatiana Shpeisman3838db72018-07-30 15:18:10 -0700663 } else if (auto *result = dyn_cast<StmtResult>(value)) {
664 if (result->getOwner()->getNumResults() != 1) {
665 resultNo = result->getResultNumber();
666 lookupValue = result->getOwner()->getResult(0);
667 }
Chris Lattner6119d382018-07-20 18:41:34 -0700668 }
669
670 auto it = valueIDs.find(lookupValue);
671 if (it == valueIDs.end()) {
Chris Lattnerf8cce872018-07-20 09:28:54 -0700672 os << "<<INVALID SSA VALUE>>";
Chris Lattner6119d382018-07-20 18:41:34 -0700673 return;
674 }
675
Tatiana Shpeisman3838db72018-07-30 15:18:10 -0700676 os << '%';
Chris Lattnerd4964212018-08-01 10:43:18 -0700677 if (it->second != nameSentinel) {
678 os << it->second;
679 } else {
680 auto nameIt = valueNames.find(lookupValue);
681 assert(nameIt != valueNames.end() && "Didn't have a name entry?");
682 os << nameIt->second;
683 }
Tatiana Shpeisman3838db72018-07-30 15:18:10 -0700684
Tatiana Shpeisman3838db72018-07-30 15:18:10 -0700685 if (resultNo != -1 && printResultNo)
Chris Lattner6119d382018-07-20 18:41:34 -0700686 os << '#' << resultNo;
Chris Lattnerf8cce872018-07-20 09:28:54 -0700687 }
688
689private:
Chris Lattnerd4964212018-08-01 10:43:18 -0700690 /// This is the value ID for each SSA value in the current function. If this
691 /// returns ~0, then the valueID has an entry in valueNames.
Chris Lattnerf8cce872018-07-20 09:28:54 -0700692 DenseMap<const SSAValue *, unsigned> valueIDs;
Chris Lattnerd4964212018-08-01 10:43:18 -0700693 DenseMap<const SSAValue *, StringRef> valueNames;
694
695 /// This keeps track of all of the non-numeric names that are in flight,
696 /// allowing us to check for duplicates.
697 llvm::StringSet<> usedNames;
698
699 /// This is the next value ID to assign in numbering.
Chris Lattnerf8cce872018-07-20 09:28:54 -0700700 unsigned nextValueID = 0;
Chris Lattnerd4964212018-08-01 10:43:18 -0700701 /// This is the ID to assign to the next induction variable.
Tatiana Shpeismanc9c4b342018-07-31 07:40:14 -0700702 unsigned nextLoopID = 0;
Chris Lattnerd4964212018-08-01 10:43:18 -0700703 /// This is the next ID to assign to an MLFunction argument.
704 unsigned nextArgumentID = 0;
705
706 /// This is the next ID to assign when a name conflict is detected.
707 unsigned nextConflictID = 0;
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700708};
James Molloy87d81022018-07-23 11:44:40 -0700709} // end anonymous namespace
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700710
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700711void FunctionPrinter::printOperation(const Operation *op) {
Chris Lattnerac591f12018-07-22 21:02:26 -0700712 if (op->getNumResults()) {
Tatiana Shpeisman3838db72018-07-30 15:18:10 -0700713 printValueID(op->getResult(0), /*printResultNo=*/false);
Chris Lattnerac591f12018-07-22 21:02:26 -0700714 os << " = ";
Chris Lattnerf8cce872018-07-20 09:28:54 -0700715 }
716
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700717 // Check to see if this is a known operation. If so, use the registered
718 // custom printer hook.
Chris Lattner4fd59b02018-07-20 09:35:47 -0700719 if (auto opInfo = state.operationSet->lookup(op->getName().str())) {
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700720 opInfo->printAssembly(op, this);
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700721 return;
722 }
723
Chris Lattnerf8cce872018-07-20 09:28:54 -0700724 // Otherwise use the standard verbose printing approach.
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700725 printDefaultOp(op);
726}
Chris Lattnerf8cce872018-07-20 09:28:54 -0700727
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700728void FunctionPrinter::printDefaultOp(const Operation *op) {
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700729 // TODO: escape name if necessary.
Chris Lattnerf8cce872018-07-20 09:28:54 -0700730 os << "\"" << op->getName().str() << "\"(";
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700731
Chris Lattnerac591f12018-07-22 21:02:26 -0700732 interleaveComma(op->getOperands(),
733 [&](const SSAValue *value) { printValueID(value); });
Chris Lattner7f9cc272018-07-19 08:35:28 -0700734
Chris Lattnerf8cce872018-07-20 09:28:54 -0700735 os << ')';
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700736 auto attrs = op->getAttrs();
737 if (!attrs.empty()) {
738 os << '{';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700739 interleaveComma(attrs, [&](NamedAttribute attr) {
Chris Lattnerf8cce872018-07-20 09:28:54 -0700740 os << attr.first << ": ";
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700741 printAttribute(attr.second);
Chris Lattnerf8cce872018-07-20 09:28:54 -0700742 });
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700743 os << '}';
744 }
Chris Lattner3b2ef762018-07-18 15:31:25 -0700745
Chris Lattnerac591f12018-07-22 21:02:26 -0700746 // Print the type signature of the operation.
747 os << " : (";
748 interleaveComma(op->getOperands(),
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700749 [&](const SSAValue *value) { printType(value->getType()); });
Chris Lattnerac591f12018-07-22 21:02:26 -0700750 os << ") -> ";
Chris Lattnerf8cce872018-07-20 09:28:54 -0700751
Chris Lattnerac591f12018-07-22 21:02:26 -0700752 if (op->getNumResults() == 1) {
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700753 printType(op->getResult(0)->getType());
Chris Lattnerac591f12018-07-22 21:02:26 -0700754 } else {
755 os << '(';
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700756 interleaveComma(op->getResults(), [&](const SSAValue *result) {
757 printType(result->getType());
758 });
Chris Lattnerac591f12018-07-22 21:02:26 -0700759 os << ')';
Chris Lattnerf8cce872018-07-20 09:28:54 -0700760 }
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700761}
762
Chris Lattner4c95a502018-06-23 16:03:42 -0700763//===----------------------------------------------------------------------===//
764// CFG Function printing
765//===----------------------------------------------------------------------===//
766
767namespace {
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700768class CFGFunctionPrinter : public FunctionPrinter {
Chris Lattner4c95a502018-06-23 16:03:42 -0700769public:
Chris Lattner4fd59b02018-07-20 09:35:47 -0700770 CFGFunctionPrinter(const CFGFunction *function, const ModulePrinter &other);
Chris Lattner4c95a502018-06-23 16:03:42 -0700771
772 const CFGFunction *getFunction() const { return function; }
773
774 void print();
775 void print(const BasicBlock *block);
Chris Lattnered65a732018-06-28 20:45:33 -0700776
777 void print(const Instruction *inst);
778 void print(const OperationInst *inst);
779 void print(const ReturnInst *inst);
780 void print(const BranchInst *inst);
James Molloy4f788372018-07-24 15:01:27 -0700781 void print(const CondBranchInst *inst);
Chris Lattner4c95a502018-06-23 16:03:42 -0700782
783 unsigned getBBID(const BasicBlock *block) {
784 auto it = basicBlockIDs.find(block);
785 assert(it != basicBlockIDs.end() && "Block not in this function?");
786 return it->second;
787 }
788
789private:
790 const CFGFunction *function;
MLIR Team54b55a22018-07-18 10:16:05 -0700791 DenseMap<const BasicBlock *, unsigned> basicBlockIDs;
Chris Lattnerf8cce872018-07-20 09:28:54 -0700792
Chris Lattner4fd59b02018-07-20 09:35:47 -0700793 void numberValuesInBlock(const BasicBlock *block);
Chris Lattner4c95a502018-06-23 16:03:42 -0700794};
James Molloy87d81022018-07-23 11:44:40 -0700795} // end anonymous namespace
Chris Lattner4c95a502018-06-23 16:03:42 -0700796
Chris Lattner4fd59b02018-07-20 09:35:47 -0700797CFGFunctionPrinter::CFGFunctionPrinter(const CFGFunction *function,
798 const ModulePrinter &other)
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700799 : FunctionPrinter(other), function(function) {
Chris Lattner4c95a502018-06-23 16:03:42 -0700800 // Each basic block gets a unique ID per function.
801 unsigned blockID = 0;
Chris Lattnerf8cce872018-07-20 09:28:54 -0700802 for (auto &block : *function) {
803 basicBlockIDs[&block] = blockID++;
Chris Lattner4fd59b02018-07-20 09:35:47 -0700804 numberValuesInBlock(&block);
Chris Lattnerf8cce872018-07-20 09:28:54 -0700805 }
806}
807
808/// Number all of the SSA values in the specified basic block.
Chris Lattner4fd59b02018-07-20 09:35:47 -0700809void CFGFunctionPrinter::numberValuesInBlock(const BasicBlock *block) {
James Molloy61a656c2018-07-22 15:45:24 -0700810 for (auto *arg : block->getArguments()) {
811 numberValueID(arg);
812 }
Chris Lattnerf8cce872018-07-20 09:28:54 -0700813 for (auto &op : *block) {
814 // We number instruction that have results, and we only number the first
815 // result.
816 if (op.getNumResults() != 0)
817 numberValueID(op.getResult(0));
818 }
819
820 // Terminators do not define values.
Chris Lattner4c95a502018-06-23 16:03:42 -0700821}
822
Chris Lattner4fd59b02018-07-20 09:35:47 -0700823void CFGFunctionPrinter::print() {
Chris Lattner4c95a502018-06-23 16:03:42 -0700824 os << "cfgfunc ";
Chris Lattner4fd59b02018-07-20 09:35:47 -0700825 printFunctionSignature(getFunction());
Chris Lattner4c95a502018-06-23 16:03:42 -0700826 os << " {\n";
827
James Molloy87d81022018-07-23 11:44:40 -0700828 for (auto &block : *function)
829 print(&block);
Chris Lattner4c95a502018-06-23 16:03:42 -0700830 os << "}\n\n";
831}
832
Chris Lattner4fd59b02018-07-20 09:35:47 -0700833void CFGFunctionPrinter::print(const BasicBlock *block) {
James Molloy61a656c2018-07-22 15:45:24 -0700834 os << "bb" << getBBID(block);
Chris Lattner4c95a502018-06-23 16:03:42 -0700835
James Molloy61a656c2018-07-22 15:45:24 -0700836 if (!block->args_empty()) {
837 os << '(';
838 interleaveComma(block->getArguments(), [&](const BBArgument *arg) {
839 printValueID(arg);
840 os << ": ";
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700841 printType(arg->getType());
James Molloy61a656c2018-07-22 15:45:24 -0700842 });
843 os << ')';
844 }
Chris Lattner25ce3062018-07-27 11:10:12 -0700845 os << ':';
846
847 // Print out some context information about the predecessors of this block.
848 if (!block->getFunction()) {
849 os << "\t// block is not in a function!";
850 } else if (block->hasNoPredecessors()) {
851 // Don't print "no predecessors" for the entry block.
852 if (block != &block->getFunction()->front())
853 os << "\t// no predecessors";
854 } else if (auto *pred = block->getSinglePredecessor()) {
855 os << "\t// pred: bb" << getBBID(pred);
856 } else {
857 // We want to print the predecessors in increasing numeric order, not in
858 // whatever order the use-list is in, so gather and sort them.
859 SmallVector<unsigned, 4> predIDs;
860 for (auto *pred : block->getPredecessors())
861 predIDs.push_back(getBBID(pred));
862 llvm::array_pod_sort(predIDs.begin(), predIDs.end());
863
864 os << "\t// " << predIDs.size() << " preds: ";
865
866 interleaveComma(predIDs, [&](unsigned predID) { os << "bb" << predID; });
867 }
868 os << '\n';
James Molloy61a656c2018-07-22 15:45:24 -0700869
Jacques Pienaarb020c542018-07-15 00:06:54 -0700870 for (auto &inst : block->getOperations()) {
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -0700871 os << " ";
Chris Lattner3a467cc2018-07-01 20:28:00 -0700872 print(&inst);
James Molloy61a656c2018-07-22 15:45:24 -0700873 os << '\n';
Jacques Pienaarb020c542018-07-15 00:06:54 -0700874 }
Chris Lattner4c95a502018-06-23 16:03:42 -0700875
876 print(block->getTerminator());
James Molloy61a656c2018-07-22 15:45:24 -0700877 os << '\n';
Chris Lattner4c95a502018-06-23 16:03:42 -0700878}
879
Chris Lattner4fd59b02018-07-20 09:35:47 -0700880void CFGFunctionPrinter::print(const Instruction *inst) {
Chris Lattner4c95a502018-06-23 16:03:42 -0700881 switch (inst->getKind()) {
Chris Lattnered65a732018-06-28 20:45:33 -0700882 case Instruction::Kind::Operation:
883 return print(cast<OperationInst>(inst));
Chris Lattnerf6d80a02018-06-24 11:18:29 -0700884 case TerminatorInst::Kind::Branch:
Chris Lattnered65a732018-06-28 20:45:33 -0700885 return print(cast<BranchInst>(inst));
James Molloy4f788372018-07-24 15:01:27 -0700886 case TerminatorInst::Kind::CondBranch:
887 return print(cast<CondBranchInst>(inst));
Chris Lattner4c95a502018-06-23 16:03:42 -0700888 case TerminatorInst::Kind::Return:
Chris Lattnered65a732018-06-28 20:45:33 -0700889 return print(cast<ReturnInst>(inst));
Chris Lattner4c95a502018-06-23 16:03:42 -0700890 }
891}
892
Chris Lattner4fd59b02018-07-20 09:35:47 -0700893void CFGFunctionPrinter::print(const OperationInst *inst) {
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700894 printOperation(inst);
Chris Lattner3b2ef762018-07-18 15:31:25 -0700895}
Chris Lattner1604e472018-07-23 08:42:19 -0700896
Chris Lattner4fd59b02018-07-20 09:35:47 -0700897void CFGFunctionPrinter::print(const BranchInst *inst) {
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -0700898 os << "br bb" << getBBID(inst->getDest());
Chris Lattner1604e472018-07-23 08:42:19 -0700899
900 if (inst->getNumOperands() != 0) {
901 os << '(';
902 // TODO: Use getOperands() when we have it.
903 interleaveComma(inst->getInstOperands(), [&](const InstOperand &operand) {
904 printValueID(operand.get());
905 });
906 os << ") : ";
907 interleaveComma(inst->getInstOperands(), [&](const InstOperand &operand) {
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700908 printType(operand.get()->getType());
Chris Lattner1604e472018-07-23 08:42:19 -0700909 });
910 }
Chris Lattnered65a732018-06-28 20:45:33 -0700911}
Chris Lattner1604e472018-07-23 08:42:19 -0700912
James Molloy4f788372018-07-24 15:01:27 -0700913void CFGFunctionPrinter::print(const CondBranchInst *inst) {
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -0700914 os << "cond_br ";
James Molloy4f788372018-07-24 15:01:27 -0700915 printValueID(inst->getCondition());
916
917 os << ", bb" << getBBID(inst->getTrueDest());
918 if (inst->getNumTrueOperands() != 0) {
919 os << '(';
920 interleaveComma(inst->getTrueOperands(),
921 [&](const CFGValue *operand) { printValueID(operand); });
922 os << " : ";
923 interleaveComma(inst->getTrueOperands(), [&](const CFGValue *operand) {
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700924 printType(operand->getType());
James Molloy4f788372018-07-24 15:01:27 -0700925 });
926 os << ")";
927 }
928
929 os << ", bb" << getBBID(inst->getFalseDest());
930 if (inst->getNumFalseOperands() != 0) {
931 os << '(';
932 interleaveComma(inst->getFalseOperands(),
933 [&](const CFGValue *operand) { printValueID(operand); });
934 os << " : ";
935 interleaveComma(inst->getFalseOperands(), [&](const CFGValue *operand) {
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700936 printType(operand->getType());
James Molloy4f788372018-07-24 15:01:27 -0700937 });
938 os << ")";
939 }
940}
941
Chris Lattner40746442018-07-21 14:32:09 -0700942void CFGFunctionPrinter::print(const ReturnInst *inst) {
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -0700943 os << "return";
Chris Lattner40746442018-07-21 14:32:09 -0700944
945 if (inst->getNumOperands() != 0)
946 os << ' ';
947
James Molloy4f788372018-07-24 15:01:27 -0700948 interleaveComma(inst->getOperands(),
949 [&](const CFGValue *operand) { printValueID(operand); });
950 os << " : ";
Chris Lattnerac591f12018-07-22 21:02:26 -0700951 interleaveComma(inst->getOperands(), [&](const CFGValue *operand) {
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700952 printType(operand->getType());
Chris Lattner40746442018-07-21 14:32:09 -0700953 });
954}
MLIR Team54b55a22018-07-18 10:16:05 -0700955
Chris Lattner4fd59b02018-07-20 09:35:47 -0700956void ModulePrinter::print(const CFGFunction *fn) {
957 CFGFunctionPrinter(fn, *this).print();
Chris Lattnered65a732018-06-28 20:45:33 -0700958}
959
Chris Lattner4c95a502018-06-23 16:03:42 -0700960//===----------------------------------------------------------------------===//
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -0700961// ML Function printing
Chris Lattner4c95a502018-06-23 16:03:42 -0700962//===----------------------------------------------------------------------===//
963
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -0700964namespace {
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700965class MLFunctionPrinter : public FunctionPrinter {
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -0700966public:
Chris Lattner4fd59b02018-07-20 09:35:47 -0700967 MLFunctionPrinter(const MLFunction *function, const ModulePrinter &other);
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -0700968
969 const MLFunction *getFunction() const { return function; }
970
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -0700971 // Prints ML function
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -0700972 void print();
973
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -0700974 // Methods to print ML function statements
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -0700975 void print(const Statement *stmt);
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700976 void print(const OperationStmt *stmt);
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -0700977 void print(const ForStmt *stmt);
978 void print(const IfStmt *stmt);
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -0700979 void print(const StmtBlock *block);
980
981 // Number of spaces used for indenting nested statements
982 const static unsigned indentWidth = 2;
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -0700983
984private:
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -0700985 void numberValues();
986
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -0700987 const MLFunction *function;
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -0700988 int numSpaces;
989};
James Molloy87d81022018-07-23 11:44:40 -0700990} // end anonymous namespace
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -0700991
Chris Lattner4fd59b02018-07-20 09:35:47 -0700992MLFunctionPrinter::MLFunctionPrinter(const MLFunction *function,
993 const ModulePrinter &other)
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -0700994 : FunctionPrinter(other), function(function), numSpaces(0) {
995 numberValues();
996}
997
998/// Number all of the SSA values in this ML function.
999void MLFunctionPrinter::numberValues() {
1000 // Visits all operation statements and numbers the first result.
Uday Bondhugula081d9e72018-07-27 10:58:14 -07001001 struct NumberValuesPass : public StmtWalker<NumberValuesPass> {
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -07001002 NumberValuesPass(MLFunctionPrinter *printer) : printer(printer) {}
1003 void visitOperationStmt(OperationStmt *stmt) {
1004 if (stmt->getNumResults() != 0)
1005 printer->numberValueID(stmt->getResult(0));
1006 }
Tatiana Shpeismanc9c4b342018-07-31 07:40:14 -07001007 void visitForStmt(ForStmt *stmt) { printer->numberValueID(stmt); }
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -07001008 MLFunctionPrinter *printer;
1009 };
1010
1011 NumberValuesPass pass(this);
1012 // TODO: it'd be cleaner to have constant visitor istead of using const_cast.
Uday Bondhugula081d9e72018-07-27 10:58:14 -07001013 pass.walk(const_cast<MLFunction *>(function));
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -07001014}
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001015
Chris Lattner4fd59b02018-07-20 09:35:47 -07001016void MLFunctionPrinter::print() {
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001017 os << "mlfunc ";
1018 // FIXME: should print argument names rather than just signature
Chris Lattner4fd59b02018-07-20 09:35:47 -07001019 printFunctionSignature(function);
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001020 os << " {\n";
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001021 print(function);
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001022 os << " return\n";
1023 os << "}\n\n";
1024}
1025
Chris Lattner4fd59b02018-07-20 09:35:47 -07001026void MLFunctionPrinter::print(const StmtBlock *block) {
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001027 numSpaces += indentWidth;
Jacques Pienaarb020c542018-07-15 00:06:54 -07001028 for (auto &stmt : block->getStatements()) {
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001029 print(&stmt);
Jacques Pienaarb020c542018-07-15 00:06:54 -07001030 os << "\n";
1031 }
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001032 numSpaces -= indentWidth;
1033}
1034
Chris Lattner4fd59b02018-07-20 09:35:47 -07001035void MLFunctionPrinter::print(const Statement *stmt) {
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001036 switch (stmt->getKind()) {
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001037 case Statement::Kind::Operation:
1038 return print(cast<OperationStmt>(stmt));
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001039 case Statement::Kind::For:
1040 return print(cast<ForStmt>(stmt));
1041 case Statement::Kind::If:
1042 return print(cast<IfStmt>(stmt));
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001043 }
1044}
1045
Chris Lattner4fd59b02018-07-20 09:35:47 -07001046void MLFunctionPrinter::print(const OperationStmt *stmt) {
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -07001047 os.indent(numSpaces);
Chris Lattner4fd59b02018-07-20 09:35:47 -07001048 printOperation(stmt);
1049}
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001050
Chris Lattner4fd59b02018-07-20 09:35:47 -07001051void MLFunctionPrinter::print(const ForStmt *stmt) {
Tatiana Shpeisman3838db72018-07-30 15:18:10 -07001052 os.indent(numSpaces) << "for ";
Tatiana Shpeismanc9c4b342018-07-31 07:40:14 -07001053 printOperand(stmt);
Tatiana Shpeisman3838db72018-07-30 15:18:10 -07001054 os << " = " << *stmt->getLowerBound();
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07001055 os << " to " << *stmt->getUpperBound();
1056 if (stmt->getStep()->getValue() != 1)
1057 os << " step " << *stmt->getStep();
1058
1059 os << " {\n";
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001060 print(static_cast<const StmtBlock *>(stmt));
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001061 os.indent(numSpaces) << "}";
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001062}
1063
Chris Lattner4fd59b02018-07-20 09:35:47 -07001064void MLFunctionPrinter::print(const IfStmt *stmt) {
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001065 os.indent(numSpaces) << "if () {\n";
1066 print(stmt->getThenClause());
1067 os.indent(numSpaces) << "}";
1068 if (stmt->hasElseClause()) {
1069 os << " else {\n";
1070 print(stmt->getElseClause());
1071 os.indent(numSpaces) << "}";
1072 }
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001073}
1074
Chris Lattner4fd59b02018-07-20 09:35:47 -07001075void ModulePrinter::print(const MLFunction *fn) {
1076 MLFunctionPrinter(fn, *this).print();
MLIR Team4718bc92018-07-17 16:56:54 -07001077}
1078
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001079//===----------------------------------------------------------------------===//
1080// print and dump methods
1081//===----------------------------------------------------------------------===//
Chris Lattnered65a732018-06-28 20:45:33 -07001082
MLIR Teamb61885d2018-07-18 16:29:21 -07001083void Attribute::print(raw_ostream &os) const {
Chris Lattner4fd59b02018-07-20 09:35:47 -07001084 ModuleState state(/*no context is known*/ nullptr);
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -07001085 ModulePrinter(os, state).printAttribute(this);
MLIR Teamb61885d2018-07-18 16:29:21 -07001086}
1087
James Molloy87d81022018-07-23 11:44:40 -07001088void Attribute::dump() const { print(llvm::errs()); }
MLIR Teamb61885d2018-07-18 16:29:21 -07001089
MLIR Team4718bc92018-07-17 16:56:54 -07001090void Type::print(raw_ostream &os) const {
Chris Lattner4fd59b02018-07-20 09:35:47 -07001091 ModuleState state(getContext());
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -07001092 ModulePrinter(os, state).printType(this);
MLIR Team4718bc92018-07-17 16:56:54 -07001093}
1094
MLIR Team54b55a22018-07-18 10:16:05 -07001095void Type::dump() const { print(llvm::errs()); }
MLIR Team4718bc92018-07-17 16:56:54 -07001096
MLIR Team718c82f2018-07-16 09:45:22 -07001097void AffineMap::dump() const {
1098 print(llvm::errs());
1099 llvm::errs() << "\n";
1100}
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001101
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001102void AffineExpr::dump() const {
1103 print(llvm::errs());
1104 llvm::errs() << "\n";
1105}
1106
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001107void AffineExpr::print(raw_ostream &os) const {
Chris Lattner4fd59b02018-07-20 09:35:47 -07001108 ModuleState state(/*no context is known*/ nullptr);
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -07001109 ModulePrinter(os, state).printAffineExpr(this);
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001110}
1111
1112void AffineMap::print(raw_ostream &os) const {
Chris Lattner4fd59b02018-07-20 09:35:47 -07001113 ModuleState state(/*no context is known*/ nullptr);
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -07001114 ModulePrinter(os, state).printAffineMap(this);
Chris Lattner4fd59b02018-07-20 09:35:47 -07001115}
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001116
Chris Lattner4fd59b02018-07-20 09:35:47 -07001117void Instruction::print(raw_ostream &os) const {
1118 ModuleState state(getFunction()->getContext());
1119 ModulePrinter modulePrinter(os, state);
1120 CFGFunctionPrinter(getFunction(), modulePrinter).print(this);
1121}
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001122
Chris Lattner4fd59b02018-07-20 09:35:47 -07001123void Instruction::dump() const {
1124 print(llvm::errs());
1125 llvm::errs() << "\n";
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001126}
1127
Chris Lattner4c95a502018-06-23 16:03:42 -07001128void BasicBlock::print(raw_ostream &os) const {
Chris Lattner4fd59b02018-07-20 09:35:47 -07001129 ModuleState state(getFunction()->getContext());
1130 ModulePrinter modulePrinter(os, state);
1131 CFGFunctionPrinter(getFunction(), modulePrinter).print(this);
Chris Lattner4c95a502018-06-23 16:03:42 -07001132}
1133
MLIR Team54b55a22018-07-18 10:16:05 -07001134void BasicBlock::dump() const { print(llvm::errs()); }
Chris Lattner4c95a502018-06-23 16:03:42 -07001135
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001136void Statement::print(raw_ostream &os) const {
Tatiana Shpeismand880b352018-07-31 23:14:16 -07001137 MLFunction *function = findFunction();
1138 ModuleState state(function->getContext());
Chris Lattner4fd59b02018-07-20 09:35:47 -07001139 ModulePrinter modulePrinter(os, state);
Tatiana Shpeismand880b352018-07-31 23:14:16 -07001140 MLFunctionPrinter(function, modulePrinter).print(this);
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07001141}
1142
MLIR Team54b55a22018-07-18 10:16:05 -07001143void Statement::dump() const { print(llvm::errs()); }
Jacques Pienaarb020c542018-07-15 00:06:54 -07001144
Chris Lattner4c95a502018-06-23 16:03:42 -07001145void Function::print(raw_ostream &os) const {
Chris Lattner4fd59b02018-07-20 09:35:47 -07001146 ModuleState state(getContext());
1147 ModulePrinter(os, state).print(this);
Chris Lattner4c95a502018-06-23 16:03:42 -07001148}
1149
MLIR Team54b55a22018-07-18 10:16:05 -07001150void Function::dump() const { print(llvm::errs()); }
1151
Chris Lattner4c95a502018-06-23 16:03:42 -07001152void Module::print(raw_ostream &os) const {
Chris Lattner4fd59b02018-07-20 09:35:47 -07001153 ModuleState state(getContext());
1154 state.initialize(this);
1155 ModulePrinter(os, state).print(this);
Chris Lattner4c95a502018-06-23 16:03:42 -07001156}
1157
MLIR Team54b55a22018-07-18 10:16:05 -07001158void Module::dump() const { print(llvm::errs()); }