#include "ir/IR.h"

#include <iostream>

namespace ir {

static const char* OpcodeToString(Opcode op) {
  switch (op) {
    case Opcode::Add:
      return "add";
    case Opcode::Sub:
      return "sub";
    case Opcode::Mul:
      return "mul";
    case Opcode::Div:
      return "div";
    case Opcode::Ret:
      return "ret";
  }
  return "?";
}

void IRPrinter::Print(const Module& module) {
  for (const auto& func : module.functions()) {
    std::cout << "define i32 @" << func->name() << "() {\n";
    const auto* bb = func->entry();
    if (!bb) {
      std::cout << "}\n";
      continue;
    }
    for (const auto& instPtr : bb->instructions()) {
      const auto* inst = instPtr.get();
      switch (inst->opcode()) {
        case Opcode::Add:
        case Opcode::Sub:
        case Opcode::Mul:
        case Opcode::Div: {
          auto* bin = static_cast<const BinaryInst*>(inst);
          std::cout << "  " << bin->name() << " = " << OpcodeToString(bin->opcode())
                    << " " << bin->lhs()->name() << ", " << bin->rhs()->name()
                    << "\n";
          break;
        }
        case Opcode::Ret: {
          auto* ret = static_cast<const ReturnInst*>(inst);
          std::cout << "  ret " << ret->value()->name() << "\n";
          break;
        }
      }
    }
    std::cout << "}\n";
  }
}

}  // namespace ir
