#include "BasicBlock.h"
#include "Constant.h"
#include "Function.h"
#include "IRStmtBuilder.h"
#include "Module.h"
#include "Type.h"

#include <iostream>
#include <memory>

#define CONST_INT(num) \
    ConstantInt::create(num, module)

#define CONST_FP(num) \
    ConstantFloat::create(num, module) // 得到常数值的表示,方便后面多次用到

using namespace SysYF::IR;

int main()
{
    // 创建module和builder
    auto module = Module::create("SysYF code");
    auto builder = IRStmtBuilder::create(nullptr, module);
    SysYF::Ptr<Type> Int32Type = Type::get_int32_type(module);
    SysYF::Ptr<Type> FloatType = Type::get_float_type(module);
    // main 函数
    auto mainFun = Function::create(FunctionType::create(Int32Type, {}), "main", module);
    auto bb = BasicBlock::create(module, "entry", mainFun);
    builder->set_insert_point(bb);
    // 分配空间和赋初值
    auto ret_Alloca = builder->create_alloca(Int32Type);                      // int return
    auto b_Alloca = builder->create_alloca(FloatType);                        // float b
    auto ArrayType_a = ArrayType::get(Int32Type, 2);                          // Type of Array a
    auto a_Alloca = builder->create_alloca(ArrayType_a);                      // int a[2]
    auto a0GEP = builder->create_gep(a_Alloca, {CONST_INT(0), CONST_INT(0)}); // a[0] pointer
    auto a1GEP = builder->create_gep(a_Alloca, {CONST_INT(0), CONST_INT(1)}); // a[1] pointer

    builder->create_store(CONST_FP(1.8), b_Alloca); // b = 1.8
    builder->create_store(CONST_INT(2), a0GEP);        // a[0] = 2
    builder->create_store(CONST_INT(0), a1GEP);        // a[1] = 0
    // 计算返回值
    auto b_Load = builder->create_load(b_Alloca);                // load b
    auto a0_Load = builder->create_load(a0GEP);                  // load a[0]
    auto a0_float = builder->create_sitofp(a0_Load, FloatType);  // int to float
    auto ans_float = builder->create_fmul(b_Load, a0_float);     // b * a[0]
    auto ans_int = builder->create_fptosi(ans_float, Int32Type); // float to int
    builder->create_store(ans_int, a1GEP);                       // store ans to a[1]
    builder->create_store(ans_int, ret_Alloca);                  // return ans
    // return
    auto ret_Load = builder->create_load(ret_Alloca);
    builder->create_ret(ret_Load);
    // 输出IR
    std::cout << module->print();
}