ir_printing.cc 2.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// 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 <ostream>
16
#include <string>
17 18 19 20 21 22
#include <unordered_map>

#include "paddle/ir/core/operation.h"
#include "paddle/ir/pass/pass.h"
#include "paddle/ir/pass/pass_instrumentation.h"
#include "paddle/ir/pass/pass_manager.h"
23
#include "paddle/ir/pass/utils.h"
24 25 26 27 28

namespace ir {

namespace {
void PrintIR(Operation *op, bool print_module, std::ostream &os) {
29
  if (!print_module) {
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
    op->Print(os << "\n");
    return;
  }

  // Find the top-level operation.
  auto *top_op = op;
  while (auto *parent_op = top_op->GetParentOp()) {
    top_op = parent_op;
  }
  top_op->Print(os);
}
}  // namespace

class IRPrinting : public PassInstrumentation {
 public:
  explicit IRPrinting(std::unique_ptr<PassManager::IRPrinterOption> option)
      : option_(std::move(option)) {}

48
  ~IRPrinting() override = default;
49 50

  void RunBeforePass(Pass *pass, Operation *op) override {
51
    if (option_->print_on_change()) {
52 53 54 55
      // TODO(liuyuanle): support print on change
    }

    option_->PrintBeforeIfEnabled(pass, op, [&](std::ostream &os) {
56 57 58
      std::string header =
          "IRPrinting on " + op->name() + " before " + pass->name() + " pass";
      detail::PrintHeader(header, os);
59
      PrintIR(op, option_->print_module(), os);
60 61 62 63 64
      os << "\n\n";
    });
  }

  void RunAfterPass(Pass *pass, Operation *op) override {
65
    if (option_->print_on_change()) {
66 67 68
      // TODO(liuyuanle): support print on change
    }

69 70 71 72
    option_->PrintAfterIfEnabled(pass, op, [&](std::ostream &os) {
      std::string header =
          "IRPrinting on " + op->name() + " after " + pass->name() + " pass";
      detail::PrintHeader(header, os);
73
      PrintIR(op, option_->print_module(), os);
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
      os << "\n\n";
    });
  }

 private:
  std::unique_ptr<PassManager::IRPrinterOption> option_;

  // TODO(liuyuanle): Add IRFingerPrint to support print on change.
};

void PassManager::EnableIRPrinting(std::unique_ptr<IRPrinterOption> option) {
  AddInstrumentation(std::make_unique<IRPrinting>(std::move(option)));
}

}  // namespace ir