diff --git a/CMakeLists.txt b/CMakeLists.txt index 65ba81d6156c3b086d6d12ec1965b21420803ed9..236bc647b8a94882f865cd22e23ae370392620d8 100755 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -39,6 +39,7 @@ INCLUDE_DIRECTORIES( include/cminusfc include/common include/lightir + include/codegen ${LLVM_INCLUDE_DIRS} ) diff --git a/include/codegen/ASMInstruction.hpp b/include/codegen/ASMInstruction.hpp new file mode 100644 index 0000000000000000000000000000000000000000..5b2d04da91dbcbc9f1ec600809deb133bb0c33c2 --- /dev/null +++ b/include/codegen/ASMInstruction.hpp @@ -0,0 +1,25 @@ +#pragma once + +#include +#include + +struct ASMInstruction { + enum InstType { Instruction, Atrribute, Label, Comment } type; + std::string content; + + explicit ASMInstruction(std::string s, InstType ty = Instruction) + : type(ty), content(s) {} + + std::string format() const { + switch (type) { + case ASMInstruction::Instruction: + case ASMInstruction::Atrribute: + return "\t" + content + "\n"; + case ASMInstruction::Label: + return content + ":\n"; + case ASMInstruction::Comment: + return "# " + content + "\n"; + } + assert(false && "unreachable"); + } +}; diff --git a/include/codegen/CodeGen.hpp b/include/codegen/CodeGen.hpp new file mode 100644 index 0000000000000000000000000000000000000000..39dd6223ab475ea0a5f0dacff186ebc648fbfece --- /dev/null +++ b/include/codegen/CodeGen.hpp @@ -0,0 +1,101 @@ +#pragma once + +#include "ASMInstruction.hpp" +#include "Module.hpp" +#include "Register.hpp" + +class CodeGen { + public: + explicit CodeGen(Module *module) : m(module) {} + + std::string print() const; + + void run(); + + template void append_inst(Args... arg) { + output.emplace_back(arg...); + } + + void + append_inst(const char *inst, std::initializer_list args, + ASMInstruction::InstType ty = ASMInstruction::Instruction) { + auto content = std::string(inst) + " "; + for (const auto &arg : args) { + content += arg + ", "; + } + content.pop_back(); + content.pop_back(); + output.emplace_back(content, ty); + } + + private: + void allocate(); + void copy_stmt(); // for phi copy + + // 向寄存器中装载数据 + void load_to_greg(Value *, const Reg &); + void load_to_freg(Value *, const FReg &); + void load_from_stack_to_greg(Value *, const Reg &); + + // 向寄存器中加载立即数 + void load_large_int32(int32_t, const Reg &); + void load_large_int64(int64_t, const Reg &); + void load_float_imm(float, const FReg &); + + // 将寄存器中的数据保存回栈上 + void store_from_greg(Value *, const Reg &); + void store_from_freg(Value *, const FReg &); + + void gen_prologue(); + void gen_ret(); + void gen_br(); + void gen_binary(); + void gen_float_binary(); + void gen_alloca(); + void gen_load(); + void gen_store(); + void gen_icmp(); + void gen_fcmp(); + void gen_zext(); + void gen_call(); + void gen_gep(); + void gen_sitofp(); + void gen_fptosi(); + void gen_epilogue(); + + static std::string label_name(BasicBlock *bb) { + return "." + bb->get_parent()->get_name() + "_" + bb->get_name(); + } + + static std::string func_exit_label_name(Function *func) { + return func->get_name() + "_exit"; + } + + static std::string fcmp_label_name(BasicBlock *bb, unsigned cnt) { + return label_name(bb) + "_fcmp_" + std::to_string(cnt); + } + + struct { + /* 随着ir遍历设置 */ + Function *func{nullptr}; // 当前函数 + BasicBlock *bb{nullptr}; // 当前基本块 + Instruction *inst{nullptr}; // 当前指令 + /* 在allocate()中设置 */ + unsigned frame_size{0}; // 当前函数的栈帧大小 + std::unordered_map offset_map{}; // 指针相对 fp 的偏移 + unsigned fcmp_cnt{0}; // fcmp 的计数器, 用于创建 fcmp 需要的 label + + void clear() { + func = nullptr; + bb = nullptr; + inst = nullptr; + frame_size = 0; + fcmp_cnt = 0; + offset_map.clear(); + } + + } context; + + Module *m; + std::list output; +}; diff --git a/include/codegen/CodeGenUtil.hpp b/include/codegen/CodeGenUtil.hpp new file mode 100644 index 0000000000000000000000000000000000000000..69ccba2613b0a48b828e90497492f9ab26035964 --- /dev/null +++ b/include/codegen/CodeGenUtil.hpp @@ -0,0 +1,75 @@ +#pragma once + +#include + +/* 关于位宽 */ +#define IMM_12_MAX 0x7FF +#define IMM_12_MIN -0x800 + +#define LOW_12_MASK 0x00000FFF +#define LOW_20_MASK 0x000FFFFF +#define LOW_32_MASK 0xFFFFFFFF + +inline unsigned ALIGN(unsigned x, unsigned alignment) { + return ((x + (alignment - 1)) & ~(alignment - 1)); +} + +inline bool IS_IMM_12(int x) { return x <= IMM_12_MAX and x >= IMM_12_MIN; } + +/* 栈帧相关 */ +#define PROLOGUE_OFFSET_BASE 16 // $ra $fp +#define PROLOGUE_ALIGN 16 + +/* 龙芯指令 */ +// Arithmetic +#define ADD "add" +#define SUB "sub" +#define MUL "mul" +#define DIV "div" + +#define ADDI "addi" + +#define FADD "fadd" +#define FSUB "fsub" +#define FMUL "fmul" +#define FDIV "fdiv" + +#define ORI "ori" + +#define LU12I_W "lu12i.w" +#define LU32I_D "lu32i.d" +#define LU52I_D "lu52i.d" + +// Data transfer (greg <-> freg) +#define GR2FR "movgr2fr" +#define FR2GR "movfr2gr" + +// Memory access +#define LOAD "ld" +#define STORE "st" +#define FLOAD "fld" +#define FSTORE "fst" + +#define BYTE ".b" +#define HALF_WORD ".h" +#define WORD ".w" +#define DOUBLE ".d" + +#define SINGLE ".s" // float +#define LONG ".l" + +// ASM syntax sugar +#define LOAD_ADDR "la.local" + +// errors +class not_implemented_error : public std::logic_error { + public: + explicit not_implemented_error(std::string &&err_msg = "") + : std::logic_error(err_msg){}; +}; + +class unreachable_error : public std::logic_error { + public: + explicit unreachable_error(std::string &&err_msg = "") + : std::logic_error(err_msg){}; +}; diff --git a/include/codegen/Register.hpp b/include/codegen/Register.hpp new file mode 100644 index 0000000000000000000000000000000000000000..675bc1b27c7871a8009a30fcea7af6d5ea125700 --- /dev/null +++ b/include/codegen/Register.hpp @@ -0,0 +1,85 @@ +#pragma once + +#include +#include + +/* General-purpose Register Convention: + * Name Alias Meaning + * $r0 $zero constant 0 + * $r1 $ra return address + * $r2 $tp thread pointer + * $r3 $sp stack pointer + * $r4 - $r5 $a0 - $a1 argument, return value + * $r6 - $r11 $a2 - $a7 argument + * $r12 - $r20 $t0 - $t8 temporary + * $r21 saved + * $r22 $fp / $s9 frame pointer + * $r23 - $r31 $s0 - $s8 static + * + * Floating-point Register Convention + * Name Alias Meaning + * $f0-$f1 $fa0-$fa1 argument/return value + * $f2-$f7 $fa2-$fa7 argument + * $f8-$f23 $ft0-$ft15 temporary + * $f24-$f31 $fs0-$fs7 static + */ + +struct Reg { + unsigned id; + + explicit Reg(unsigned i) : id(i) { assert(i <= 31); } + bool operator==(const Reg &other) { return id == other.id; } + + std::string print() const; + + static Reg zero() { return Reg(0); } + static Reg ra() { return Reg(1); } + static Reg sp() { return Reg(3); } + static Reg fp() { return Reg(22); } + static Reg a(unsigned i) { + assert(0 <= i and i <= 7); + return Reg(i + 4); + } + static Reg t(unsigned i) { + assert(0 <= i and i <= 8); + return Reg(i + 12); + } + static Reg s(unsigned i) { + assert(0 <= i and i <= 9); + if (i == 9) + return Reg(22); + else + return Reg(i + 23); + } +}; + +struct FReg { + unsigned id; + + explicit FReg(unsigned i) : id(i) { assert(i <= 31); } + bool operator==(const FReg &other) { return id == other.id; } + + std::string print() const; + + static FReg fa(unsigned i) { + assert(0 <= i and i <= 7); + return FReg(i); + } + static FReg ft(unsigned i) { + assert(0 <= i and i <= 15); + return FReg(i + 8); + } + static FReg fs(unsigned i) { + assert(0 <= i and i <= 7); + return FReg(i + 24); + } +}; + +struct CFReg { + unsigned id; + + explicit CFReg(unsigned i) : id(i) { assert(i <= 7); } + bool operator==(const CFReg &other) { return id == other.id; } + + std::string print() const { return "$fcc" + std::to_string(id); } +}; diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index a1ec57b1a3101f0c8e18a4ab8035c8d6b509b352..4a64eae897033353de03e7e89dbd164c35217db2 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -3,4 +3,5 @@ add_subdirectory(common) add_subdirectory(logging) add_subdirectory(cminusfc) add_subdirectory(lightir) -add_subdirectory(io) \ No newline at end of file +add_subdirectory(io) +add_subdirectory(codegen) diff --git a/src/cminusfc/CMakeLists.txt b/src/cminusfc/CMakeLists.txt index 3e54d07f7f8a7fbb57d956d02a333118541207e6..77342fc778fa91b5e49cc6bb73258de55d9787f9 100644 --- a/src/cminusfc/CMakeLists.txt +++ b/src/cminusfc/CMakeLists.txt @@ -8,6 +8,7 @@ target_link_libraries( cminusfc IR_lib common + codegen syntax stdc++fs ) diff --git a/src/cminusfc/main.cpp b/src/cminusfc/main.cpp index 1c1591f9033669d421997aca641732704ae3e75a..af13e17b97fe73f5679eb8b0fd82e3c6e3ab0655 100644 --- a/src/cminusfc/main.cpp +++ b/src/cminusfc/main.cpp @@ -1,6 +1,7 @@ #include "Module.hpp" #include "ast.hpp" #include "cminusf_builder.hpp" +#include "CodeGen.hpp" #include #include @@ -16,6 +17,7 @@ struct Config { std::filesystem::path output_file; bool emitast{false}; + bool emitasm{false}; bool emitllvm{false}; Config(int argc, char **argv) : argc(argc), argv(argv) { @@ -55,9 +57,13 @@ int main(int argc, char **argv) { output_stream << "; ModuleID = 'cminus'\n"; output_stream << "source_filename = " << abs_path << "\n\n"; output_stream << m->print(); + } else if (config.emitasm) { + CodeGen codegen(m.get()); + codegen.run(); + output_stream << codegen.print(); } - // TODO: lab3 lab4 (IR optimization or codegen) + // TODO: lab4 (IR optimization) } return 0; @@ -79,6 +85,8 @@ void Config::parse_cmd_line() { emitast = true; } else if (argv[i] == "-emit-llvm"s) { emitllvm = true; + } else if (argv[i] == "-S"s) { + emitasm = true; } else { if (input_file.empty()) { input_file = argv[i]; @@ -102,6 +110,8 @@ void Config::check() { */ if (output_file.empty()) { output_file = input_file.stem(); + if (emitasm && !emitllvm && !emitast) + output_file += ".s"; } } diff --git a/src/codegen/CMakeLists.txt b/src/codegen/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..aa3b92370f07081c31aa2afa64d9ad7c54aa9fbb --- /dev/null +++ b/src/codegen/CMakeLists.txt @@ -0,0 +1,7 @@ +add_library( + codegen STATIC + CodeGen.cpp + Register.cpp +) + +target_link_libraries(codegen common IR_lib) diff --git a/src/codegen/CodeGen.cpp b/src/codegen/CodeGen.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f947e4c0b50e9a33e77ec707aeeb6b399b3fd07e --- /dev/null +++ b/src/codegen/CodeGen.cpp @@ -0,0 +1,502 @@ +#include "CodeGen.hpp" + +#include "CodeGenUtil.hpp" + +void CodeGen::allocate() { + // 备份 $ra $fp + unsigned offset = PROLOGUE_OFFSET_BASE; + + // 为每个参数分配栈空间 + for (auto &arg : context.func->get_args()) { + auto size = arg.get_type()->get_size(); + offset = offset + size; + context.offset_map[&arg] = -static_cast(offset); + } + + // 为指令结果分配栈空间 + for (auto &bb : context.func->get_basic_blocks()) { + for (auto &instr : bb.get_instructions()) { + // 每个非 void 的定值都分配栈空间 + if (not instr.is_void()) { + auto size = instr.get_type()->get_size(); + offset = offset + size; + context.offset_map[&instr] = -static_cast(offset); + } + // alloca 的副作用:分配额外空间 + if (instr.is_alloca()) { + auto *alloca_inst = static_cast(&instr); + auto alloc_size = alloca_inst->get_alloca_type()->get_size(); + offset += alloc_size; + } + } + } + + // 分配栈空间,需要是 16 的整数倍 + context.frame_size = ALIGN(offset, PROLOGUE_ALIGN); +} + +void CodeGen::copy_stmt() { + for (auto &succ : context.bb->get_succ_basic_blocks()) { + for (auto &inst : succ->get_instructions()) { + if (inst.is_phi()) { + // 遍历后继块中 phi 的定值 bb + for (unsigned i = 1; i < inst.get_operands().size(); i += 2) { + // phi 的定值 bb 是当前翻译块 + if (inst.get_operand(i) == context.bb) { + auto *lvalue = inst.get_operand(i - 1); + if (lvalue->get_type()->is_float_type()) { + load_to_freg(lvalue, FReg::fa(0)); + store_from_freg(&inst, FReg::fa(0)); + } else { + load_to_greg(lvalue, Reg::a(0)); + store_from_greg(&inst, Reg::a(0)); + } + break; + } + // 如果没有找到当前翻译块,说明是 undef,无事可做 + } + } else { + break; + } + } + } +} + +void CodeGen::load_to_greg(Value *val, const Reg ®) { + assert(val->get_type()->is_integer_type() || + val->get_type()->is_pointer_type()); + + if (auto *constant = dynamic_cast(val)) { + int32_t val = constant->get_value(); + if (IS_IMM_12(val)) { + append_inst(ADDI WORD, {reg.print(), "$zero", std::to_string(val)}); + } else { + load_large_int32(val, reg); + } + } else if (auto *global = dynamic_cast(val)) { + append_inst(LOAD_ADDR, {reg.print(), global->get_name()}); + } else { + load_from_stack_to_greg(val, reg); + } +} + +void CodeGen::load_large_int32(int32_t val, const Reg ®) { + int32_t high_20 = val >> 12; // si20 + uint32_t low_12 = val & LOW_12_MASK; + append_inst(LU12I_W, {reg.print(), std::to_string(high_20)}); + append_inst(ORI, {reg.print(), reg.print(), std::to_string(low_12)}); +} + +void CodeGen::load_large_int64(int64_t val, const Reg ®) { + auto low_32 = static_cast(val & LOW_32_MASK); + load_large_int32(low_32, reg); + + auto high_32 = static_cast(val >> 32); + int32_t high_32_low_20 = (high_32 << 12) >> 12; // si20 + int32_t high_32_high_12 = high_32 >> 20; // si12 + append_inst(LU32I_D, {reg.print(), std::to_string(high_32_low_20)}); + append_inst(LU52I_D, + {reg.print(), reg.print(), std::to_string(high_32_high_12)}); +} + +void CodeGen::load_from_stack_to_greg(Value *val, const Reg ®) { + auto offset = context.offset_map.at(val); + auto offset_str = std::to_string(offset); + auto *type = val->get_type(); + if (IS_IMM_12(offset)) { + if (type->is_int1_type()) { + append_inst(LOAD BYTE, {reg.print(), "$fp", offset_str}); + } else if (type->is_int32_type()) { + append_inst(LOAD WORD, {reg.print(), "$fp", offset_str}); + } else { // Pointer + append_inst(LOAD DOUBLE, {reg.print(), "$fp", offset_str}); + } + } else { + load_large_int64(offset, reg); + append_inst(ADD DOUBLE, {reg.print(), "$fp", reg.print()}); + if (type->is_int1_type()) { + append_inst(LOAD BYTE, {reg.print(), reg.print(), "0"}); + } else if (type->is_int32_type()) { + append_inst(LOAD WORD, {reg.print(), reg.print(), "0"}); + } else { // Pointer + append_inst(LOAD DOUBLE, {reg.print(), reg.print(), "0"}); + } + } +} + +void CodeGen::store_from_greg(Value *val, const Reg ®) { + auto offset = context.offset_map.at(val); + auto offset_str = std::to_string(offset); + auto *type = val->get_type(); + if (IS_IMM_12(offset)) { + if (type->is_int1_type()) { + append_inst(STORE BYTE, {reg.print(), "$fp", offset_str}); + } else if (type->is_int32_type()) { + append_inst(STORE WORD, {reg.print(), "$fp", offset_str}); + } else { // Pointer + append_inst(STORE DOUBLE, {reg.print(), "$fp", offset_str}); + } + } else { + auto addr = Reg::t(8); + load_large_int64(offset, addr); + append_inst(ADD DOUBLE, {addr.print(), "$fp", addr.print()}); + if (type->is_int1_type()) { + append_inst(STORE BYTE, {reg.print(), addr.print(), "0"}); + } else if (type->is_int32_type()) { + append_inst(STORE WORD, {reg.print(), addr.print(), "0"}); + } else { // Pointer + append_inst(STORE DOUBLE, {reg.print(), addr.print(), "0"}); + } + } +} + +void CodeGen::load_to_freg(Value *val, const FReg &freg) { + assert(val->get_type()->is_float_type()); + if (auto *constant = dynamic_cast(val)) { + float val = constant->get_value(); + load_float_imm(val, freg); + } else { + auto offset = context.offset_map.at(val); + auto offset_str = std::to_string(offset); + if (IS_IMM_12(offset)) { + append_inst(FLOAD SINGLE, {freg.print(), "$fp", offset_str}); + } else { + auto addr = Reg::t(8); + load_large_int64(offset, addr); + append_inst(ADD DOUBLE, {addr.print(), "$fp", addr.print()}); + append_inst(FLOAD SINGLE, {freg.print(), addr.print(), "0"}); + } + } +} + +void CodeGen::load_float_imm(float val, const FReg &r) { + int32_t bytes = *reinterpret_cast(&val); + load_large_int32(bytes, Reg::t(8)); + append_inst(GR2FR WORD, {r.print(), Reg::t(8).print()}); +} + +void CodeGen::store_from_freg(Value *val, const FReg &r) { + auto offset = context.offset_map.at(val); + if (IS_IMM_12(offset)) { + auto offset_str = std::to_string(offset); + append_inst(FSTORE SINGLE, {r.print(), "$fp", offset_str}); + } else { + auto addr = Reg::t(8); + load_large_int64(offset, addr); + append_inst(ADD DOUBLE, {addr.print(), "$fp", addr.print()}); + append_inst(FSTORE SINGLE, {r.print(), addr.print(), "0"}); + } +} + +void CodeGen::gen_prologue() { + if (IS_IMM_12(-static_cast(context.frame_size))) { + append_inst("st.d $ra, $sp, -8"); + append_inst("st.d $fp, $sp, -16"); + append_inst("addi.d $fp, $sp, 0"); + append_inst("addi.d $sp, $sp, " + + std::to_string(-static_cast(context.frame_size))); + } else { + load_large_int64(context.frame_size, Reg::t(0)); + append_inst("st.d $ra, $sp, -8"); + append_inst("st.d $fp, $sp, -16"); + append_inst("sub.d $sp, $sp, $t0"); + append_inst("add.d $fp, $sp, $t0"); + } + + int garg_cnt = 0; + int farg_cnt = 0; + for (auto &arg : context.func->get_args()) { + if (arg.get_type()->is_float_type()) { + store_from_freg(&arg, FReg::fa(farg_cnt++)); + } else { // int or pointer + store_from_greg(&arg, Reg::a(garg_cnt++)); + } + } +} + +void CodeGen::gen_epilogue() { + // TODO 根据你的理解设定函数的 epilogue + throw not_implemented_error{__FUNCTION__}; +} + + +void CodeGen::gen_ret() { + // TODO 函数返回,思考如何处理返回值、寄存器备份,如何返回调用者地址 + throw not_implemented_error{__FUNCTION__}; +} + +void CodeGen::gen_br() { + auto *branchInst = static_cast(context.inst); + if (branchInst->is_cond_br()) { + // TODO 补全条件跳转的情况 + throw not_implemented_error{__FUNCTION__}; + } else { + auto *branchbb = static_cast(branchInst->get_operand(0)); + append_inst("b " + label_name(branchbb)); + } +} + +void CodeGen::gen_binary() { + load_to_greg(context.inst->get_operand(0), Reg::t(0)); + load_to_greg(context.inst->get_operand(1), Reg::t(1)); + switch (context.inst->get_instr_type()) { + case Instruction::add: + output.emplace_back("add.w $t2, $t0, $t1"); + break; + case Instruction::sub: + output.emplace_back("sub.w $t2, $t0, $t1"); + break; + case Instruction::mul: + output.emplace_back("mul.w $t2, $t0, $t1"); + break; + case Instruction::sdiv: + output.emplace_back("div.w $t2, $t0, $t1"); + break; + default: + assert(false); + } + store_from_greg(context.inst, Reg::t(2)); +} + +void CodeGen::gen_float_binary() { + // TODO 浮点类型的二元指令 + throw not_implemented_error{__FUNCTION__}; +} + +void CodeGen::gen_alloca() { + /* 我们已经为 alloca 的内容分配空间,在此我们还需保存 alloca + * 指令自身产生的定值,即指向 alloca 空间起始地址的指针 + */ + // TODO 将 alloca 出空间的起始地址保存在栈帧上 + throw not_implemented_error{__FUNCTION__}; +} + +void CodeGen::gen_load() { + auto *ptr = context.inst->get_operand(0); + auto *type = context.inst->get_type(); + load_to_greg(ptr, Reg::t(0)); + + if (type->is_float_type()) { + append_inst("fld.s $ft0, $t0, 0"); + store_from_freg(context.inst, FReg::ft(0)); + } else { + // TODO load 整数类型的数据 + throw not_implemented_error{__FUNCTION__}; + } +} + +void CodeGen::gen_store() { + // TODO 翻译 store 指令 + throw not_implemented_error{__FUNCTION__}; +} + +void CodeGen::gen_icmp() { + // TODO 处理各种整数比较的情况 + throw not_implemented_error{__FUNCTION__}; +} + +void CodeGen::gen_fcmp() { + // TODO 处理各种浮点数比较的情况 + throw not_implemented_error{__FUNCTION__}; +} + +void CodeGen::gen_zext() { + // TODO 将窄位宽的整数数据进行零扩展 + throw not_implemented_error{__FUNCTION__}; +} + +void CodeGen::gen_call() { + // TODO 函数调用,注意我们只需要通过寄存器传递参数,即不需考虑栈上传参的情况 + throw not_implemented_error{__FUNCTION__}; +} + +/* + * %op = getelementptr [10 x i32], [10 x i32]* %op, i32 0, i32 %op + * %op = getelementptr i32, i32* %op, i32 %op + * + * Memory layout + * - ^ + * +-----------+ | Smaller address + * | arg ptr |---+ | + * +-----------+ | | + * | | | | + * +-----------+ / | + * | |<-- | + * | | \ | + * | | | | + * | Array | | | + * | | | | + * | | | | + * | | | | + * +-----------+ | | + * | Pointer |---+ | + * +-----------+ | + * | | | + * +-----------+ | + * | | | + * +-----------+ | + * | | | + * +-----------+ | Larger address + * + + */ +void CodeGen::gen_gep() { + // TODO 计算内存地址 + throw not_implemented_error{__FUNCTION__}; +} + +void CodeGen::gen_sitofp() { + // TODO 整数转向浮点数 + throw not_implemented_error{__FUNCTION__}; +} + +void CodeGen::gen_fptosi() { + // TODO 浮点数转向整数,注意向下取整(round to zero) + throw not_implemented_error{__FUNCTION__}; +} + +void CodeGen::run() { + // 确保每个函数中基本块的名字都被设置好 + m->set_print_name(); + + /* 使用 GNU 伪指令为全局变量分配空间 + * 你可以使用 `la.local` 指令将标签 (全局变量) 的地址载入寄存器中, 比如 + * 要将 `a` 的地址载入 $t0, 只需要 `la.local $t0, a` + */ + if (!m->get_global_variable().empty()) { + append_inst("Global variables", ASMInstruction::Comment); + /* 虽然下面两条伪指令可以简化为一条 `.bss` 伪指令, 但是我们还是选择使用 + * `.section` 将全局变量放到可执行文件的 BSS 段, 原因如下: + * - 尽可能对齐交叉编译器 loongarch64-unknown-linux-gnu-gcc 的行为 + * - 支持更旧版本的 GNU 汇编器, 因为 `.bss` 伪指令是应该相对较新的指令, + * GNU 汇编器在 2023 年 2 月的 2.37 版本才将其引入 + */ + append_inst(".text", ASMInstruction::Atrribute); + append_inst(".section", {".bss", "\"aw\"", "@nobits"}, + ASMInstruction::Atrribute); + for (auto &global : m->get_global_variable()) { + auto size = + global.get_type()->get_pointer_element_type()->get_size(); + append_inst(".globl", {global.get_name()}, + ASMInstruction::Atrribute); + append_inst(".type", {global.get_name(), "@object"}, + ASMInstruction::Atrribute); + append_inst(".size", {global.get_name(), std::to_string(size)}, + ASMInstruction::Atrribute); + append_inst(global.get_name(), ASMInstruction::Label); + append_inst(".space", {std::to_string(size)}, + ASMInstruction::Atrribute); + } + } + + // 函数代码段 + output.emplace_back(".text", ASMInstruction::Atrribute); + for (auto &func : m->get_functions()) { + if (not func.is_declaration()) { + // 更新 context + context.clear(); + context.func = &func; + + // 函数信息 + append_inst(".globl", {func.get_name()}, ASMInstruction::Atrribute); + append_inst(".type", {func.get_name(), "@function"}, + ASMInstruction::Atrribute); + append_inst(func.get_name(), ASMInstruction::Label); + + // 分配函数栈帧 + allocate(); + // 生成 prologue + gen_prologue(); + + for (auto &bb : func.get_basic_blocks()) { + context.bb = &bb; + append_inst(label_name(context.bb), ASMInstruction::Label); + for (auto &instr : bb.get_instructions()) { + // For debug + append_inst(instr.print(), ASMInstruction::Comment); + context.inst = &instr; // 更新 context + switch (instr.get_instr_type()) { + case Instruction::ret: + gen_ret(); + break; + case Instruction::br: + copy_stmt(); + gen_br(); + break; + case Instruction::add: + case Instruction::sub: + case Instruction::mul: + case Instruction::sdiv: + gen_binary(); + break; + case Instruction::fadd: + case Instruction::fsub: + case Instruction::fmul: + case Instruction::fdiv: + gen_float_binary(); + break; + case Instruction::alloca: + /* 对于 alloca 指令,我们已经为 alloca + * 的内容分配空间,在此我们还需保存 alloca + * 指令自身产生的定值,即指向 alloca 空间起始地址的指针 + */ + gen_alloca(); + break; + case Instruction::load: + gen_load(); + break; + case Instruction::store: + gen_store(); + break; + case Instruction::ge: + case Instruction::gt: + case Instruction::le: + case Instruction::lt: + case Instruction::eq: + case Instruction::ne: + gen_icmp(); + break; + case Instruction::fge: + case Instruction::fgt: + case Instruction::fle: + case Instruction::flt: + case Instruction::feq: + case Instruction::fne: + gen_fcmp(); + break; + case Instruction::phi: + /* for phi, just convert to a series of + * copy-stmts */ + /* we can collect all phi and deal them at + * the end */ + break; + case Instruction::call: + gen_call(); + break; + case Instruction::getelementptr: + gen_gep(); + break; + case Instruction::zext: + gen_zext(); + break; + case Instruction::fptosi: + gen_fptosi(); + break; + case Instruction::sitofp: + gen_sitofp(); + break; + } + } + } + // 生成 epilogue + gen_epilogue(); + } + } +} + +std::string CodeGen::print() const { + std::string result; + for (const auto &inst : output) { + result += inst.format(); + } + return result; +} diff --git a/src/codegen/Register.cpp b/src/codegen/Register.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c0c58499a9341b1ce7887db30117ccca40a5e988 --- /dev/null +++ b/src/codegen/Register.cpp @@ -0,0 +1,41 @@ +#include "Register.hpp" +#include + +std::string Reg::print() const { + if (id == 0) { + return "$zero"; + } + if (id == 1) { + return "$ra"; + } + if (id == 2) { + return "$tp"; + } + if (id == 3) { + return "$sp"; + } + if (4 <= id and id <= 11) { + return "$a" + std::to_string(id - 4); + } + if (12 <= id and id <= 20) { + return "$t" + std::to_string(id - 12); + } + if (id == 22) { + return "$fp"; + } + assert(false); +} + +std::string FReg::print() const { + + if (0 <= id and id <= 7) { + return "$fa" + std::to_string(id); + } + if (8 <= id and id <= 23) { + return "$ft" + std::to_string(id - 8); + } + if (24 <= id and id <= 31) { + return "$fs" + std::to_string(id - 24); + } + assert(false); +} diff --git a/tests/3-codegen/README.md b/tests/3-codegen/README.md new file mode 100644 index 0000000000000000000000000000000000000000..91329620a674b92c62ba271492addb1c56ccba9e --- /dev/null +++ b/tests/3-codegen/README.md @@ -0,0 +1,50 @@ +# 2026 实验三:LoongArch64 代码生成 + +本目录提供实验三的框架、热身练习及自动测试。实验三以完成实验一的解析器和实验二的 IR 生成为前提。 + +## 需要完成的内容 + +- `warmup/stu_cpp/`:按照注释完成 6 个热身程序,输入 IR 见 `warmup/ll_cases/`。 +- `../../src/codegen/CodeGen.cpp`:补全标有 TODO 的指令翻译和函数调用、返回等逻辑。 +- `../../include/codegen/`:汇编输出、寄存器和辅助接口。 + +热身程序保留了待填空的代码。完成前置实验和热身程序后,在仓库根目录默认构建即可生成六个热身可执行文件,例如: + +```bash +cmake -S . -B build +cmake --build build +./build/stu_assign_codegen > assign.s +``` + +其他热身目标为 `stu_function_codegen`、`stu_icmp_codegen`、`stu_fcmp_codegen`、`stu_float_codegen` 和 `stu_global_codegen`。 + +## 编译器入口 + +完成前置实验后,在仓库根目录构建编译器: + +```bash +cmake -S . -B build +cmake --build build --target cminusfc +./build/cminusfc -S input.cminus -o output.s +``` + +省略 `-o` 时,`./build/cminusfc -S input.cminus` 默认生成 `input.s`。 + +`-emit-ast` 和 `-emit-llvm` 的现有入口保留。后端框架尚未实现的部分会抛出 `not_implemented_error`,需要完成 TODO 后才能运行相关程序。 + +## 自动测试 + +需要安装 `loongarch64-unknown-linux-gnu-gcc` 和 `qemu-loongarch64`。在以下目录运行测试脚本: + +```bash +cd tests/3-codegen/autogen +./eval_lab3.sh ./testcases debug +# 也可以运行通用测试集 +./eval_lab3.sh ../../testcases_general test +``` + +`debug` 模式额外保存 LLVM IR。脚本生成 LoongArch64 汇编,交叉编译并使用 QEMU 执行,将标准输出和退出码与 `.out` 文件比较。生成文件在 `output/`,详细日志为 `log.txt`。 + +```bash +./cleanup.sh +``` diff --git a/tests/3-codegen/autogen/.gitignore b/tests/3-codegen/autogen/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..9c6495b9ce7c52c57c6667a41a8fc472a7b4328d --- /dev/null +++ b/tests/3-codegen/autogen/.gitignore @@ -0,0 +1,2 @@ +output/ +log.txt diff --git a/tests/3-codegen/autogen/cleanup.sh b/tests/3-codegen/autogen/cleanup.sh new file mode 100755 index 0000000000000000000000000000000000000000..78fecdf3ce08ec95e2f7a2b0db9093dedb5ee19e --- /dev/null +++ b/tests/3-codegen/autogen/cleanup.sh @@ -0,0 +1,2 @@ +#!/bin/bash +rm -rf output log.txt diff --git a/tests/3-codegen/autogen/eval_lab3.sh b/tests/3-codegen/autogen/eval_lab3.sh new file mode 100755 index 0000000000000000000000000000000000000000..43de6d2684f233173f6a39eb7bc2601baf0bbe70 --- /dev/null +++ b/tests/3-codegen/autogen/eval_lab3.sh @@ -0,0 +1,109 @@ +#!/bin/bash + +project_dir=$(realpath ../../../) +io_dir=$(realpath "$project_dir"/src/io) +output_dir=output +suffix=cminus + +LOG=log.txt + +usage() { + cat </dev/null + +mkdir -p $output_dir + +truncate -s 0 $LOG + +if [ $debug_mode = false ]; then + exec 3>/dev/null 4>&1 5>&2 1>&3 2>&3 +else + exec 3>&1 +fi + +if [ $debug_mode = false ]; then + exec 1>&4 2>&5 +fi + +echo "[info] Start testing, using testcase dir: $test_dir" +# asm +for case in $testcases; do + echo "==========$case==========" >>$LOG + case_base_name=$(basename -s .$suffix "$case") + std_out_file=$test_dir/$case_base_name.out + in_file=$test_dir/$case_base_name.in + asm_file=$output_dir/$case_base_name.s + exe_file=$output_dir/$case_base_name + out_file=$output_dir/$case_base_name.out + ll_file=$output_dir/$case_base_name.ll + + echo -n "$case_base_name..." + # if debug mode on, generate .ll also + if [ $debug_mode = true ]; then + bash -c "${project_dir}/build/cminusfc -emit-llvm $case -o $ll_file" >>$LOG 2>&1 + fi + # cminusfc compile to .s + bash -c "${project_dir}/build/cminusfc -S $case -o $asm_file" >>$LOG 2>&1 + check_return_value $? 0 "CE" "cminusfc compiler error" || continue + + # gcc compile asm to executable + loongarch64-unknown-linux-gnu-gcc -static \ + "$asm_file" "$io_dir"/io.c -o "$exe_file" \ + >>$LOG + check_return_value $? 0 "CE" "gcc compiler error" || continue + + # qemu run + if [ -e "$in_file" ]; then + exec_cmd="qemu-loongarch64 $exe_file >$out_file <$in_file" + else + exec_cmd="qemu-loongarch64 $exe_file >$out_file" + fi + bash -c "$exec_cmd" + ret=$? + # remove trailing null byte in the end line + sed -i "\$s/\x00*$//" "$out_file" + # append return value + echo $ret >>"$out_file" + + # compare output + diff --strip-trailing-cr "$std_out_file" "$out_file" -y >>$LOG + check_return_value $? 0 "WA" "output differ, check $std_out_file and $out_file" || continue + + # ok + printf "\033[1;32mOK\033[0m\n" +done diff --git a/tests/3-codegen/autogen/testcases/0-io.cminus b/tests/3-codegen/autogen/testcases/0-io.cminus new file mode 100644 index 0000000000000000000000000000000000000000..b73460e6f70228dfa1ce758f5b9182131c7d46dc --- /dev/null +++ b/tests/3-codegen/autogen/testcases/0-io.cminus @@ -0,0 +1,4 @@ +int main(void) { + output(input()); + return 0; +} diff --git a/tests/3-codegen/autogen/testcases/0-io.in b/tests/3-codegen/autogen/testcases/0-io.in new file mode 100644 index 0000000000000000000000000000000000000000..81c545efebe5f57d4cab2ba9ec294c4b0cadf672 --- /dev/null +++ b/tests/3-codegen/autogen/testcases/0-io.in @@ -0,0 +1 @@ +1234 diff --git a/tests/3-codegen/autogen/testcases/0-io.out b/tests/3-codegen/autogen/testcases/0-io.out new file mode 100644 index 0000000000000000000000000000000000000000..2b8eb81b54b5e42caf8d751595e576f6aebe7a42 --- /dev/null +++ b/tests/3-codegen/autogen/testcases/0-io.out @@ -0,0 +1,2 @@ +1234 +0 diff --git a/tests/3-codegen/autogen/testcases/1-return.cminus b/tests/3-codegen/autogen/testcases/1-return.cminus new file mode 100644 index 0000000000000000000000000000000000000000..91e77f24ebc661dcf7fb22883bb8ef52ccddae93 --- /dev/null +++ b/tests/3-codegen/autogen/testcases/1-return.cminus @@ -0,0 +1,4 @@ +int main(void) { + output(111); + return 111; +} diff --git a/tests/3-codegen/autogen/testcases/1-return.out b/tests/3-codegen/autogen/testcases/1-return.out new file mode 100644 index 0000000000000000000000000000000000000000..2bbe845f4ef76194eda16eaad3b846e7ba014516 --- /dev/null +++ b/tests/3-codegen/autogen/testcases/1-return.out @@ -0,0 +1,2 @@ +111 +111 diff --git a/tests/3-codegen/autogen/testcases/10-float.cminus b/tests/3-codegen/autogen/testcases/10-float.cminus new file mode 100644 index 0000000000000000000000000000000000000000..8de09f6119d7244a7df03187440e8469ef66dc96 --- /dev/null +++ b/tests/3-codegen/autogen/testcases/10-float.cminus @@ -0,0 +1,19 @@ +int main(void) { + float a; + float b; + float c; + + a = 1.1; + b = 1.5; + c = 1.2; + + outputFloat(a * b + c); + return 0; +} + +/* + 用 gcc 编译此文件生成汇编代码时,命令为 gcc -include io.h -S 10-float.c + 其中 io.h 位于 src/io/io.h, + + 也可以在本文件开头加上 void outputFloat(float x); +*/ diff --git a/tests/3-codegen/autogen/testcases/10-float.out b/tests/3-codegen/autogen/testcases/10-float.out new file mode 100644 index 0000000000000000000000000000000000000000..28c52e755c337283648fc20a7ade4ac29a98574f --- /dev/null +++ b/tests/3-codegen/autogen/testcases/10-float.out @@ -0,0 +1,2 @@ +2.850000 +0 diff --git a/tests/3-codegen/autogen/testcases/11-floatcall.cminus b/tests/3-codegen/autogen/testcases/11-floatcall.cminus new file mode 100644 index 0000000000000000000000000000000000000000..23f73d7efb499b59c207c6730c8d4f3e356b3c1c --- /dev/null +++ b/tests/3-codegen/autogen/testcases/11-floatcall.cminus @@ -0,0 +1,18 @@ +/* float function call */ + +float mod(float x, float y) { + int div; + div = x / y; + return x - div * y; +} + +int main(void) { + float a; + float b; + + a = 11.2; + b = 2.2; + + outputFloat(mod(a, b)); + return 0; +} diff --git a/tests/3-codegen/autogen/testcases/11-floatcall.out b/tests/3-codegen/autogen/testcases/11-floatcall.out new file mode 100644 index 0000000000000000000000000000000000000000..e1765193609cecdd1a26474b060effe9b0d36b69 --- /dev/null +++ b/tests/3-codegen/autogen/testcases/11-floatcall.out @@ -0,0 +1,2 @@ +0.200000 +0 diff --git a/tests/3-codegen/autogen/testcases/12-global.cminus b/tests/3-codegen/autogen/testcases/12-global.cminus new file mode 100644 index 0000000000000000000000000000000000000000..63bddbbd3feeca9e8abdedab92c3ef9bcf31b88f --- /dev/null +++ b/tests/3-codegen/autogen/testcases/12-global.cminus @@ -0,0 +1,47 @@ +int seed; + +int randomLCG(void) { + seed = seed * 1103515245 + 12345; + return seed; +} + +int randBin(void) { + if (randomLCG() > 0) + return 1; + else + return 0; +} + +/* random walk */ +int returnToZeroSteps(void) { + int x; + int steps; + + x = 0; + steps = 0; + + while (steps < 20) { + if (randBin()) + x = x + 1; + else + x = x - 1; + + steps = steps + 1; + if (x == 0) + return steps; + } + return 20; +} + +int main(void) { + int i; + i = 0; + + seed = 3407; + + while (i < 20) { + output(returnToZeroSteps()); + i = i + 1; + } + return 0; +} diff --git a/tests/3-codegen/autogen/testcases/12-global.out b/tests/3-codegen/autogen/testcases/12-global.out new file mode 100644 index 0000000000000000000000000000000000000000..66bb32318d81ec4cac480a518a337e5c7aa5c632 --- /dev/null +++ b/tests/3-codegen/autogen/testcases/12-global.out @@ -0,0 +1,21 @@ +4 +2 +2 +4 +8 +2 +2 +2 +2 +2 +6 +2 +10 +8 +4 +2 +20 +2 +2 +8 +0 diff --git a/tests/3-codegen/autogen/testcases/13-complex.cminus b/tests/3-codegen/autogen/testcases/13-complex.cminus new file mode 100644 index 0000000000000000000000000000000000000000..22232fb669dadf8765c62b62df913bbe657817c0 --- /dev/null +++ b/tests/3-codegen/autogen/testcases/13-complex.cminus @@ -0,0 +1,67 @@ +/* 01 背包问题 */ + +int n; +int m; + +int w[5]; +int v[5]; + +int dp[66]; /* dp[n * 11 + size] 表示前 n 个物品放入容量为 size 的背包中的最大价值,初始化为 -1 */ + +int max(int a, int b) { + if (a > b) + return a; + else + return b; +} + +/* 状态转移方程: + dp[n][size] = max(dp[n - 1][size], dp[n - 1][size - w[n]] + v[n]) + 边界条件: + dp[n][size <= 0] = 0 + dp[0][size] = 0 */ + +int knapsack(int n, int size) { + int result; + if (size <= 0) + return 0; + if (n == 0) + return 0; + if (dp[n * 11 + size] >= 0) + return dp[n * 11 + size]; + + if (size < w[n - 1]) + result = knapsack(n - 1, size); + else + result = max(knapsack(n - 1, size), knapsack(n - 1, size - w[n - 1]) + v[n - 1]); + + dp[n * 11 + size] = result; + return result; +} + +int main(void) { + int i; + i = 0; + + n = 5; + m = 10; + w[0] = 2; + w[1] = 2; + w[2] = 6; + w[3] = 5; + w[4] = 4; + + v[0] = 6; + v[1] = 3; + v[2] = 5; + v[3] = 4; + v[4] = 6; + + while (i < 66) { + dp[i] = 0 - 1; + i = i + 1; + } + + output(knapsack(n, m)); + return 0; +} diff --git a/tests/3-codegen/autogen/testcases/13-complex.out b/tests/3-codegen/autogen/testcases/13-complex.out new file mode 100644 index 0000000000000000000000000000000000000000..227eae2e84c4aa04d74e2afd977a8c52936dfaec --- /dev/null +++ b/tests/3-codegen/autogen/testcases/13-complex.out @@ -0,0 +1,2 @@ +15 +0 diff --git a/tests/3-codegen/autogen/testcases/2-calculate.cminus b/tests/3-codegen/autogen/testcases/2-calculate.cminus new file mode 100644 index 0000000000000000000000000000000000000000..fa4c9a1f341e58aff1d0f07e3f67ff26388c2415 --- /dev/null +++ b/tests/3-codegen/autogen/testcases/2-calculate.cminus @@ -0,0 +1,11 @@ +int main(void) { + int a; + int b; + int c; + + a = 23; + b = 25; + c = 4; + + return a + b * c; +} diff --git a/tests/3-codegen/autogen/testcases/2-calculate.out b/tests/3-codegen/autogen/testcases/2-calculate.out new file mode 100644 index 0000000000000000000000000000000000000000..190a18037c64c43e6b11489df4bf0b9eb6d2c9bf --- /dev/null +++ b/tests/3-codegen/autogen/testcases/2-calculate.out @@ -0,0 +1 @@ +123 diff --git a/tests/3-codegen/autogen/testcases/3-output.cminus b/tests/3-codegen/autogen/testcases/3-output.cminus new file mode 100644 index 0000000000000000000000000000000000000000..abe3222400d6ff8d1ac2e7e589011d97f2e23b06 --- /dev/null +++ b/tests/3-codegen/autogen/testcases/3-output.cminus @@ -0,0 +1,5 @@ +int main(void) { + output(11); + output(22222); + return 0; +} diff --git a/tests/3-codegen/autogen/testcases/3-output.out b/tests/3-codegen/autogen/testcases/3-output.out new file mode 100644 index 0000000000000000000000000000000000000000..1983173f37dfac419ee2c5b5997f62d240be0d65 --- /dev/null +++ b/tests/3-codegen/autogen/testcases/3-output.out @@ -0,0 +1,3 @@ +11 +22222 +0 diff --git a/tests/3-codegen/autogen/testcases/4-if.cminus b/tests/3-codegen/autogen/testcases/4-if.cminus new file mode 100644 index 0000000000000000000000000000000000000000..a4ba887f31161281363c4da0a69cc88a263de299 --- /dev/null +++ b/tests/3-codegen/autogen/testcases/4-if.cminus @@ -0,0 +1,23 @@ +int main(void) { + int a; + int b; + int c; + + a = 11; + b = 22; + c = 33; + + /* max value */ + if (a > b) { + if (a > c) + output(a); + else + output(c); + } else { + if (c < b) + output(b); + else + output(c); + } + return 0; +} diff --git a/tests/3-codegen/autogen/testcases/4-if.out b/tests/3-codegen/autogen/testcases/4-if.out new file mode 100644 index 0000000000000000000000000000000000000000..54a647cf204067321a9819d900b92ee655f99428 --- /dev/null +++ b/tests/3-codegen/autogen/testcases/4-if.out @@ -0,0 +1,2 @@ +33 +0 diff --git a/tests/3-codegen/autogen/testcases/5-while.cminus b/tests/3-codegen/autogen/testcases/5-while.cminus new file mode 100644 index 0000000000000000000000000000000000000000..da3313b91c0c519a1af8c0aa98e7127fe400436c --- /dev/null +++ b/tests/3-codegen/autogen/testcases/5-while.cminus @@ -0,0 +1,14 @@ +int main(void) { + int n; + int i; + + n = 10; + i = 0; + + while (i < n) { + output(i); + i = i + 1; + } + + return 0; +} diff --git a/tests/3-codegen/autogen/testcases/5-while.out b/tests/3-codegen/autogen/testcases/5-while.out new file mode 100644 index 0000000000000000000000000000000000000000..c9f2be1a9611927baea84bbe3b819b5a7a328401 --- /dev/null +++ b/tests/3-codegen/autogen/testcases/5-while.out @@ -0,0 +1,11 @@ +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +0 diff --git a/tests/3-codegen/autogen/testcases/6-array.cminus b/tests/3-codegen/autogen/testcases/6-array.cminus new file mode 100644 index 0000000000000000000000000000000000000000..3383fcafa1c07a12cf3d3780fc4509e781ef0022 --- /dev/null +++ b/tests/3-codegen/autogen/testcases/6-array.cminus @@ -0,0 +1,15 @@ +int main(void) { + int a[10]; + int i; + + i = 0; + a[0] = 11; + a[4] = 22; + a[9] = 33; + + output(a[0]); + output(a[4]); + output(a[9]); + + return 0; +} diff --git a/tests/3-codegen/autogen/testcases/6-array.out b/tests/3-codegen/autogen/testcases/6-array.out new file mode 100644 index 0000000000000000000000000000000000000000..d7fcd8c808df07b274ae64b8754e1617b37003aa --- /dev/null +++ b/tests/3-codegen/autogen/testcases/6-array.out @@ -0,0 +1,4 @@ +11 +22 +33 +0 diff --git a/tests/3-codegen/autogen/testcases/7-function.cminus b/tests/3-codegen/autogen/testcases/7-function.cminus new file mode 100644 index 0000000000000000000000000000000000000000..2eb2620d1110b06d1f07ab51fbff8343e41b510c --- /dev/null +++ b/tests/3-codegen/autogen/testcases/7-function.cminus @@ -0,0 +1,21 @@ +int min(int a, int b) { + if (a <= b) + return a; + else + return b; +} + +int main(void) { + int a; + int b; + int c; + + a = 11; + b = 22; + c = 33; + + output(min(a, b)); + output(min(b, c)); + output(min(c, a)); + return 0; +} diff --git a/tests/3-codegen/autogen/testcases/7-function.out b/tests/3-codegen/autogen/testcases/7-function.out new file mode 100644 index 0000000000000000000000000000000000000000..38ea32361a25780c6da08b24aead9a02d32c3f0c --- /dev/null +++ b/tests/3-codegen/autogen/testcases/7-function.out @@ -0,0 +1,4 @@ +11 +22 +11 +0 diff --git a/tests/3-codegen/autogen/testcases/8-store.cminus b/tests/3-codegen/autogen/testcases/8-store.cminus new file mode 100644 index 0000000000000000000000000000000000000000..15a438d24d427ad15ce892d4ce25102e6154113f --- /dev/null +++ b/tests/3-codegen/autogen/testcases/8-store.cminus @@ -0,0 +1,26 @@ +int store(int arr[], int index, int value) { + arr[index] = value; + return value; +} + +int main(void) { + int a[10]; + int i; + int sum; + + i = 0; + while (i < 10) { + store(a, i, i * 2); + i = i + 1; + } + + sum = 0; + i = 0; + while (i < 10) { + sum = sum + a[i]; + i = i + 1; + } + + output(sum); + return 0; +} diff --git a/tests/3-codegen/autogen/testcases/8-store.out b/tests/3-codegen/autogen/testcases/8-store.out new file mode 100644 index 0000000000000000000000000000000000000000..d2044a0e5daa8e8d2ed3a54a15127b6c919eb4f4 --- /dev/null +++ b/tests/3-codegen/autogen/testcases/8-store.out @@ -0,0 +1,2 @@ +90 +0 diff --git a/tests/3-codegen/autogen/testcases/9-fibonacci.cminus b/tests/3-codegen/autogen/testcases/9-fibonacci.cminus new file mode 100644 index 0000000000000000000000000000000000000000..df0ee724c115a1339d59ae260be5519ea3b41c14 --- /dev/null +++ b/tests/3-codegen/autogen/testcases/9-fibonacci.cminus @@ -0,0 +1,23 @@ +int fibonacci(int n) { + if (n == 0) + return 0; + else if (n == 1) + return 1; + else + return fibonacci(n - 1) + fibonacci(n - 2); +} + +int main(void) { + int n; + int i; + + n = 10; + i = 0; + + while (i < n) { + output(fibonacci(i)); + i = i + 1; + } + + return 0; +} diff --git a/tests/3-codegen/autogen/testcases/9-fibonacci.out b/tests/3-codegen/autogen/testcases/9-fibonacci.out new file mode 100644 index 0000000000000000000000000000000000000000..f53d098dcdc78d4553b72ce722b2d7e0b055435e --- /dev/null +++ b/tests/3-codegen/autogen/testcases/9-fibonacci.out @@ -0,0 +1,11 @@ +0 +1 +1 +2 +3 +5 +8 +13 +21 +34 +0 diff --git a/tests/3-codegen/warmup/CMakeLists.txt b/tests/3-codegen/warmup/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..2ab782239a763ebf0a35f0bd740adb78b7825ae5 --- /dev/null +++ b/tests/3-codegen/warmup/CMakeLists.txt @@ -0,0 +1,59 @@ +add_executable( + stu_assign_codegen + stu_cpp/assign_codegen.cpp +) +target_link_libraries( + stu_assign_codegen + IR_lib + codegen +) + +add_executable( + stu_function_codegen + stu_cpp/function_codegen.cpp +) +target_link_libraries( + stu_function_codegen + IR_lib + codegen +) + +add_executable( + stu_icmp_codegen + stu_cpp/icmp_codegen.cpp +) +target_link_libraries( + stu_icmp_codegen + IR_lib + codegen +) + +add_executable( + stu_fcmp_codegen + stu_cpp/fcmp_codegen.cpp +) +target_link_libraries( + stu_fcmp_codegen + IR_lib + codegen +) + +add_executable( + stu_float_codegen + stu_cpp/float_codegen.cpp +) +target_link_libraries( + stu_float_codegen + IR_lib + codegen +) + +add_executable( + stu_global_codegen + stu_cpp/global_codegen.cpp +) +target_link_libraries( + stu_global_codegen + IR_lib + codegen +) diff --git a/tests/3-codegen/warmup/ll_cases/assign.ll b/tests/3-codegen/warmup/ll_cases/assign.ll new file mode 100644 index 0000000000000000000000000000000000000000..9dbfaf3c3b30c3dbebddfb2a835e926abadca28e --- /dev/null +++ b/tests/3-codegen/warmup/ll_cases/assign.ll @@ -0,0 +1,12 @@ +define i32 @main() { +label_entry: + %op0 = alloca [10 x i32] + %op1 = getelementptr [10 x i32], [10 x i32]* %op0, i32 0, i32 0 + store i32 10, i32* %op1 + %op2 = getelementptr [10 x i32], [10 x i32]* %op0, i32 0, i32 1 + %op3 = load i32, i32* %op1 + %op4 = mul i32 %op3, 3 + store i32 %op4, i32* %op2 + %op5 = load i32, i32* %op2 + ret i32 %op5 +} diff --git a/tests/3-codegen/warmup/ll_cases/fcmp.ll b/tests/3-codegen/warmup/ll_cases/fcmp.ll new file mode 100644 index 0000000000000000000000000000000000000000..64fb24a7fdf84aab4f6307bf62fbd7a0fe153d61 --- /dev/null +++ b/tests/3-codegen/warmup/ll_cases/fcmp.ll @@ -0,0 +1,12 @@ +define i32 @main() { +label_entry: + ; 5.5 (0x40b00000) > 1.0 (0x3f800000) + %op0 = fcmp ugt float 0x4016000000000000, 0x3ff0000000000000 + %op1 = zext i1 %op0 to i32 + %op2 = icmp ne i32 %op1, 0 + br i1 %op2, label %label3, label %label4 +label3: ; preds = %label_entry + ret i32 233 +label4: ; preds = %label_entry + ret i32 0 +} diff --git a/tests/3-codegen/warmup/ll_cases/float.ll b/tests/3-codegen/warmup/ll_cases/float.ll new file mode 100644 index 0000000000000000000000000000000000000000..edd0e6b445a6c4c5fcd919f9b953dcb972ecbb3e --- /dev/null +++ b/tests/3-codegen/warmup/ll_cases/float.ll @@ -0,0 +1,8 @@ +define i32 @main() { +label_entry: + %op0 = alloca float + store float 0x40091eb860000000, float* %op0 ; 3.14, FP32 0x4048f5c3 + %op1 = load float, float* %op0 + %op2 = fptosi float %op1 to i32 + ret i32 %op2 +} diff --git a/tests/3-codegen/warmup/ll_cases/function.ll b/tests/3-codegen/warmup/ll_cases/function.ll new file mode 100644 index 0000000000000000000000000000000000000000..7a4362c671e5d4738f90b478f83ad7b3055c4bc6 --- /dev/null +++ b/tests/3-codegen/warmup/ll_cases/function.ll @@ -0,0 +1,14 @@ +define i32 @callee(i32 %arg0) { +label_entry: + %op1 = alloca i32 + store i32 %arg0, i32* %op1 + %op2 = load i32, i32* %op1 + %op3 = mul i32 3, %op2 + ret i32 %op3 +} + +define i32 @main() { +label_entry: + %op0 = call i32 @callee(i32 110) + ret i32 %op0 +} diff --git a/tests/3-codegen/warmup/ll_cases/global.ll b/tests/3-codegen/warmup/ll_cases/global.ll new file mode 100644 index 0000000000000000000000000000000000000000..24a15ad9b2dcada9ca345390d0abeb0b65be904f --- /dev/null +++ b/tests/3-codegen/warmup/ll_cases/global.ll @@ -0,0 +1,8 @@ +@a = global i32 zeroinitializer + +define i32 @main() { +label_entry: + store i32 10, i32* @a + %op0 = load i32, i32* @a + ret i32 %op0 +} diff --git a/tests/3-codegen/warmup/ll_cases/icmp.ll b/tests/3-codegen/warmup/ll_cases/icmp.ll new file mode 100644 index 0000000000000000000000000000000000000000..02dc2c2e7c00d443d3fa47516ee301c15e4a4ce5 --- /dev/null +++ b/tests/3-codegen/warmup/ll_cases/icmp.ll @@ -0,0 +1,11 @@ +define i32 @main() { +label_entry: + %op0 = icmp sgt i32 5, 1 + %op1 = zext i1 %op0 to i32 + %op2 = icmp ne i32 %op1, 0 + br i1 %op2, label %label3, label %label4 +label3: ; preds = %label_entry + ret i32 233 +label4: ; preds = %label_entry + ret i32 0 +} diff --git a/tests/3-codegen/warmup/stu_cpp/assign_codegen.cpp b/tests/3-codegen/warmup/stu_cpp/assign_codegen.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c61ceefdea971fbf7b099d3f8aa6d7bc55142640 --- /dev/null +++ b/tests/3-codegen/warmup/stu_cpp/assign_codegen.cpp @@ -0,0 +1,150 @@ +#include "ASMInstruction.hpp" +#include "CodeGen.hpp" +#include "Module.hpp" + +#include +#include +#include + +void translate_main(CodeGen *codegen); // 将 main 函数翻译为汇编代码 + +int main() { + auto *module = new Module(); + auto *codegen = new CodeGen(module); + + // 告诉汇编器将汇编放到代码段 + codegen->append_inst(".text", ASMInstruction::Atrribute); + + translate_main(codegen); + + std::cout << codegen->print(); + delete codegen; + delete module; + return 0; +} + +// TODO: 按照提示补全 +void translate_main(CodeGen *codegen) { + std::unordered_map offset_map; + + /* 声明 main 函数 */ + codegen->append_inst(".globl main", ASMInstruction::Atrribute); + codegen->append_inst(".type main, @function", ASMInstruction::Atrribute); + + /* main 函数开始 */ + codegen->append_inst("main", ASMInstruction::Label); // main 函数标签 + + /* main 函数的 Prologue (序言) */ + // 保存返回地址 + codegen->append_inst("st.d $ra, $sp, -8"); + // 保存老的 fp + codegen->append_inst("st.d $fp, $sp, -16"); + // 设置新的 fp + codegen->append_inst("addi.d $fp, $sp, 0"); + // 为栈帧分配空间. 思考: 为什么是 96 字节? + codegen->append_inst("addi.d $sp, $sp, -96"); + + /* main 函数的 label_entry */ + codegen->append_inst(".main_label_entry", ASMInstruction::Label); + + /* %op0 = alloca [10 x i32] */ + // 在汇编中写入注释, 方便 debug + codegen->append_inst("%op0 = alloca [10 x i32]", ASMInstruction::Comment); + // 将数组的地址写入 %op0 对应的内存空间中 + // 首先计算数组的地址对应的偏移量, 按照我们在栈式分配中介绍的规则, 数组的空 + // 间紧挨着 %op0 的空间, 数组的地址为这段空间的最小值. + // 然后将数组的地址写入 %op0 对应的内存空间中. + // 你需要思考: + // - %op0 的大小是多少字节? + // - %op0 的偏移量是多少字节? + // - 数组的大小是多少字节? + // - 数组的偏移量是多少字节? + offset_map["%op0"] = ; // TODO: 请填空 + offset_map["array"] = ; // TODO: 请填空 + codegen->append_inst("addi.d", + {"$t0", "$fp", std::to_string(offset_map["array"])}); + codegen->append_inst("st.d", + {"$t0", "$fp", std::to_string(offset_map["%op0"])}); + + /* %op1 = getelementptr [10 x i32], [10 x i32]* %op0, i32 0, i32 0 */ + codegen->append_inst( + "%op1 = getelementptr [10 x i32], [10 x i32]* %op0, i32 0, i32 0", + ASMInstruction::Comment); + // 将 gep 的值写入 %op1 对应的内存空间中 + // 你可以手动计算 gep 的值, 或者使用指令计算 gep 的值 + // 你需要思考 %op1 的偏移量是多少字节 + offset_map["%op1"] = ; // TODO: 请填空 + // 获得数组的地址, 将其写入 $t0 中 + codegen->append_inst("ld.d", + {"$t0", "$fp", std::to_string(offset_map["%op0"])}); + // TODO: 计算 %op1 的值, 并将其写入 %op1 对应的内存空间中 + codegen->append_inst(""); + + /* store i32 10, i32* %op1 */ + codegen->append_inst("store i32 10, i32* %op1", ASMInstruction::Comment); + // 将 10 写入数组 (%op1 指向的空间) 中, 需要先获得 %op1 的值 + codegen->append_inst("ld.d", + {"$t0", "$fp", std::to_string(offset_map["%op1"])}); + codegen->append_inst("addi.w $t1, $zero, 10"); + codegen->append_inst("st.w $t1, $t0, 0"); + + /* %op2 = getelementptr [10 x i32], [10 x i32]* %op0, i32 0, i32 1 */ + codegen->append_inst( + "%op2 = getelementptr [10 x i32], [10 x i32]* %op0, i32 0, i32 1", + ASMInstruction::Comment); + // 将 gep 的值写入 %op2 对应的内存空间中 + // 你可以手动计算 gep 的值, 或者使用指令计算 gep 的值 + // 你需要思考 %op2 的偏移量是多少字节 + offset_map["%op2"] = ; // TODO: 请填空 + // 获得数组的地址, 将其写入 $t0 中 + codegen->append_inst("ld.d", + {"$t0", "$fp", std::to_string(offset_map["%op0"])}); + // TODO: 计算 gep 的值, 并将其写入 %op2 对应的内存空间中 + codegen->append_inst(""); + + /* %op3 = load i32, i32* %op1 */ + codegen->append_inst("%op3 = load i32, i32* %op1", ASMInstruction::Comment); + // 将 %op1 指向的空间中存储的值写入 %op3 对应的内存空间中 + offset_map["%op3"] = ; // TODO: 请填空 + // TODO: 先获得 %op1 的值, 然后获得 %op1 指向的空间的值, 最后将这个值写入 + // %op3 对应的内存空间中 + codegen->append_inst(""); + + /* %op4 = mul i32 %op3, 3 */ + codegen->append_inst("%op4 = mul i32 %op3, 3", ASMInstruction::Comment); + offset_map["%op4"] = ; // TODO: 请填空 + // TODO: 先获得 %op3 的值, 然后将其乘以 3, 最后将结果写入 %op4 对应的内存空 + // 间中 + codegen->append_inst(""); + + /* store i32 %op4, i32* %op2 */ + codegen->append_inst("store i32 %op4, i32* %op2", ASMInstruction::Comment); + // 将 %op4 的值写入 %op2 指向的空间中 + // TODO: 先获得 %op4 的值, 然后将其写入 %op2 指向的空间中 + codegen->append_inst(""); + + /* %op5 = load i32, i32* %op2 */ + // 将 %op2 指向的空间中存储的值写入 %op5 对应的内存空间中 + offset_map["%op5"] = ; // TODO: 请填空 + // TODO: 先获得 %op2 的值, 然后获得 %op2 指向的空间的值, 最后将这个值写入 + // %op5 对应的内存空间中 + codegen->append_inst(""); + + /* ret i32 %op5 */ + codegen->append_inst("ret i32 %op5", ASMInstruction::Comment); + // TODO: 将 %op5 的值写入 $a0 中 + codegen->append_inst(""); + // 思考: 为什么不在这里 jr $ra, 而是跳转到 main_exit? + codegen->append_inst("b main_exit"); + + /* main 函数的 Epilogue (收尾) */ + codegen->append_inst("main_exit", ASMInstruction::Label); + // 释放栈帧空间 + codegen->append_inst("addi.d $sp, $sp, 96"); + // 恢复 ra + codegen->append_inst("ld.d $ra, $sp, -8"); + // 恢复 fp + codegen->append_inst("ld.d $fp, $sp, -16"); + // 返回 + codegen->append_inst("jr $ra"); +} diff --git a/tests/3-codegen/warmup/stu_cpp/fcmp_codegen.cpp b/tests/3-codegen/warmup/stu_cpp/fcmp_codegen.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6ee2e08af1cb3f988525aaec48206ddd868fa40f --- /dev/null +++ b/tests/3-codegen/warmup/stu_cpp/fcmp_codegen.cpp @@ -0,0 +1,118 @@ +#include "ASMInstruction.hpp" +#include "CodeGen.hpp" +#include "Module.hpp" + +#include +#include +#include + +void translate_main(CodeGen *codegen); // 将 main 函数翻译为汇编代码 + +int main() { + auto *module = new Module(); + auto *codegen = new CodeGen(module); + + // 告诉汇编器将汇编放到代码段 + codegen->append_inst(".text", ASMInstruction::Atrribute); + + translate_main(codegen); + + std::cout << codegen->print(); + delete codegen; + delete module; + return 0; +} + +// TODO: 按照提示补全 +void translate_main(CodeGen *codegen) { + std::unordered_map offset_map; + + /* 声明 main 函数 */ + codegen->append_inst(".globl main", ASMInstruction::Atrribute); + codegen->append_inst(".type main, @function", ASMInstruction::Atrribute); + + /* main 函数开始 */ + codegen->append_inst("main", ASMInstruction::Label); // main 函数标签 + + /* main 函数的 Prologue (序言) */ + // 保存返回地址 + codegen->append_inst("st.d $ra, $sp, -8"); + // 保存老的 fp + codegen->append_inst("st.d $fp, $sp, -16"); + // 设置新的 fp + codegen->append_inst("addi.d $fp, $sp, 0"); + // 为栈帧分配空间. 思考: 为什么是 32 字节? + codegen->append_inst("addi.d $sp, $sp, -32"); + + /* main 函数的 label_entry */ + codegen->append_inst(".main_label_entry", ASMInstruction::Label); + + /* %op0 = fcmp ugt float 0x4016000000000000, 0x3ff0000000000000 */ + // 在汇编中写入注释, 方便 debug + codegen->append_inst( + "%op0 = fcmp ugt float 0x4016000000000000, 0x3ff0000000000000", + ASMInstruction::Comment); + // 将比较结果写入 %op0 对应的内存空间中 + offset_map["%op0"] = ; // TODO: 请填空 + // TODO: 将 5.5 (0x40b00000) 加载到浮点寄存器中 + codegen->append_inst(""); + // TODO: 将 1.0 (0x3f800000) 加载到浮点寄存器中 + codegen->append_inst(""); + // TODO: 使用 fcmp.slt.s 进行比较, 比较结果在浮点标志寄存器中, 你需要思考 + // 如何将浮点标志寄存器中的值写入内存. 提示: 尝试使用 bcnez 指令 + codegen->append_inst(""); + + /* %op1 = zext i1 %op0 to i32 */ + codegen->append_inst("%op1 = zext i1 %op0 to i32", ASMInstruction::Comment); + // 将 %op0 的值从 i1 类型转换为 i32 类型, 并将结果写入到 %op1 对应的内存空 + // 间中 + offset_map["%op1"] = ; // TODO: 请填空 + // TODO: 获得 %op0 的值, 然后进行转换, 最后将结果写入 %op1 + // 思考: 怎么转换? 需不需要显式地使用某些指令转换? + codegen->append_inst(""); + + /* %op2 = icmp ne i32 %op1, 0 */ + codegen->append_inst("%op2 = icmp ne i32 %op1, 0", ASMInstruction::Comment); + // 比较 %op1 和 0, 并将结果写入 %op2 对应的内存空间中 + offset_map["%op2"] = ; // TODO: 请填空 + // TODO: 获得 %op1 的值, 然后进行比较, 最后将结果写入 %op2 + // 思考: 如何比较? 能否不使用跳转指令计算结果? + // 提示: 尝试使用 xor/xori 和 slt/sltu/slti/sltui 计算比较结果 + codegen->append_inst(""); + + /* br i1 %op2, label %label3, label %label4 */ + codegen->append_inst("br i1 %op2, label %label3, label %label4", + ASMInstruction::Comment); + // TODO: 获得 %op2 的值, 并根据 %op2 的值跳转到 label3 或者 label4 + // 提示: 汇编中对应的标签分别为 .main_label3 和 .main_label4 + codegen->append_inst(""); + + /* label3: */ + codegen->append_inst(".main_label3", ASMInstruction::Label); + + /* ret i32 233 */ + codegen->append_inst("ret i32 233", ASMInstruction::Comment); + // 将 233 写入 $a0 中 + codegen->append_inst("addi.w $a0, $zero, 233"); + codegen->append_inst("b main_exit"); + + /* label4: */ + codegen->append_inst(".main_label4", ASMInstruction::Label); + + /* ret i32 0 */ + codegen->append_inst("ret i32 0", ASMInstruction::Comment); + // 将 0 写入 $a0 中 + codegen->append_inst("addi.w $a0, $zero, 0"); + codegen->append_inst("b main_exit"); + + /* main 函数的 Epilogue (收尾) */ + codegen->append_inst("main_exit", ASMInstruction::Label); + // 释放栈帧空间 + codegen->append_inst("addi.d $sp, $sp, 32"); + // 恢复 ra + codegen->append_inst("ld.d $ra, $sp, -8"); + // 恢复 fp + codegen->append_inst("ld.d $fp, $sp, -16"); + // 返回 + codegen->append_inst("jr $ra"); +} diff --git a/tests/3-codegen/warmup/stu_cpp/float_codegen.cpp b/tests/3-codegen/warmup/stu_cpp/float_codegen.cpp new file mode 100644 index 0000000000000000000000000000000000000000..71e11366224d6f50bfef6b33fc0d5880815647d3 --- /dev/null +++ b/tests/3-codegen/warmup/stu_cpp/float_codegen.cpp @@ -0,0 +1,104 @@ +#include "ASMInstruction.hpp" +#include "CodeGen.hpp" +#include "Module.hpp" + +#include +#include +#include + +void translate_main(CodeGen *codegen); // 将 main 函数翻译为汇编代码 + +int main() { + auto *module = new Module(); + auto *codegen = new CodeGen(module); + + // 告诉汇编器将汇编放到代码段 + codegen->append_inst(".text", ASMInstruction::Atrribute); + + translate_main(codegen); + + std::cout << codegen->print(); + delete codegen; + delete module; + return 0; +} + +// TODO: 按照提示补全 +void translate_main(CodeGen *codegen) { + std::unordered_map offset_map; + + /* 声明 main 函数 */ + codegen->append_inst(".globl main", ASMInstruction::Atrribute); + codegen->append_inst(".type main, @function", ASMInstruction::Atrribute); + + /* main 函数开始 */ + codegen->append_inst("main", ASMInstruction::Label); // main 函数标签 + + /* main 函数的 Prologue (序言) */ + // 保存返回地址 + codegen->append_inst("st.d $ra, $sp, -8"); + // 保存老的 fp + codegen->append_inst("st.d $fp, $sp, -16"); + // 设置新的 fp + codegen->append_inst("addi.d $fp, $sp, 0"); + // 为栈帧分配空间. 思考: 为什么是 48 字节? + codegen->append_inst("addi.d $sp, $sp, -48"); + + /* main 函数的 label_entry */ + codegen->append_inst(".main_label_entry", ASMInstruction::Label); + + /* %op0 = alloca float */ + // 在汇编中写入注释, 方便 debug + codegen->append_inst("%op0 = alloca float", ASMInstruction::Comment); + // 将浮点数的地址写入 %op0 对应的内存空间中 + offset_map["%op0"] = ; // TODO: 请填空 + offset_map["*%op0"] = ; // TODO: 请填空 + codegen->append_inst("addi.d", + {"$t0", "$fp", std::to_string(offset_map["*%op0"])}); + codegen->append_inst("st.d", + {"$t0", "$fp", std::to_string(offset_map["%op0"])}); + + /* store float 0x40091eb860000000, float* %op0 */ + codegen->append_inst("store float 0x40091eb860000000, float* %op0", + ASMInstruction::Comment); + // 将 3.14 (0x4048f5c3) 写入 %op0 指向的内存空间中 + // 获得 %op0 的值 + codegen->append_inst("ld.d", + {"$t0", "$fp", std::to_string(offset_map["%op0"])}); + // TODO: 将 0x4048f5c3 加载到通用寄存器或者浮点寄存器中 + codegen->append_inst(""); + // TODO: 将通用寄存器或者浮点寄存器中的值写入 %op0 对应的内存空间中 + codegen->append_inst(""); + + /* %op1 = load float, float* %op0 */ + codegen->append_inst("%op1 = load float, float* %op0", + ASMInstruction::Comment); + // TODO: 先获得 %op0 的值, 然后获得 %op0 指向的空间的值, 最后将这个值写入 + // %op1 对应的内存空间中 + offset_map["%op1"] = ; // TODO: 请填空 + codegen->append_inst(""); + + /* %op2 = fptosi float %op1 to i32 */ + codegen->append_inst("%op2 = fptosi float %op1 to i32", + ASMInstruction::Comment); + // TODO: 使用 ftintrz.w.s 指令进行转换, 并将结果写入 %op2 对应的内存空间中 + offset_map["%op2"] = ; // TODO: 请填空 + codegen->append_inst(""); + + /* ret i32 %op2 */ + codegen->append_inst("ret i32 %op2", ASMInstruction::Comment); + // TODO: 将 %op2 的值写入 $a0 中 + codegen->append_inst(""); + codegen->append_inst("b main_exit"); + + /* main 函数的 Epilogue (收尾) */ + codegen->append_inst("main_exit", ASMInstruction::Label); + // 释放栈帧空间 + codegen->append_inst("addi.d $sp, $sp, 48"); + // 恢复 ra + codegen->append_inst("ld.d $ra, $sp, -8"); + // 恢复 fp + codegen->append_inst("ld.d $fp, $sp, -16"); + // 返回 + codegen->append_inst("jr $ra"); +} diff --git a/tests/3-codegen/warmup/stu_cpp/function_codegen.cpp b/tests/3-codegen/warmup/stu_cpp/function_codegen.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dac5466b1b43ebd472c502386e1e82fbd8a14c7e --- /dev/null +++ b/tests/3-codegen/warmup/stu_cpp/function_codegen.cpp @@ -0,0 +1,170 @@ +#include "ASMInstruction.hpp" +#include "CodeGen.hpp" +#include "Module.hpp" + +#include +#include +#include + +void translate_main(CodeGen *codegen); // 将 main 函数翻译为汇编代码 +void translate_callee(CodeGen *codegen); // 将 callee 函数翻译为汇编代码 + +int main() { + auto *module = new Module(); + auto *codegen = new CodeGen(module); + + // 告诉汇编器将汇编放到代码段 + codegen->append_inst(".text", ASMInstruction::Atrribute); + + translate_callee(codegen); + translate_main(codegen); + + std::cout << codegen->print(); + delete codegen; + delete module; + return 0; +} + +// TODO: 按照提示补全 +void translate_callee(CodeGen *codegen) { + std::unordered_map offset_map; + + /* 声明 callee 函数 */ + codegen->append_inst(".globl callee", ASMInstruction::Atrribute); + codegen->append_inst(".type callee, @function", ASMInstruction::Atrribute); + + /* callee 函数开始 */ + codegen->append_inst("callee", ASMInstruction::Label); // main 函数标签 + + /* callee 函数的 Prologue (序言) */ + // 保存返回地址 + codegen->append_inst("st.d $ra, $sp, -8"); + // 保存老的 fp + codegen->append_inst("st.d $fp, $sp, -16"); + // 设置新的 fp + codegen->append_inst("addi.d $fp, $sp, 0"); + // 为栈帧分配空间. 思考: 为什么是 48 字节? + codegen->append_inst("addi.d $sp, $sp, -48"); + + // 为参数分配空间 + offset_map["%arg0"] = ; // TODO: 请填空 + codegen->append_inst("st.w", + {"$a0", "$fp", std::to_string(offset_map["%arg0"])}); + + /* callee 函数的 label_entry */ + codegen->append_inst(".callee_label_entry", ASMInstruction::Label); + + /* %op1 = alloca i32 */ + // 在汇编中写入注释, 方便 debug + codegen->append_inst("%op1 = alloca i32", ASMInstruction::Comment); + // 将 alloca 的地址写入 %op1 对应的内存空间中 + offset_map["%op1"] = ; // TODO: 请填空 + offset_map["*%op1"] = ; // TODO: 请填空 + codegen->append_inst("addi.d", + {"$t0", "$fp", std::to_string(offset_map["*%op1"])}); + codegen->append_inst("st.d", + {"$t0", "$fp", std::to_string(offset_map["%op1"])}); + + /* store i32 %arg0, i32* %op1 */ + codegen->append_inst("store i32 %arg0, i32* %op1", ASMInstruction::Comment); + // 将 %arg0 的值写入 %op1 对应的内存空间中 + codegen->append_inst("ld.d", + {"$t0", "$fp", std::to_string(offset_map["%op1"])}); + codegen->append_inst("ld.w", + {"$t1", "$fp", std::to_string(offset_map["%arg0"])}); + codegen->append_inst("st.w $t1, $t0, 0"); + + /* %op2 = load i32, i32* %op1 */ + codegen->append_inst("%op2 = load i32, i32* %op1", ASMInstruction::Comment); + // 将 %op1 对应的内存空间的值写入 %op2 对应的内存空间中 + offset_map["%op2"] = ; // TODO: 请填空 + codegen->append_inst("ld.d", + {"$t0", "$fp", std::to_string(offset_map["%op1"])}); + codegen->append_inst("ld.w $t1, $t0, 0"); + codegen->append_inst("st.w", + {"$t1", "$fp", std::to_string(offset_map["%op2"])}); + + /* %op3 = mul i32 3, %op2 */ + codegen->append_inst("%op3 = mul i32 3, %op2", ASMInstruction::Comment); + // 将 %op2 的值乘以 3, 并将结果写入 %op3 对应的内存空间中 + offset_map["%op3"] = ; // TODO: 请填空 + codegen->append_inst("ld.w", + {"$t0", "$fp", std::to_string(offset_map["%op2"])}); + codegen->append_inst("addi.w $t1, $zero, 3"); + codegen->append_inst("mul.w $t0, $t0, $t1"); + codegen->append_inst("st.w", + {"$t0", "$fp", std::to_string(offset_map["%op3"])}); + + /* ret i32 %op3 */ + codegen->append_inst("ret i32 %op3", ASMInstruction::Comment); + // 将 %op3 的值写入 $a0 中 + codegen->append_inst("ld.w", + {"$a0", "$fp", std::to_string(offset_map["%op3"])}); + codegen->append_inst("b callee_exit"); + + /* callee 函数的 Epilogue (收尾) */ + codegen->append_inst("callee_exit", ASMInstruction::Label); + // 释放栈帧空间 + codegen->append_inst("addi.d $sp, $sp, 48"); + // 恢复 ra + codegen->append_inst("ld.d $ra, $sp, -8"); + // 恢复 fp + codegen->append_inst("ld.d $fp, $sp, -16"); + // 返回 + codegen->append_inst("jr $ra"); +} + +// TODO: 按照提示补全 +void translate_main(CodeGen *codegen) { + std::unordered_map offset_map; + + /* 声明 main 函数 */ + codegen->append_inst(".globl main", ASMInstruction::Atrribute); + codegen->append_inst(".type main, @function", ASMInstruction::Atrribute); + + /* main 函数开始 */ + codegen->append_inst("main", ASMInstruction::Label); // main 函数标签 + + /* main 函数的 Prologue (序言) */ + // 保存返回地址 + codegen->append_inst("st.d $ra, $sp, -8"); + // 保存老的 fp + codegen->append_inst("st.d $fp, $sp, -16"); + // 设置新的 fp + codegen->append_inst("addi.d $fp, $sp, 0"); + // 为栈帧分配空间. 思考: 为什么是 32 字节? + codegen->append_inst("addi.d $sp, $sp, -32"); + + /* main 函数的 label_entry */ + codegen->append_inst(".main_label_entry", ASMInstruction::Label); + + /* %op0 = call i32 @callee(i32 110) */ + // 在汇编中写入注释, 方便 debug + codegen->append_inst("%op0 = call i32 @callee(i32 110)", + ASMInstruction::Comment); + offset_map["%op0"] = ; // TODO: 请填空 + // TODO: 将参数写入参数寄存器 + codegen->append_inst(""); + // TODO: 调用 callee 函数 + codegen->append_inst(""); + // 将返回值写入 %op0 对应的内存空间中 + codegen->append_inst("st.w", + {"$a0", "$fp", std::to_string(offset_map["%op0"])}); + + /* ret i32 %op0 */ + codegen->append_inst("ret i32 %op0", ASMInstruction::Comment); + codegen->append_inst("ld.w", + {"$a0", "$fp", std::to_string(offset_map["%op0"])}); + codegen->append_inst("b main_exit"); + + /* main 函数的 Epilogue (收尾) */ + codegen->append_inst("main_exit", ASMInstruction::Label); + // 释放栈帧空间 + codegen->append_inst("addi.d $sp, $sp, 32"); + // 恢复 ra + codegen->append_inst("ld.d $ra, $sp, -8"); + // 恢复 fp + codegen->append_inst("ld.d $fp, $sp, -16"); + // 返回 + codegen->append_inst("jr $ra"); +} diff --git a/tests/3-codegen/warmup/stu_cpp/global_codegen.cpp b/tests/3-codegen/warmup/stu_cpp/global_codegen.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fb1c787c12e6321dade5bbd52745cf5a023f2d7b --- /dev/null +++ b/tests/3-codegen/warmup/stu_cpp/global_codegen.cpp @@ -0,0 +1,108 @@ +#include "ASMInstruction.hpp" +#include "CodeGen.hpp" +#include "Module.hpp" + +#include +#include +#include + +void declare_global(CodeGen *codegen); // 声明全局变量 a +void translate_main(CodeGen *codegen); // 将 main 函数翻译为汇编代码 + +int main() { + auto *module = new Module(); + auto *codegen = new CodeGen(module); + + // 告诉汇编器将汇编放到代码段 + codegen->append_inst(".text", ASMInstruction::Atrribute); + + declare_global(codegen); + + codegen->append_inst(".text", ASMInstruction::Atrribute); + translate_main(codegen); + + std::cout << codegen->print(); + delete codegen; + delete module; + return 0; +} + +void declare_global(CodeGen *codegen) { + // 声明全局变量 a + // 将 a 放到 .bss 段中 + codegen->append_inst(".section .bss, \"aw\", @nobits", + ASMInstruction::Atrribute); + // 标记 a 为全局变量 + codegen->append_inst(".globl a", ASMInstruction::Atrribute); + // 标记 a 为数据对象 (变量) + codegen->append_inst(".type a, @object", ASMInstruction::Atrribute); + // 标记 a 的大小为 4 字节 + codegen->append_inst(".size a, 4", ASMInstruction::Atrribute); + // a 的标签 + codegen->append_inst("a", ASMInstruction::Label); + // 为 a 分配空间 + codegen->append_inst(".space 4"); +} + +// TODO: 按照提示补全 +void translate_main(CodeGen *codegen) { + std::unordered_map offset_map; + + /* 声明 main 函数 */ + codegen->append_inst(".globl main", ASMInstruction::Atrribute); + codegen->append_inst(".type main, @function", ASMInstruction::Atrribute); + + /* main 函数开始 */ + codegen->append_inst("main", ASMInstruction::Label); // main 函数标签 + + /* main 函数的 Prologue (序言) */ + // 保存返回地址 + codegen->append_inst("st.d $ra, $sp, -8"); + // 保存老的 fp + codegen->append_inst("st.d $fp, $sp, -16"); + // 设置新的 fp + codegen->append_inst("addi.d $fp, $sp, 0"); + // 为栈帧分配空间. 思考: 为什么是 32 字节? + codegen->append_inst("addi.d $sp, $sp, -32"); + + /* main 函数的 label_entry */ + codegen->append_inst(".main_label_entry", ASMInstruction::Label); + + /* store i32 10, i32* @a */ + // 在汇编中写入注释, 方便 debug + codegen->append_inst("store i32 10, i32* @a", ASMInstruction::Comment); + // 将 10 写入 a 对应的内存空间中 + // TODO: 获得 a 的地址 + codegen->append_inst(""); + // TODO: 将 10 写入 a 对应的内存空间中 + codegen->append_inst(""); + + /* %op0 = load i32, i32* @a */ + codegen->append_inst("%op0 = load i32, i32* @a", ASMInstruction::Comment); + // 将 a 的值写入 %op0 对应的内存空间中 + offset_map["%op0"] = ; // TODO: 请填空 + // TODO: 获得 a 的地址, 并存储在 $t0 中 + codegen->append_inst(""); + // 将 a 的值写入 %op0 对应的内存空间中 + codegen->append_inst("ld.w $t1, $t0, 0"); + codegen->append_inst("st.w", + {"$t1", "$fp", std::to_string(offset_map["%op0"])}); + + /* ret i32 %op0 */ + codegen->append_inst("ret i32 %op0", ASMInstruction::Comment); + // 将 %op0 的值写入 $a0 + codegen->append_inst("ld.w", + {"$a0", "$fp", std::to_string(offset_map["%op0"])}); + codegen->append_inst("b main_exit"); + + /* main 函数的 Epilogue (收尾) */ + codegen->append_inst("main_exit", ASMInstruction::Label); + // 释放栈帧空间 + codegen->append_inst("addi.d $sp, $sp, 32"); + // 恢复 ra + codegen->append_inst("ld.d $ra, $sp, -8"); + // 恢复 fp + codegen->append_inst("ld.d $fp, $sp, -16"); + // 返回 + codegen->append_inst("jr $ra"); +} diff --git a/tests/3-codegen/warmup/stu_cpp/icmp_codegen.cpp b/tests/3-codegen/warmup/stu_cpp/icmp_codegen.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ee51e49ab404f1faa97f72f5ebf8a803b0f11d2a --- /dev/null +++ b/tests/3-codegen/warmup/stu_cpp/icmp_codegen.cpp @@ -0,0 +1,114 @@ +#include "ASMInstruction.hpp" +#include "CodeGen.hpp" +#include "Module.hpp" + +#include +#include +#include + +void translate_main(CodeGen *codegen); // 将 main 函数翻译为汇编代码 + +int main() { + auto *module = new Module(); + auto *codegen = new CodeGen(module); + + // 告诉汇编器将汇编放到代码段 + codegen->append_inst(".text", ASMInstruction::Atrribute); + + translate_main(codegen); + + std::cout << codegen->print(); + delete codegen; + delete module; + return 0; +} + +// TODO: 按照提示补全 +void translate_main(CodeGen *codegen) { + std::unordered_map offset_map; + + /* 声明 main 函数 */ + codegen->append_inst(".globl main", ASMInstruction::Atrribute); + codegen->append_inst(".type main, @function", ASMInstruction::Atrribute); + + /* main 函数开始 */ + codegen->append_inst("main", ASMInstruction::Label); // main 函数标签 + + /* main 函数的 Prologue (序言) */ + // 保存返回地址 + codegen->append_inst("st.d $ra, $sp, -8"); + // 保存老的 fp + codegen->append_inst("st.d $fp, $sp, -16"); + // 设置新的 fp + codegen->append_inst("addi.d $fp, $sp, 0"); + // 为栈帧分配空间. 思考: 为什么是 32 字节? + codegen->append_inst("addi.d $sp, $sp, -32"); + + /* main 函数的 label_entry */ + codegen->append_inst(".main_label_entry", ASMInstruction::Label); + + /* %op0 = icmp sgt i32 5, 1 */ + // 在汇编中写入注释, 方便 debug + codegen->append_inst("%op0 = icmp sgt i32 5, 1", ASMInstruction::Comment); + // 将比较结果写入 %op0 对应的内存空间中 + offset_map["%op0"] = ; // TODO: 请填空 + codegen->append_inst("addi.w $t0, $zero, 5"); + codegen->append_inst("addi.w $t1, $zero, 1"); + // TODO: 使用 slt 指令比较, 并将结果写入 %op0 对应的内存空间中 + codegen->append_inst(""); + codegen->append_inst(""); + + /* %op1 = zext i1 %op0 to i32 */ + codegen->append_inst("%op1 = zext i1 %op0 to i32", ASMInstruction::Comment); + // 将 %op0 的值从 i1 类型转换为 i32 类型, 并将结果写入到 %op1 对应的内存空 + // 间中 + offset_map["%op1"] = ; // TODO: 请填空 + // TODO: 获得 %op0 的值, 然后进行转换, 最后将结果写入 %op1 + // 思考: 怎么转换? 需不需要显式地使用某些指令转换? + codegen->append_inst(""); + + /* %op2 = icmp ne i32 %op1, 0 */ + codegen->append_inst("%op2 = icmp ne i32 %op1, 0", ASMInstruction::Comment); + // 比较 %op1 和 0, 并将结果写入 %op2 对应的内存空间中 + offset_map["%op2"] = ; // TODO: 请填空 + // TODO: 获得 %op1 的值, 然后进行比较, 最后将结果写入 %op2 + // 思考: 如何比较? 能否不使用跳转指令计算结果? + // 提示: 尝试使用 xor/xori 和 slt/sltu/slti/sltui 计算比较结果 + codegen->append_inst(""); + + /* br i1 %op2, label %label3, label %label4 */ + codegen->append_inst("br i1 %op2, label %label3, label %label4", + ASMInstruction::Comment); + // TODO: 获得 %op2 的值, 并根据 %op2 的值跳转到 label3 或者 label4 + // 提示: 汇编中对应的标签分别为 .main_label3 和 .main_label4 + codegen->append_inst(""); + + /* label3: */ + codegen->append_inst(".main_label3", ASMInstruction::Label); + + /* ret i32 233 */ + codegen->append_inst("ret i32 233", ASMInstruction::Comment); + // 将 233 写入 $a0 中 + codegen->append_inst("addi.w $a0, $zero, 233"); + codegen->append_inst("b main_exit"); + + /* label4: */ + codegen->append_inst(".main_label4", ASMInstruction::Label); + + /* ret i32 0 */ + codegen->append_inst("ret i32 0", ASMInstruction::Comment); + // 将 0 写入 $a0 中 + codegen->append_inst("addi.w $a0, $zero, 0"); + codegen->append_inst("b main_exit"); + + /* main 函数的 Epilogue (收尾) */ + codegen->append_inst("main_exit", ASMInstruction::Label); + // 释放栈帧空间 + codegen->append_inst("addi.d $sp, $sp, 32"); + // 恢复 ra + codegen->append_inst("ld.d $ra, $sp, -8"); + // 恢复 fp + codegen->append_inst("ld.d $fp, $sp, -16"); + // 返回 + codegen->append_inst("jr $ra"); +} diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index ca25a59f65041c6bb171755b92e522d9907043bf..6c9ad388c0cd77ce762f01ec08dc2d9df9dc7f38 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -1 +1,2 @@ -add_subdirectory("2-ir-gen/warmup") \ No newline at end of file +add_subdirectory("2-ir-gen/warmup") +add_subdirectory("3-codegen/warmup") \ No newline at end of file