From fedb4b0a9f0540bc98f955c2d0d52a536ec4588c Mon Sep 17 00:00:00 2001 From: Lixuanwang Date: Fri, 18 Jul 2025 18:48:38 +0800 Subject: [PATCH] =?UTF-8?q?[backend]=E4=BF=AE=E5=A4=8D=E4=BA=86=E6=A0=88?= =?UTF-8?q?=E5=88=86=E9=85=8D=E7=A9=BA=E9=97=B4=E5=A4=A7=E5=B0=8F=E4=B8=8D?= =?UTF-8?q?=E8=80=83=E8=99=91=E6=95=B0=E7=BB=84=E7=9A=84=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/RISCv64Backend.cpp | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/src/RISCv64Backend.cpp b/src/RISCv64Backend.cpp index 25012d4..22be499 100644 --- a/src/RISCv64Backend.cpp +++ b/src/RISCv64Backend.cpp @@ -1348,6 +1348,7 @@ RISCv64CodeGen::RegAllocResult RISCv64CodeGen::register_allocation(Function* fun int current_stack_offset = 0; std::set allocas_in_func; + // 收集函数中的所有 AllocaInst for (const auto& bb_ptr : func->getBasicBlocks()) { for (const auto& inst_ptr : bb_ptr->getInstructions()) { if (auto alloca = dynamic_cast(inst_ptr.get())) { @@ -1356,10 +1357,28 @@ RISCv64CodeGen::RegAllocResult RISCv64CodeGen::register_allocation(Function* fun } } + // 为每个 AllocaInst 计算栈空间并分配偏移量 for (auto alloca : allocas_in_func) { - int size = 4; // 假设 i32 或 float, 依旧是4字节 + int total_size = 4; // 基本元素大小(int 或 float) + auto dims = alloca->getDims(); + if (!dims.empty()) { + int num_elements = 1; + for (const auto& dim_use : dims) { + Value* dim_value = dim_use->getValue(); + if (auto const_dim = dynamic_cast(dim_value)) { + if (const_dim->isInt()) { + num_elements *= const_dim->getInt(); + } else { + throw std::runtime_error("数组维度必须是整数"); + } + } else { + throw std::runtime_error("数组维度必须是编译时常量"); + } + } + total_size *= num_elements; + } alloc_result.stack_map[alloca] = current_stack_offset; - current_stack_offset += size; + current_stack_offset += total_size; } // RV64 修改: 为保存的 ra 和 s0 (各8字节) 预留16字节空间 alloc_result.stack_size = current_stack_offset + 16;