[backend]添加了一些工具函数

This commit is contained in:
Lixuanwang
2025-08-04 16:32:54 +08:00
parent 64ba25a77e
commit 0179c13cf4
5 changed files with 36 additions and 26 deletions

View File

@ -1,7 +1,8 @@
#include "RISCv64AsmPrinter.h"
#include "RISCv64ISel.h"
#include <stdexcept>
#include <sstream>
#include <iostream>
namespace sysy {
// 检查是否为内存加载/存储指令,以处理特殊的打印格式
@ -236,4 +237,30 @@ std::string RISCv64AsmPrinter::regToString(PhysicalReg reg) {
}
}
std::string RISCv64AsmPrinter::formatInstr(const MachineInstr* instr) {
if (!instr) return "(null instr)";
// 使用 stringstream 作为临时的输出目标
std::stringstream ss;
// 关键: 临时将类成员 'OS' 指向我们的 stringstream
std::ostream* old_os = this->OS;
this->OS = &ss;
// 修正: 调用正确的内部打印函数 printMachineInstr
printInstruction(const_cast<MachineInstr*>(instr), false);
// 恢复旧的 ostream 指针
this->OS = old_os;
// 获取stringstream的内容并做一些清理
std::string result = ss.str();
size_t endpos = result.find_last_not_of(" \t\n\r");
if (std::string::npos != endpos) {
result = result.substr(0, endpos + 1);
}
return result;
}
} // namespace sysy

View File

@ -1699,4 +1699,8 @@ void RISCv64ISel::print_dag(const std::vector<std::unique_ptr<DAGNode>>& dag, co
std::cerr << "======================================\n\n";
}
unsigned int RISCv64ISel::getVRegCounter() const {
return vreg_counter;
}
} // namespace sysy

View File

@ -122,30 +122,6 @@ void RISCv64RegAlloc::precolorByCallingConvention() {
}
}
// // --- 部分2为CALL指令的返回值预着色 ---
// for (auto& mbb : MFunc->getBlocks()) {
// for (auto& instr : mbb->getInstructions()) {
// if (instr->getOpcode() == RVOpcodes::CALL) {
// if (!instr->getOperands().empty() &&
// instr->getOperands().front()->getKind() == MachineOperand::KIND_REG)
// {
// auto reg_op = static_cast<RegOperand*>(instr->getOperands().front().get());
// if (reg_op->isVirtual()) {
// unsigned ret_vreg = reg_op->getVRegNum();
// assert(vreg_to_value_map.count(ret_vreg) && "Return vreg not found!");
// Value* ret_val = vreg_to_value_map.at(ret_vreg);
// if (ret_val->getType()->isFloat()) {
// color_map[ret_vreg] = PhysicalReg::F10; // fa0
// } else {
// color_map[ret_vreg] = PhysicalReg::A0; // a0
// }
// }
// }
// }
// }
// }
// 将所有预着色的vreg视为已着色节点
for(const auto& pair : color_map) {
coloredNodes.insert(pair.first);

View File

@ -20,6 +20,8 @@ public:
void setStream(std::ostream& os) { OS = &os; }
// 辅助函数
std::string regToString(PhysicalReg reg);
std::string formatInstr(const MachineInstr *instr);
private:
// 打印各个部分
void printBasicBlock(MachineBasicBlock* mbb, bool debug = false);

View File

@ -17,7 +17,8 @@ public:
// 公开接口以便后续模块如RegAlloc可以查询或创建vreg
unsigned getVReg(Value* val);
unsigned getNewVReg() { return vreg_counter++; }
unsigned getNewVReg(Type* type);
unsigned getNewVReg(Type* type);
unsigned getVRegCounter() const;
// 获取 vreg_map 的公共接口
const std::map<Value*, unsigned>& getVRegMap() const { return vreg_map; }
const std::map<unsigned, Value*>& getVRegValueMap() const { return vreg_to_value_map; }