// IR 指令体系：
// - 二元运算/比较、load/store、call、br/condbr、ret、phi、alloca 等
// - 指令操作数与结果类型管理，支持打印与优化
#include "ir/IR.h"

#include <algorithm>
#include <stdexcept>
#include <utility>

#include "utils/Log.h"

namespace ir {

namespace {

const char* TypeKindToString(Type::Kind k) {
  switch (k) {
    case Type::Kind::Void:
      return "void";
    case Type::Kind::Int32:
      return "i32";
    case Type::Kind::PtrInt32:
      return "i32*";
  }
  return "?";
}

}  // namespace

User::User(std::shared_ptr<Type> ty, std::string name)
    : Value(std::move(ty), std::move(name)) {}

size_t User::GetNumOperands() const { return operands_.size(); }

Value* User::GetOperand(size_t index) const {
  if (index >= operands_.size()) {
    throw std::out_of_range("User operand index out of range");
  }
  return operands_[index];
}

void User::SetOperand(size_t index, Value* value) {
  if (index >= operands_.size()) {
    throw std::out_of_range("User operand index out of range");
  }
  if (!value) {
    throw std::runtime_error(FormatError("ir", "User operand 不能为空"));
  }
  auto* old = operands_[index];
  if (old == value) {
    return;
  }
  if (old) {
    old->RemoveUse(this, index);
  }
  operands_[index] = value;
  value->AddUse(this, index);
}

void User::AddOperand(Value* value) {
  if (!value) {
    throw std::runtime_error(FormatError("ir", "User operand 不能为空"));
  }
  size_t operand_index = operands_.size();
  operands_.push_back(value);
  value->AddUse(this, operand_index);
}

Instruction::Instruction(Opcode op, std::shared_ptr<Type> ty, std::string name)
    : User(std::move(ty), std::move(name)), opcode_(op) {}

Opcode Instruction::GetOpcode() const { return opcode_; }

bool Instruction::IsTerminator() const {
  return opcode_ == Opcode::Ret || opcode_ == Opcode::Br ||
         opcode_ == Opcode::CondBr;
}

BasicBlock* Instruction::GetParent() const { return parent_; }

void Instruction::SetParent(BasicBlock* parent) {
  parent_ = parent;
  if (!parent_) {
    return;
  }
  if (auto* br = dynamic_cast<BranchInst*>(this)) {
    auto* target = br->GetTarget();
    parent_->AddSuccessor(target);
    target->AddPredecessor(parent_);
    return;
  }
  if (auto* cbr = dynamic_cast<CondBranchInst*>(this)) {
    auto* true_bb = cbr->GetTrueBlock();
    auto* false_bb = cbr->GetFalseBlock();
    parent_->AddSuccessor(true_bb);
    true_bb->AddPredecessor(parent_);
    parent_->AddSuccessor(false_bb);
    false_bb->AddPredecessor(parent_);
  }
}

static bool IsBinaryOpcode(Opcode op) {
  return op == Opcode::Add || op == Opcode::Sub || op == Opcode::Mul ||
         op == Opcode::Div || op == Opcode::Mod;
}

BinaryInst::BinaryInst(Opcode op, std::shared_ptr<Type> ty, Value* lhs,
                       Value* rhs, std::string name)
    : Instruction(op, std::move(ty), std::move(name)) {
  if (!IsBinaryOpcode(op)) {
    throw std::runtime_error(FormatError("ir", "BinaryInst 非法二元操作码"));
  }
  if (!lhs || !rhs) {
    throw std::runtime_error(FormatError("ir", "BinaryInst 缺少操作数"));
  }
  if (!type_ || !lhs->GetType() || !rhs->GetType()) {
    throw std::runtime_error(FormatError("ir", "BinaryInst 缺少类型信息"));
  }
  if (lhs->GetType()->GetKind() != rhs->GetType()->GetKind() ||
      type_->GetKind() != lhs->GetType()->GetKind()) {
    throw std::runtime_error(FormatError("ir", "BinaryInst 类型不匹配"));
  }
  if (!type_->IsInt32()) {
    throw std::runtime_error(FormatError("ir", "BinaryInst 当前只支持 i32"));
  }
  AddOperand(lhs);
  AddOperand(rhs);
}

Value* BinaryInst::GetLhs() const { return GetOperand(0); }

Value* BinaryInst::GetRhs() const { return GetOperand(1); }

CmpInst::CmpInst(CmpOp op, std::shared_ptr<Type> ty, Value* lhs, Value* rhs,
                 std::string name)
    : Instruction(Opcode::Cmp, std::move(ty), std::move(name)), cmp_op_(op) {
  if (!lhs || !rhs) {
    throw std::runtime_error(FormatError("ir", "CmpInst 缺少操作数"));
  }
  if (!type_ || !lhs->GetType() || !rhs->GetType()) {
    throw std::runtime_error(FormatError("ir", "CmpInst 缺少类型信息"));
  }
  if (!type_->IsInt32()) {
    throw std::runtime_error(FormatError("ir", "CmpInst 结果类型必须为 i32"));
  }
  if (!lhs->GetType()->IsInt32() || !rhs->GetType()->IsInt32()) {
    throw std::runtime_error(FormatError(
        "ir", "CmpInst 当前只支持 i32 比较，实际为 " +
                   std::string(TypeKindToString(lhs->GetType()->GetKind())) +
                   " 与 " +
                   std::string(TypeKindToString(rhs->GetType()->GetKind()))));
  }
  AddOperand(lhs);
  AddOperand(rhs);
}

CmpOp CmpInst::GetCmpOp() const { return cmp_op_; }

Value* CmpInst::GetLhs() const { return GetOperand(0); }

Value* CmpInst::GetRhs() const { return GetOperand(1); }

ReturnInst::ReturnInst(std::shared_ptr<Type> void_ty, Value* val)
    : Instruction(Opcode::Ret, std::move(void_ty), "") {
  if (!type_ || !type_->IsVoid()) {
    throw std::runtime_error(FormatError("ir", "ReturnInst 返回类型必须为 void"));
  }
  if (val) {
    AddOperand(val);
  }
}

Value* ReturnInst::GetValue() const {
  return GetNumOperands() > 0 ? GetOperand(0) : nullptr;
}

AllocaInst::AllocaInst(std::shared_ptr<Type> ptr_ty, std::string name)
    : Instruction(Opcode::Alloca, std::move(ptr_ty), std::move(name)), count_(1) {
  if (!type_ || !type_->IsPtrInt32()) {
    throw std::runtime_error(FormatError("ir", "AllocaInst 当前只支持 i32*"));
  }
}

AllocaInst::AllocaInst(std::shared_ptr<Type> ptr_ty, std::string name, int count)
    : Instruction(Opcode::Alloca, std::move(ptr_ty), std::move(name)), count_(count) {
  if (!type_ || !type_->IsPtrInt32()) {
    throw std::runtime_error(FormatError("ir", "AllocaInst 当前只支持 i32*"));
  }
  if (count_ <= 0) {
    throw std::runtime_error(FormatError("ir", "AllocaInst 数组大小必须为正数"));
  }
}

LoadInst::LoadInst(std::shared_ptr<Type> val_ty, Value* ptr, std::string name)
    : Instruction(Opcode::Load, std::move(val_ty), std::move(name)) {
  if (!ptr) {
    throw std::runtime_error(FormatError("ir", "LoadInst 缺少 ptr"));
  }
  if (!type_ || !type_->IsInt32()) {
    throw std::runtime_error(FormatError("ir", "LoadInst 当前只支持加载 i32"));
  }
  if (!ptr->GetType() || !ptr->GetType()->IsPtrInt32()) {
    throw std::runtime_error(
        FormatError("ir", "LoadInst 当前只支持从 i32* 加载"));
  }
  AddOperand(ptr);
}

Value* LoadInst::GetPtr() const { return GetOperand(0); }

StoreInst::StoreInst(std::shared_ptr<Type> void_ty, Value* val, Value* ptr)
    : Instruction(Opcode::Store, std::move(void_ty), "") {
  if (!val) {
    throw std::runtime_error(FormatError("ir", "StoreInst 缺少 value"));
  }
  if (!ptr) {
    throw std::runtime_error(FormatError("ir", "StoreInst 缺少 ptr"));
  }
  if (!type_ || !type_->IsVoid()) {
    throw std::runtime_error(FormatError("ir", "StoreInst 返回类型必须为 void"));
  }
  if (!val->GetType() || !val->GetType()->IsInt32()) {
    throw std::runtime_error(FormatError("ir", "StoreInst 当前只支持存储 i32"));
  }
  if (!ptr->GetType() || !ptr->GetType()->IsPtrInt32()) {
    throw std::runtime_error(
        FormatError("ir", "StoreInst 当前只支持写入 i32*"));
  }
  AddOperand(val);
  AddOperand(ptr);
}

Value* StoreInst::GetValue() const { return GetOperand(0); }

Value* StoreInst::GetPtr() const { return GetOperand(1); }

BranchInst::BranchInst(std::shared_ptr<Type> void_ty, BasicBlock* target)
    : Instruction(Opcode::Br, std::move(void_ty), "") {
  if (!target) {
    throw std::runtime_error(FormatError("ir", "BranchInst 缺少目标块"));
  }
  if (!type_ || !type_->IsVoid()) {
    throw std::runtime_error(FormatError("ir", "BranchInst 返回类型必须为 void"));
  }
  AddOperand(target);
}

BasicBlock* BranchInst::GetTarget() const {
  return static_cast<BasicBlock*>(GetOperand(0));
}

CondBranchInst::CondBranchInst(std::shared_ptr<Type> void_ty, Value* cond,
                               BasicBlock* true_bb, BasicBlock* false_bb)
    : Instruction(Opcode::CondBr, std::move(void_ty), "") {
  if (!cond || !true_bb || !false_bb) {
    throw std::runtime_error(FormatError("ir", "CondBranchInst 参数不完整"));
  }
  if (!type_ || !type_->IsVoid()) {
    throw std::runtime_error(
        FormatError("ir", "CondBranchInst 返回类型必须为 void"));
  }
  if (!cond->GetType() || !cond->GetType()->IsInt32()) {
    throw std::runtime_error(FormatError("ir", "CondBranchInst 条件必须为 i32"));
  }
  AddOperand(cond);
  AddOperand(true_bb);
  AddOperand(false_bb);
}

Value* CondBranchInst::GetCond() const { return GetOperand(0); }

BasicBlock* CondBranchInst::GetTrueBlock() const {
  return static_cast<BasicBlock*>(GetOperand(1));
}

BasicBlock* CondBranchInst::GetFalseBlock() const {
  return static_cast<BasicBlock*>(GetOperand(2));
}

CallInst::CallInst(std::shared_ptr<Type> ret_ty, Function* callee,
                   std::vector<Value*> args, std::string name)
    : Instruction(Opcode::Call, std::move(ret_ty), std::move(name)) {
  if (!callee) {
    throw std::runtime_error(FormatError("ir", "CallInst 缺少被调函数"));
  }
  const auto& param_types = callee->GetParamTypes();
  if (args.size() != param_types.size()) {
    throw std::runtime_error(FormatError("ir", "CallInst 参数个数不匹配"));
  }
  if (!type_ || !callee->GetType() || type_->GetKind() != callee->GetType()->GetKind()) {
    throw std::runtime_error(FormatError("ir", "CallInst 返回类型与函数签名不匹配"));
  }

  AddOperand(callee);
  for (size_t i = 0; i < args.size(); ++i) {
    auto* arg = args[i];
    if (!arg || !arg->GetType()) {
      throw std::runtime_error(FormatError("ir", "CallInst 存在非法参数"));
    }
    if (!param_types[i] || arg->GetType()->GetKind() != param_types[i]->GetKind()) {
      throw std::runtime_error(FormatError("ir", "CallInst 参数类型不匹配"));
    }
    AddOperand(arg);
  }
}

Function* CallInst::GetCallee() const {
  return static_cast<Function*>(GetOperand(0));
}

size_t CallInst::GetNumArgs() const { return GetNumOperands() - 1; }

Value* CallInst::GetArg(size_t index) const {
  if (index >= GetNumArgs()) {
    throw std::out_of_range("CallInst arg index out of range");
  }
  return GetOperand(index + 1);
}

GepInst::GepInst(std::shared_ptr<Type> ptr_ty, Value* base, Value* index,
                 std::string name)
    : Instruction(Opcode::Gep, std::move(ptr_ty), std::move(name)) {
  if (!base || !index) {
    throw std::runtime_error(FormatError("ir", "GepInst 缺少操作数"));
  }
  if (!base->GetType() || !base->GetType()->IsPtrInt32()) {
    throw std::runtime_error(FormatError("ir", "GepInst base 必须为 i32*"));
  }
  if (!index->GetType() || !index->GetType()->IsInt32()) {
    throw std::runtime_error(FormatError("ir", "GepInst index 必须为 i32"));
  }
  AddOperand(base);
  AddOperand(index);
}

Value* GepInst::GetBase() const { return GetOperand(0); }
Value* GepInst::GetIndex() const { return GetOperand(1); }

}  // namespace ir
