// 管理基础类型、整型常量池和临时名生成。
#include "ir/IR.h"

#include <sstream>

namespace ir {

Context::~Context() = default;

ConstantInt* Context::GetConstInt(int v) {
  auto it = const_ints_.find(v);
  if (it != const_ints_.end()) return it->second.get();
  auto inserted =
      const_ints_.emplace(v, std::make_unique<ConstantInt>(Type::GetInt32Type(), v)).first;
  return inserted->second.get();
}

ConstantFloat* Context::GetConstFloat(float v) {
  auto it = const_floats_.find(v);
  if (it != const_floats_.end()) return it->second.get();
  auto inserted =
      const_floats_.emplace(v, std::make_unique<ConstantFloat>(Type::GetFloatType(), v)).first;
  return inserted->second.get();
}

ConstantArray* Context::GetConstArray(std::shared_ptr<Type> ty, std::vector<ConstantValue*> elements) {
  auto ca = std::make_unique<ConstantArray>(std::move(ty), std::move(elements));
  auto* ptr = ca.get();
  const_arrays_.push_back(std::move(ca));
  return ptr;
}

ConstantZero* Context::GetConstZero(std::shared_ptr<Type> ty) {
  auto cz = std::make_unique<ConstantZero>(std::move(ty));
  auto* ptr = cz.get();
  const_zeros_.push_back(std::move(cz));
  return ptr;
}

std::string Context::NextTemp() {
  std::ostringstream oss;
  oss << "%t" << ++temp_index_;
  return oss.str();
}

}  // namespace ir
