refactor(irgen): IR改成alloca和store形式

This commit is contained in:
jing
2026-03-01 15:36:50 +08:00
parent 29bf99727f
commit 730280abb8
10 changed files with 180 additions and 10 deletions

View File

@@ -5,11 +5,18 @@
#include "irgen/IRGen.h"
#include <memory>
#include <stdexcept>
#include "ast/AstNodes.h"
#include "ir/IR.h"
void IRGenImpl::GenBlock(const ast::Block& block) {
// 先为所有局部变量创建栈槽,使 alloca 聚集在入口块前部。
for (const auto& decl : block.varDecls) {
auto* slot = builder_.CreateAllocaI32(ir::DefaultContext().NextTemp());
locals_[decl->name] = slot;
}
for (const auto& decl : block.varDecls) {
GenVarDecl(*decl);
}
@@ -19,11 +26,16 @@ void IRGenImpl::GenBlock(const ast::Block& block) {
}
void IRGenImpl::GenVarDecl(const ast::VarDecl& decl) {
auto it = locals_.find(decl.name);
if (it == locals_.end()) {
throw std::runtime_error("变量栈槽未创建: " + decl.name);
}
ir::Value* init = nullptr;
if (decl.init) {
init = GenExpr(*decl.init);
} else {
init = ir::DefaultContext().GetConstInt(0);
}
locals_[decl.name] = init;
builder_.CreateStore(init, it->second);
}