1//===- Unit.cpp - Support for manipulating IR Unit ------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "mlir/IR/Unit.h"
10#include "mlir/IR/Operation.h"
11#include "mlir/IR/OperationSupport.h"
12#include "mlir/IR/Region.h"
13#include "llvm/Support/raw_ostream.h"
14#include <iterator>
15
16using namespace mlir;
17
18static void printOp(llvm::raw_ostream &os, Operation *op,
19 OpPrintingFlags &flags) {
20 if (!op) {
21 os << "<Operation:nullptr>";
22 return;
23 }
24 op->print(os, flags);
25}
26
27static void printRegion(llvm::raw_ostream &os, Region *region,
28 OpPrintingFlags &flags) {
29 if (!region) {
30 os << "<Region:nullptr>";
31 return;
32 }
33 os << "Region #" << region->getRegionNumber() << " for op ";
34 printOp(os, op: region->getParentOp(), flags);
35}
36
37static void printBlock(llvm::raw_ostream &os, Block *block,
38 OpPrintingFlags &flags) {
39 Region *region = block->getParent();
40 os << "Block #" << block->computeBlockNumber() << " for ";
41 bool shouldSkipRegions = flags.shouldSkipRegions();
42 printRegion(os, region, flags&: flags.skipRegions());
43 if (!shouldSkipRegions)
44 block->print(os);
45}
46
47void mlir::IRUnit::print(llvm::raw_ostream &os, OpPrintingFlags flags) const {
48 if (auto *op = llvm::dyn_cast_if_present<Operation *>(Val: *this))
49 return printOp(os, op, flags);
50 if (auto *region = llvm::dyn_cast_if_present<Region *>(Val: *this))
51 return printRegion(os, region, flags);
52 if (auto *block = llvm::dyn_cast_if_present<Block *>(Val: *this))
53 return printBlock(os, block, flags);
54 llvm_unreachable("unknown IRUnit");
55}
56
57llvm::raw_ostream &mlir::operator<<(llvm::raw_ostream &os, const IRUnit &unit) {
58 unit.print(os);
59 return os;
60}
61