#include "RISCv64Backend.h"
#include "RISCv64ISel.h"
#include "RISCv64RegAlloc.h"
#include "RISCv64AsmPrinter.h"
#include "RISCv64Passes.h" // 包含优化Pass的头文件
#include <sstream>

namespace sysy {

// 顶层入口
std::string RISCv64CodeGen::code_gen() {
    return module_gen();
}

// 模块级代码生成
std::string RISCv64CodeGen::module_gen() {
    std::stringstream ss;
    
    // 1. 处理全局变量 (.data段)
    if (!module->getGlobals().empty()) {
        ss << ".data\n";
        for (const auto& global : module->getGlobals()) {
            ss << ".globl " << global->getName() << "\n";
            ss << global->getName() << ":\n";
            const auto& init_values = global->getInitValues();
            for (size_t i = 0; i < init_values.getValues().size(); ++i) {
                auto val = init_values.getValues()[i];
                auto count = init_values.getNumbers()[i];
                if (auto constant = dynamic_cast<ConstantValue*>(val)) {
                    for (unsigned j = 0; j < count; ++j) {
                        if (constant->isInt()) {
                            ss << "    .word " << constant->getInt() << "\n";
                        } else {
                            float f = constant->getFloat();
                            uint32_t float_bits = *(uint32_t*)&f;
                            ss << "    .word " << float_bits << "\n";
                        }
                    }
                }
            }
        }
    }

    // 2. 处理函数 (.text段)
    if (!module->getFunctions().empty()) {
        ss << ".text\n";
        for (const auto& func_pair : module->getFunctions()) {
            if (func_pair.second.get()) {
                ss << function_gen(func_pair.second.get());
            }
        }
    }
    return ss.str();
}

// function_gen 现在是包含具体优化名称的、完整的处理流水线
std::string RISCv64CodeGen::function_gen(Function* func) {
    // === 完整的后端处理流水线 ===

    // 阶段 1: 指令选择 (sysy::IR -> LLIR with virtual registers)
    RISCv64ISel isel;
    std::unique_ptr<MachineFunction> mfunc = isel.runOnFunction(func);

    std::stringstream ss1;
    RISCv64AsmPrinter printer1(mfunc.get());
    printer1.run(ss1, true);

    // 阶段 2: 指令调度 (Instruction Scheduling)
    PreRA_Scheduler scheduler;
    scheduler.runOnMachineFunction(mfunc.get());

    // 阶段 3: 物理寄存器分配 (Register Allocation)
    RISCv64RegAlloc reg_alloc(mfunc.get());
    reg_alloc.run();

    // 阶段 3.5: 处理被调用者保存寄存器
    CalleeSavedHandler callee_handler;
    callee_handler.runOnMachineFunction(mfunc.get());

    // 阶段 4: 窥孔优化 (Peephole Optimization)
    PeepholeOptimizer peephole;
    peephole.runOnMachineFunction(mfunc.get());

    // 阶段 5: 局部指令调度 (Local Scheduling)
    PostRA_Scheduler local_scheduler;
    local_scheduler.runOnMachineFunction(mfunc.get());

    // 阶段 6: 代码发射 (Code Emission)
    std::stringstream ss;
    RISCv64AsmPrinter printer(mfunc.get());
    printer.run(ss);
    if (DEBUG) ss << "\n" << ss1.str(); // 将指令选择阶段的结果也包含在最终输出中
    return ss.str();
}

} // namespace sysy