实现指令编解码与反汇编,冻结 disasm 格式。

- Encode.h/Encode.cpp:encode/decode 往返 + disasm 一行文本
- 指令与映像.md 新增反汇编格式表(9 种形态 + 未知操作码)
- Op.h STORE_* 注释对齐 disasm(rs, slot 寄存器在前)
This commit is contained in:
2026-08-19 14:06:20 +08:00
parent 7c855b1618
commit eba48f852e
4 changed files with 149 additions and 3 deletions
+96
View File
@@ -0,0 +1,96 @@
/**
* @file Encode.cpp
* @brief 指令编解码与反汇编
* @author
* @date 2026-08-19
*/
#include "isa/Encode.h"
#include <cstdio>
namespace isa {
Instr encode(Decoded d) {
return pack(d.op, d.rd, d.a, d.b);
}
Decoded decode(Instr w) {
Decoded d;
d.op = op(w);
d.rd = rd(w);
d.a = a(w);
d.b = b(w);
return d;
}
void disasm(Instr w, char* out, size_t cap) {
if (cap == 0) {
return;
}
out[0] = '\0';
const Op o = op(w);
const int idx = static_cast<int>(o);
if (idx < 0 || idx >= kOpCount) {
snprintf(out, cap, "??? 0x%08x", static_cast<unsigned>(w));
return;
}
const char* m = mnemonic(o);
switch (o) {
case Op::MOVE:
case Op::NOT:
snprintf(out, cap, "%s r%u, r%u", m,
static_cast<unsigned>(rd(w)), static_cast<unsigned>(a(w)));
break;
case Op::AND:
case Op::OR:
case Op::ADD:
case Op::SUB:
case Op::MUL:
case Op::DIV:
case Op::CMP_EQ:
case Op::CMP_NE:
case Op::CMP_LT:
case Op::CMP_LE:
case Op::CMP_GT:
case Op::CMP_GE:
snprintf(out, cap, "%s r%u, r%u, r%u", m,
static_cast<unsigned>(rd(w)), static_cast<unsigned>(a(w)),
static_cast<unsigned>(b(w)));
break;
case Op::LOADK:
snprintf(out, cap, "%s r%u, %u", m,
static_cast<unsigned>(rd(w)), static_cast<unsigned>(imm16(w)));
break;
case Op::JMP:
snprintf(out, cap, "%s %+d", m, static_cast<int>(off16(w)));
break;
case Op::JT:
case Op::JF:
snprintf(out, cap, "%s r%u, %+d", m,
static_cast<unsigned>(rd(w)), static_cast<int>(off16(w)));
break;
case Op::LOAD_I:
case Op::STORE_Q:
case Op::LOAD_M:
case Op::STORE_M:
case Op::LOAD_GLOBAL:
case Op::STORE_GLOBAL:
snprintf(out, cap, "%s r%u, %u", m,
static_cast<unsigned>(rd(w)), static_cast<unsigned>(imm16(w)));
break;
case Op::CAL_TON:
case Op::CAL_TOF:
case Op::CAL_CTU:
case Op::CALL:
snprintf(out, cap, "%s %u", m, static_cast<unsigned>(imm16(w)));
break;
case Op::RET:
snprintf(out, cap, "%s", m);
break;
}
}
} // namespace isa