[midend]IRPrinter增加了打印全局常量的功能

This commit is contained in:
rain2133
2025-07-30 14:46:28 +08:00
parent 98511efd91
commit 38bee5d5ac
2 changed files with 44 additions and 0 deletions

View File

@@ -15,6 +15,7 @@ public:
public: public:
void printIR(); void printIR();
void printGlobalVariable(); void printGlobalVariable();
void printGlobalConstant();
public: public:

View File

@@ -13,6 +13,7 @@ void SysYPrinter::printIR() {
//TODO: Print target datalayout and triple (minimal required by LLVM) //TODO: Print target datalayout and triple (minimal required by LLVM)
printGlobalVariable(); printGlobalVariable();
printGlobalConstant();
for (const auto &iter : functions) { for (const auto &iter : functions) {
if (iter.second->getName() == "main") { if (iter.second->getName() == "main") {
@@ -137,6 +138,48 @@ void SysYPrinter::printGlobalVariable() {
} }
} }
void SysYPrinter::printGlobalConstant() {
auto &globalConstants = pModule->getConsts();
for (const auto &globalConstant : globalConstants) {
std::cout << "@" << globalConstant->getName() << " = global constant ";
// 全局变量的类型是一个指针,指向其基类型 (可能是 ArrayType 或 Integer/FloatType)
auto globalVarBaseType = dynamic_cast<PointerType *>(globalConstant->getType())->getBaseType();
printType(globalVarBaseType); // 打印全局变量的实际类型 (例如 i32 或 [10 x i32])
std::cout << " ";
// 检查是否是数组类型 (通过检查 globalVarBaseType 是否是 ArrayType)
if (globalVarBaseType->isArray()) {
// 数组初始化器
std::cout << "["; // LLVM IR 数组初始化器格式: [type value, type value, ...]
auto values = globalConstant->getInitValues(); // 假设 getInitValues() 返回一个 ValueCounter
const std::vector<sysy::Value *> &counterValues = values.getValues(); // 获取所有值
for (size_t i = 0; i < counterValues.size(); i++) {
if (i > 0) std::cout << ", ";
// 打印元素类型,这个元素类型应该是数组的最终元素类型,例如 i32 或 float
// 可以从 globalVarBaseType 逐层剥离得到最终元素类型,但这里简化为直接从值获取
printType(counterValues[i]->getType());
std::cout << " ";
printValue(counterValues[i]);
}
std::cout << "]";
} else {
// 标量初始化器
// 假设标量全局变量的初始化值通过 getByIndex(0) 获取
Value* initVal = globalConstant->getByIndex(0);
printType(initVal->getType()); // 打印标量值的类型
std::cout << " ";
printValue(initVal); // 打印标量值
}
std::cout << ", align 4" << std::endl;
}
}
void SysYPrinter::printBlock(BasicBlock *block) { void SysYPrinter::printBlock(BasicBlock *block) {
std::cout << getBlockName(block); std::cout << getBlockName(block);
} }