ir_printer.cc 6.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <list>
#include <ostream>
#include <string>
#include <unordered_map>

20
#include "paddle/ir/core/block.h"
21 22 23 24 25 26
#include "paddle/ir/core/builtin_attribute.h"
#include "paddle/ir/core/builtin_type.h"
#include "paddle/ir/core/dialect.h"
#include "paddle/ir/core/operation.h"
#include "paddle/ir/core/program.h"
#include "paddle/ir/core/value.h"
27 28 29 30 31

namespace ir {

namespace {
constexpr char newline[] = "\n";
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46

template <typename ForwardIterator, typename UnaryFunctor, typename NullFunctor>
void PrintInterleave(ForwardIterator begin,
                     ForwardIterator end,
                     UnaryFunctor print_func,
                     NullFunctor between_func) {
  if (begin == end) return;
  print_func(*begin);
  begin++;
  for (; begin != end; begin++) {
    between_func();
    print_func(*begin);
  }
}

47 48
}  // namespace

49
class BasicIRPrinter {
50
 public:
51
  explicit BasicIRPrinter(std::ostream& os) : os(os) {}
52 53

  void PrintType(ir::Type type) {
K
kangguangli 已提交
54
    if (!type) {
55
      os << "<<NULL TYPE>>";
K
kangguangli 已提交
56 57 58
      return;
    }

59 60 61 62 63 64 65 66 67 68 69 70
    if (type.isa<ir::Float16Type>()) {
      os << "f16";
    } else if (type.isa<ir::Float32Type>()) {
      os << "f32";
    } else if (type.isa<ir::Float64Type>()) {
      os << "f64";
    } else if (type.isa<ir::Int16Type>()) {
      os << "i16";
    } else if (type.isa<ir::Int32Type>()) {
      os << "i32";
    } else if (type.isa<ir::Int64Type>()) {
      os << "i64";
71 72 73 74 75 76 77
    } else if (type.isa<ir::VectorType>()) {
      os << "vec<";
      auto inner_types = type.dyn_cast<ir::VectorType>().data();
      PrintInterleave(
          inner_types.begin(),
          inner_types.end(),
          [this](ir::Type v) { this->PrintType(v); },
78
          [this]() { this->os << ", "; });
79
      os << ">";
80 81 82 83 84 85
    } else {
      auto& dialect = type.dialect();
      dialect.PrintType(type, os);
    }
  }

86 87 88
  void PrintAttribute(ir::Operation* op) { os << " { ATTRIBUTE }"; }

 protected:
89 90 91
  std::ostream& os;
};

92
class IRPrinter : public BasicIRPrinter {
93
 public:
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
  explicit IRPrinter(std::ostream& os) : BasicIRPrinter(os) {}

  /// @brief print program
  /// @param program
  /// @example
  void PrintProgram(ir::Program* program) {
    PrintOperation(program->module_op());
  }

  /// @brief print operation
  /// @param op
  /// @example
  void PrintOperation(ir::Operation* op) {
    for (size_t i = 0; i < op->num_regions(); ++i) {
      auto& region = op->GetRegion(i);
      for (auto it = region.begin(); it != region.end(); ++it) {
        auto* block = *it;
        os << "{\n";
        for (auto it = block->begin(); it != block->end(); ++it) {
          auto* op = *it;
          // TODO(lyk): add API to get opresults directly
          PrintOpResult(op);
          os << " =";

          os << " \"" << op->name() << "\"";

          // TODO(lyk): add API to get operands directly
          PrintOpOperands(op);

          PrintAttribute(op);
          os << " :";

          // PrintOpSingature
          PrintOperandsType(op);
          os << " -> ";

          // TODO(lyk): add API to get opresults directly
          PrintOpReturnType(op);

          os << newline;
        }
        os << "}\n";
      }
137 138 139
    }
  }

140
 private:
141
  void PrintValue(ir::Value v) {
K
kangguangli 已提交
142 143 144 145
    if (!v) {
      os << "<<NULL VALUE>>";
      return;
    }
146
    const void* key = static_cast<const void*>(v.impl());
147 148
    auto ret = aliases_.find(key);
    if (ret != aliases_.end()) {
149 150 151 152
      os << ret->second;
      return;
    }

153 154 155
    std::string new_name = "%" + std::to_string(cur_var_number_);
    cur_var_number_++;
    aliases_[key] = new_name;
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
    os << new_name;
  }

  void PrintOpResult(ir::Operation* op) {
    os << " (";
    auto num_op_result = op->num_results();
    std::vector<ir::OpResult> op_results;
    op_results.reserve(num_op_result);
    for (size_t idx = 0; idx < num_op_result; idx++) {
      op_results.push_back(op->GetResultByIndex(idx));
    }
    PrintInterleave(
        op_results.begin(),
        op_results.end(),
        [this](ir::Value v) { this->PrintValue(v); },
171 172
        [this]() { this->os << ", "; });
    os << ")";
173 174 175 176 177 178 179 180
  }

  void PrintOpOperands(ir::Operation* op) {
    os << " (";
    auto num_op_operands = op->num_operands();
    std::vector<ir::Value> op_operands;
    op_operands.reserve(num_op_operands);
    for (size_t idx = 0; idx < num_op_operands; idx++) {
181
      op_operands.push_back(op->GetOperandByIndex(idx).source());
182 183 184 185 186
    }
    PrintInterleave(
        op_operands.begin(),
        op_operands.end(),
        [this](ir::Value v) { this->PrintValue(v); },
187 188
        [this]() { this->os << ", "; });
    os << ")";
189 190 191 192 193 194 195
  }

  void PrintOperandsType(ir::Operation* op) {
    auto num_op_operands = op->num_operands();
    std::vector<ir::Type> op_operand_types;
    op_operand_types.reserve(num_op_operands);
    for (size_t idx = 0; idx < num_op_operands; idx++) {
K
kangguangli 已提交
196 197 198 199 200 201
      auto op_operand = op->GetOperandByIndex(idx);
      if (op_operand) {
        op_operand_types.push_back(op->GetOperandByIndex(idx).source().type());
      } else {
        op_operand_types.push_back(ir::Type(nullptr));
      }
202
    }
203
    os << " (";
204 205 206 207
    PrintInterleave(
        op_operand_types.begin(),
        op_operand_types.end(),
        [this](ir::Type t) { this->PrintType(t); },
208 209
        [this]() { this->os << ", "; });
    os << ")";
210 211 212 213 214 215 216
  }

  void PrintOpReturnType(ir::Operation* op) {
    auto num_op_result = op->num_results();
    std::vector<ir::Type> op_result_types;
    op_result_types.reserve(num_op_result);
    for (size_t idx = 0; idx < num_op_result; idx++) {
K
kangguangli 已提交
217 218 219 220 221 222
      auto op_result = op->GetResultByIndex(idx);
      if (op_result) {
        op_result_types.push_back(op_result.type());
      } else {
        op_result_types.push_back(ir::Type(nullptr));
      }
223 224 225 226 227
    }
    PrintInterleave(
        op_result_types.begin(),
        op_result_types.end(),
        [this](ir::Type t) { this->PrintType(t); },
228
        [this]() { this->os << ", "; });
229 230 231
  }

 private:
232 233
  size_t cur_var_number_{0};
  std::unordered_map<const void*, std::string> aliases_;
234 235
};

236 237 238 239 240 241 242 243 244 245 246 247 248
void Program::print(std::ostream& os) {
  IRPrinter printer(os);
  printer.PrintProgram(this);
}

void Operation::Print(std::ostream& os) {
  IRPrinter printer(os);
  printer.PrintOperation(this);
}

void Type::print(std::ostream& os) const {
  BasicIRPrinter printer(os);
  printer.PrintType(*this);
249 250 251
}

}  // namespace ir