优化ir
This commit is contained in:
parent
d9f402f8b8
commit
0c9fd24fbc
@ -24,7 +24,7 @@ import org.jcnc.snow.compiler.parser.ast.base.StatementNode;
|
||||
final class FunctionBuilder {
|
||||
|
||||
/** 当前正在构建的 IRFunction 实例 */
|
||||
private IRFunction fn;
|
||||
private IRFunction irFunction;
|
||||
|
||||
/** 管理变量名到虚拟寄存器的映射 */
|
||||
private final Scope scope = new Scope();
|
||||
@ -32,19 +32,19 @@ final class FunctionBuilder {
|
||||
/**
|
||||
* 将给定的 FunctionNode 转换为 IRFunction。
|
||||
*
|
||||
* @param node 要转换的函数节点
|
||||
* @param functionNode 要转换的函数节点
|
||||
* @return 构建完成的 IRFunction
|
||||
*/
|
||||
IRFunction build(FunctionNode node) {
|
||||
fn = new IRFunction(node.name());
|
||||
scope.attachFunction(fn);
|
||||
for (ParameterNode p : node.parameters()) {
|
||||
IRFunction build(FunctionNode functionNode) {
|
||||
irFunction = new IRFunction(functionNode.name());
|
||||
scope.attachFunction(irFunction);
|
||||
for (ParameterNode p : functionNode.parameters()) {
|
||||
scope.declare(p.name());
|
||||
}
|
||||
for (StatementNode s : node.body()) {
|
||||
for (StatementNode s : functionNode.body()) {
|
||||
stmt(s);
|
||||
}
|
||||
return fn;
|
||||
return irFunction;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -77,9 +77,9 @@ final class FunctionBuilder {
|
||||
case ReturnNode r -> {
|
||||
// 处理返回语句,区分是否带返回值
|
||||
if (r.getExpression().isPresent()) {
|
||||
fn.add(new ReturnInstruction(expr(r.getExpression().get())));
|
||||
irFunction.add(new ReturnInstruction(expr(r.getExpression().get())));
|
||||
} else {
|
||||
fn.add(new ReturnInstruction(null));
|
||||
irFunction.add(new ReturnInstruction(null));
|
||||
}
|
||||
}
|
||||
case null, default -> throw new IllegalStateException("Unsupported statement: " + s);
|
||||
@ -115,8 +115,8 @@ final class FunctionBuilder {
|
||||
* @return 存放常量的虚拟寄存器
|
||||
*/
|
||||
private VirtualRegister number(NumberLiteralNode n) {
|
||||
VirtualRegister vr = fn.newRegister();
|
||||
fn.add(new LoadConstInstruction(vr, new Constant(Integer.parseInt(n.value()))));
|
||||
VirtualRegister vr = irFunction.newRegister();
|
||||
irFunction.add(new LoadConstInstruction(vr, new Constant(Integer.parseInt(n.value()))));
|
||||
return vr;
|
||||
}
|
||||
|
||||
@ -129,7 +129,7 @@ final class FunctionBuilder {
|
||||
private VirtualRegister bin(BinaryExpressionNode b) {
|
||||
VirtualRegister l = expr(b.left());
|
||||
VirtualRegister r = expr(b.right());
|
||||
VirtualRegister d = fn.newRegister();
|
||||
VirtualRegister d = irFunction.newRegister();
|
||||
|
||||
IROp op = switch (b.operator()) {
|
||||
case "+" -> IROp.ADD_I32;
|
||||
@ -139,7 +139,7 @@ final class FunctionBuilder {
|
||||
default -> throw new IllegalStateException("Unknown operator " + b.operator());
|
||||
};
|
||||
|
||||
fn.add(new BinOpInstruction(op, d, l, r));
|
||||
irFunction.add(new BinOpInstruction(op, d, l, r));
|
||||
return d;
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user