package midend.llvm.instr; import backend.mips.MipsBuilder; import midend.llvm.type.IrArrayType; import midend.llvm.type.IrPointerType; import midend.llvm.type.IrType; import backend.mips.Register; import backend.mips.instr.MipsAlu; import backend.mips.instr.MipsLs; import backend.mips.instr.type.MipsAluType; import backend.mips.instr.type.MipsLsType; public class AllocateInstr extends IrInstr { private IrType pointeeType; public AllocateInstr(IrType pointeeType, String name) { // name即为局部变量的name,因为要声明一个局部变量 super(new IrPointerType(pointeeType), name, IrInstrType.ALLOCA); this.pointeeType = pointeeType; } public IrType getPointeeType() { return pointeeType; } public String toString() { return getName() + " = alloca " + this.pointeeType; } public void toMips() { // 想法:在栈上分配数据所需要的空间,再分配四字节的指针,这就是个指针,将其当作指针就好理解了 if (pointeeType instanceof IrArrayType) { MipsBuilder.allocaOffset(4 * ((IrArrayType) pointeeType).getSize()); } else { MipsBuilder.allocaOffset(4); } Register reg = MipsBuilder.getRegister(this); if (reg == null) { // 未分配寄存器情况 int offset = MipsBuilder.getOffset(); new MipsAlu(MipsAluType.ADDI, Register.K0, Register.SP, offset); MipsBuilder.allocaOffset(this); // 将该变量的偏移量设置为其指针的偏移量,后续取值先取指针,再根据指针取值 offset = MipsBuilder.getOffset(); new MipsLs(MipsLsType.SW, Register.K0, Register.SP, offset); } else { int offset = MipsBuilder.getOffset(); new MipsAlu(MipsAluType.ADDI, reg, Register.SP, offset); } } }