[midend-llvnirprint]修改浮点为字面值打印,修复assign的类型推断

This commit is contained in:
rain2133
2025-08-10 16:12:09 +08:00
parent 2c5e4cead1
commit d1ba140657
2 changed files with 98 additions and 50 deletions

View File

@@ -13,16 +13,15 @@
using namespace std;
inline std::string getMachineCode(float fval) {
// LLVM IR要求float也使用64位十六进制表示
// 将float扩展为double精度格式
double dval = static_cast<double>(fval);
uint64_t bits = *reinterpret_cast<uint64_t*>(&dval);
// 如果是0直接返回
if (bits == 0 || fval == 0.0f) {
if (fval == 0.0f) {
return "0x0000000000000000";
}
// 正确的float到double扩展先转换值再获取double的位表示
double dval = static_cast<double>(fval);
uint64_t bits = *reinterpret_cast<uint64_t*>(&dval);
std::stringstream ss;
ss << "0x" << std::hex << std::uppercase << std::setfill('0') << std::setw(16) << bits;
return ss.str();
@@ -90,11 +89,18 @@ static inline ostream &printFunctionName(ostream &os, const Function *fn) {
static inline ostream &printOperand(ostream &os, const Value *value) {
auto constValue = dynamic_cast<const ConstantValue*>(value);
if (constValue != nullptr) {
// 对于常量,只打印值,不打印类型(类型已经在指令中单独打印了)
if (auto constInt = dynamic_cast<const ConstantInteger*>(constValue)) {
os << constInt->getInt();
} else if (auto constFloat = dynamic_cast<const ConstantFloating*>(constValue)) {
os << getMachineCode(constFloat->getFloat());
float f = constFloat->getFloat();
char buffer[64];
snprintf(buffer, sizeof(buffer), "%.17g", f);
std::string str(buffer);
if (str.find('.') == std::string::npos && str.find('e') == std::string::npos) {
str += ".0";
}
os << str;
} else if (auto undefVal = dynamic_cast<const UndefinedValue*>(constValue)) {
os << "undef";
}
@@ -586,10 +592,18 @@ void ConstantValue::print(std::ostream &os) const {
}
void ConstantInteger::print(std::ostream &os) const {
os << "i32 " << this->getInt();
os << this->getInt();
}
void ConstantFloating::print(std::ostream &os) const {
os << "float " << getMachineCode(this->getFloat());
float f = this->getFloat();
char buffer[64];
snprintf(buffer, sizeof(buffer), "%.17g", f);
std::string str(buffer);
if (str.find('.') == std::string::npos && str.find('e') == std::string::npos) {
str += ".0";
}
os << str;
}
void UndefinedValue::print(std::ostream &os) const {
os << this->getType() << " undef";