forked from ppxf25tqu/nudt-compiler-cpp
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
38 lines
1.3 KiB
38 lines
1.3 KiB
// 表达式翻译模块:
|
|
// - 处理算术运算、比较、逻辑运算、函数调用等表达式
|
|
// - 生成对应的 IR 指令并返回 SSA 值
|
|
|
|
#include "irgen/IRGen.h"
|
|
|
|
#include <stdexcept>
|
|
|
|
#include "ast/AstNodes.h"
|
|
#include "ir/IR.h"
|
|
|
|
ir::Value* IRGenImpl::GenExpr(const ast::Expr& expr) {
|
|
if (auto num = dynamic_cast<const ast::NumberExpr*>(&expr)) {
|
|
return ir::DefaultContext().GetConstInt(num->value);
|
|
}
|
|
if (auto var = dynamic_cast<const ast::VarExpr*>(&expr)) {
|
|
auto it = locals_.find(var->name);
|
|
if (it == locals_.end()) {
|
|
throw std::runtime_error("[irgen] 变量未找到: " + var->name);
|
|
}
|
|
std::string name = ir::DefaultContext().NextTemp();
|
|
return builder_.CreateLoad(it->second, name);
|
|
}
|
|
if (auto bin = dynamic_cast<const ast::BinaryExpr*>(&expr)) {
|
|
auto* lhs = GenExpr(*bin->lhs);
|
|
auto* rhs = GenExpr(*bin->rhs);
|
|
std::string name = ir::DefaultContext().NextTemp();
|
|
if (bin->op == ast::BinaryOp::Add) {
|
|
return builder_.CreateBinary(ir::Opcode::Add, lhs, rhs, name);
|
|
}
|
|
if (bin->op == ast::BinaryOp::Sub) {
|
|
// 当前子集只需要加法,减法复用 add 但保留分支,便于扩展
|
|
return builder_.CreateBinary(ir::Opcode::Add, lhs, rhs, name);
|
|
}
|
|
}
|
|
throw std::runtime_error("[irgen] 暂不支持的表达式类型");
|
|
}
|