diff --git a/test_script/runit-riscv64-single.sh b/script/runit-riscv64-single.sh similarity index 100% rename from test_script/runit-riscv64-single.sh rename to script/runit-riscv64-single.sh diff --git a/test_script/runit-riscv64.sh b/script/runit-riscv64.sh similarity index 100% rename from test_script/runit-riscv64.sh rename to script/runit-riscv64.sh diff --git a/test_script/runit-single.sh b/script/runit-single.sh similarity index 100% rename from test_script/runit-single.sh rename to script/runit-single.sh diff --git a/test_script/runit.sh b/script/runit.sh similarity index 100% rename from test_script/runit.sh rename to script/runit.sh diff --git a/src/AddressCalculationExpansion.cpp b/src/AddressCalculationExpansion.cpp deleted file mode 100644 index 12712ae..0000000 --- a/src/AddressCalculationExpansion.cpp +++ /dev/null @@ -1,171 +0,0 @@ -#include "AddressCalculationExpansion.h" -#include -#include -#include "IR.h" -#include "IRBuilder.h" - -extern int DEBUG; - -namespace sysy { - -bool AddressCalculationExpansion::run() { - bool changed = false; - - for (auto& funcPair : pModule->getFunctions()) { - Function* func = funcPair.second.get(); - for (auto& bb_ptr : func->getBasicBlocks()) { - BasicBlock* bb = bb_ptr.get(); - for (auto it = bb->getInstructions().begin(); it != bb->getInstructions().end(); ) { - Instruction* inst = it->get(); - - Value* basePointer = nullptr; - Value* valueToStore = nullptr; - size_t firstIndexOperandIdx = 0; - size_t numBaseOperands = 0; - - if (inst->isLoad()) { - numBaseOperands = 1; - basePointer = inst->getOperand(0); - firstIndexOperandIdx = 1; - } else if (inst->isStore()) { - numBaseOperands = 2; - valueToStore = inst->getOperand(0); - basePointer = inst->getOperand(1); - firstIndexOperandIdx = 2; - } else { - ++it; - continue; - } - - if (inst->getNumOperands() <= numBaseOperands) { - ++it; - continue; - } - - std::vector dims; - if (AllocaInst* allocaInst = dynamic_cast(basePointer)) { - for (const auto& use_ptr : allocaInst->getDims()) { - Value* dimValue = use_ptr->getValue(); - if (ConstantValue* constVal = dynamic_cast(dimValue)) { - dims.push_back(constVal->getInt()); - } else { - std::cerr << "Warning: AllocaInst dimension is not a constant integer. Skipping GEP expansion for: "; - SysYPrinter::printValue(allocaInst); - std::cerr << "\n"; - dims.clear(); - break; - } - } - } else if (GlobalValue* globalValue = dynamic_cast(basePointer)) { - // 遍历 GlobalValue 的所有维度操作数 - for (const auto& use_ptr : globalValue->getDims()) { - Value* dimValue = use_ptr->getValue(); - // 将维度值转换为常量整数 - if (ConstantInteger* constVal = dynamic_cast(dimValue)) { - dims.push_back(constVal->getInt()); - } else { - // 如果维度不是常量整数,则无法处理。 - // 根据 IR.h 中 GlobalValue 的构造函数,这种情况不应发生,但作为安全检查是好的。 - std::cerr << "Warning: GlobalValue dimension is not a constant integer. Skipping GEP expansion for: "; - SysYPrinter::printValue(globalValue); - std::cerr << "\n"; - dims.clear(); // 清空已收集的部分维度信息 - break; - } - } - } else { - std::cerr << "Warning: Base pointer is not AllocaInst/GlobalValue or its array dimensions cannot be determined for GEP expansion. Skipping GEP for: "; - SysYPrinter::printValue(basePointer); - std::cerr << " in instruction "; - SysYPrinter::printInst(inst); - std::cerr << "\n"; - ++it; - continue; - } - - if (dims.empty() && (inst->getNumOperands() > numBaseOperands)) { - if (DEBUG) { - std::cerr << "ACE Warning: Could not get valid array dimensions for "; - SysYPrinter::printValue(basePointer); - std::cerr << " in instruction "; - SysYPrinter::printInst(inst); - std::cerr << " (expected dimensions for indices, but got none).\n"; - } - ++it; - continue; - } - - std::vector indexOperands; - for (size_t i = firstIndexOperandIdx; i < inst->getNumOperands(); ++i) { - indexOperands.push_back(inst->getOperand(i)); - } - - if (AllocaInst* allocaInst = dynamic_cast(basePointer)) { - if (allocaInst->getNumDims() != indexOperands.size()) { - if (DEBUG) { - std::cerr << "ACE Warning: Index count (" << indexOperands.size() << ") does not match AllocaInst dimensions (" << allocaInst->getNumDims() << ") for instruction "; - SysYPrinter::printInst(inst); - std::cerr << "\n"; - } - ++it; - continue; - } - } - - Value* totalOffset = ConstantInteger::get(0); - pBuilder->setPosition(bb, it); - - for (size_t i = 0; i < indexOperands.size(); ++i) { - Value* index = indexOperands[i]; - int stride = calculateStride(dims, i); - Value* strideConst = ConstantInteger::get(stride); - Type* intType = Type::getIntType(); - BinaryInst* currentDimOffsetInst = pBuilder->createBinaryInst(Instruction::kMul, intType, index, strideConst); - BinaryInst* newTotalOffsetInst = pBuilder->createBinaryInst(Instruction::kAdd, intType, totalOffset, currentDimOffsetInst); - totalOffset = newTotalOffsetInst; - } - - // 计算有效地址:effective_address = basePointer + totalOffset - Value* effective_address = pBuilder->createBinaryInst(Instruction::kAdd, basePointer->getType(), basePointer, totalOffset); - - // 创建新的 LoadInst 或 StoreInst,indices 为空 - Instruction* newInst = nullptr; - if (inst->isLoad()) { - newInst = pBuilder->createLoadInst(effective_address, {}); - inst->replaceAllUsesWith(newInst); - } else { // StoreInst - newInst = pBuilder->createStoreInst(valueToStore, effective_address, {}); - } - - Instruction* oldInst = it->get(); - ++it; - - for (size_t i = 0; i < oldInst->getNumOperands(); ++i) { - Value* operandValue = oldInst->getOperand(i); - if (operandValue) { - for (auto use_it = operandValue->getUses().begin(); use_it != operandValue->getUses().end(); ++use_it) { - if ((*use_it)->getUser() == oldInst && (*use_it)->getIndex() == i) { - operandValue->removeUse(*use_it); - break; - } - } - } - } - - bb->getInstructions().erase(std::prev(it)); - changed = true; - - if (DEBUG) { - std::cerr << "ACE: Computed effective address:\n"; - SysYPrinter::printInst(dynamic_cast(effective_address)); - std::cerr << "ACE: New Load/Store instruction:\n"; - SysYPrinter::printInst(newInst); - std::cerr << "--------------------------------\n"; - } - } - } - } - return changed; -} - -} // namespace sysy \ No newline at end of file diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 4f2f335..bc89c78 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1,60 +1,24 @@ -# 移除 ANTLR 代码生成相关配置 -# list(APPEND CMAKE_MODULE_PATH "${ANTLR_RUNTIME}/cmake") -# include(FindANTLR) -# antlr_target(SysYGen SysY.g4 -# LEXER PARSER -# OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} -# VISITOR -# ) +# src/CMakeLists.txt +# add_subdirectory 命令会负责遍历子目录并查找其内部的 CMakeLists.txt 文件 +add_subdirectory(frontend) +add_subdirectory(midend) +add_subdirectory(backend/RISCv64) -# 移除 SysYParser 库的构建(如果不需要独立库) -# add_library(SysYParser SHARED ${ANTLR_SysYGen_CXX_OUTPUTS}) -# target_include_directories(SysYParser PUBLIC ${ANTLR_RUNTIME}/runtime/src) -# target_link_libraries(SysYParser PUBLIC antlr4_shared) - -# 构建 sysyc 可执行文件,使用手动提供的 SysYLexer.cpp、SysYParser.cpp 等文件 +# 构建 sysyc 可执行文件,链接各个模块的库 add_executable(sysyc - sysyc.cpp - SysYLexer.cpp # 手动提供的文件 - SysYParser.cpp # 手动提供的文件 - SysYVisitor.cpp # 手动提供的文件 - IR.cpp - SysYIRGenerator.cpp - SysYIRPrinter.cpp - SysYIRCFGOpt.cpp - Pass.cpp - Dom.cpp - Liveness.cpp - DCE.cpp - AddressCalculationExpansion.cpp - Mem2Reg.cpp - Reg2Mem.cpp - RISCv64Backend.cpp - RISCv64ISel.cpp - RISCv64RegAlloc.cpp - RISCv64AsmPrinter.cpp - RISCv64Peephole.cpp - PreRA_Scheduler.cpp - PostRA_Scheduler.cpp - CalleeSavedHandler.cpp - LegalizeImmediates.cpp - PrologueEpilogueInsertion.cpp - RISCv64LLIR.cpp + sysyc.cpp ) -# 设置 include 路径,包含 ANTLR 运行时库和项目头文件 +# 链接各个模块的库 +target_link_libraries(sysyc PRIVATE + frontend_lib + midend_lib + riscv64_backend_lib + antlr4_shared +) + +# 设置 include 路径,包含项目顶层 include 目录 target_include_directories(sysyc PRIVATE - ${CMAKE_CURRENT_SOURCE_DIR}/include # 项目头文件目录 - ${ANTLR_RUNTIME}/runtime/src # ANTLR 运行时库头文件 -) - -# 保留 ANTLR 运行时库的链接 -target_link_libraries(sysyc PRIVATE antlr4_shared) - -# 保留其他编译选项 -target_compile_options(sysyc PRIVATE -frtti) - -# 可选:线程支持(如果需要,取消注释) -# set(THREADS_PREFER_PTHREAD_FLAG ON) -# find_package(Threads REQUIRED) -# target_link_libraries(sysyc PRIVATE Threads::Threads) \ No newline at end of file + ${CMAKE_CURRENT_SOURCE_DIR}/include # 项目头文件目录 + ${ANTLR_RUNTIME}/runtime/src # ANTLR运行时库头文件 +) \ No newline at end of file diff --git a/src/SysYIRAnalyser.cpp b/src/SysYIRAnalyser.cpp deleted file mode 100644 index 51e2b27..0000000 --- a/src/SysYIRAnalyser.cpp +++ /dev/null @@ -1,529 +0,0 @@ -#include "SysYIRAnalyser.h" -#include - - -namespace sysy { - - -void ControlFlowAnalysis::init() { - // 初始化分析器 - auto &functions = pModule->getFunctions(); - for (const auto &function : functions) { - auto func = function.second.get(); - auto basicBlocks = func->getBasicBlocks(); - for (auto &basicBlock : basicBlocks) { - blockAnalysisInfo[basicBlock.get()] = new BlockAnalysisInfo(); - blockAnalysisInfo[basicBlock.get()]->clear(); - } - functionAnalysisInfo[func] = new FunctionAnalysisInfo(); - functionAnalysisInfo[func]->clear(); - } -} - -void ControlFlowAnalysis::runControlFlowAnalysis() { - // 运行控制流分析 - clear(); // 清空之前的分析结果 - init(); // 初始化分析器 - computeDomNode(); - computeDomTree(); - computeDomFrontierAllBlk(); -} - -void ControlFlowAnalysis::intersectOP4Dom(std::unordered_set &dom, const std::unordered_set &other) { - // 计算交集 - for (auto it = dom.begin(); it != dom.end();) { - if (other.find(*it) == other.end()) { - // 如果other中没有这个基本块,则从dom中删除 - it = dom.erase(it); - } else { - ++it; - } - } -} - -auto ControlFlowAnalysis::findCommonDominator(BasicBlock *a, BasicBlock *b) -> BasicBlock * { - // 查找两个基本块的共同支配结点 - while (a != b) { - BlockAnalysisInfo* infoA = blockAnalysisInfo[a]; - BlockAnalysisInfo* infoB = blockAnalysisInfo[b]; - // 如果深度不同,则向上移动到直接支配结点 - // TODO:空间换时间倍增优化,优先级较低 - while (infoA->getDomDepth() > infoB->getDomDepth()) { - a = const_cast(infoA->getIdom()); - infoA = blockAnalysisInfo[a]; - } - while (infoB->getDomDepth() > infoA->getDomDepth()) { - b = const_cast(infoB->getIdom()); - infoB = blockAnalysisInfo[b]; - } - if (a == b) break; - a = const_cast(infoA->getIdom()); - b = const_cast(infoB->getIdom()); - } - return a; -} - -void ControlFlowAnalysis::computeDomNode(){ - auto &functions = pModule->getFunctions(); - // 分析每个函数内的基本块 - for (const auto &function : functions) { - auto func = function.second.get(); - auto basicBlocks = func->getBasicBlocks(); - std::unordered_set domSetTmp; - // 一开始把domSetTmp置为所有block - auto entry_block = func->getEntryBlock(); - entry_block->setName("Entry"); - blockAnalysisInfo[entry_block]->addDominants(entry_block); - for (auto &basicBlock : basicBlocks) { - domSetTmp.emplace(basicBlock.get()); - } - // 初始化 - for (auto &basicBlock : basicBlocks) { - if (basicBlock.get() != entry_block) { - blockAnalysisInfo[basicBlock.get()]->setDominants(domSetTmp); - // 先把所有block的必经结点都设为N - } - } - - // 支配节点计算公式 - //DOM[B]={B}∪ {⋂P∈pred(B) DOM[P]} - // 其中pred(B)是B的所有前驱结点 - // 迭代计算支配结点,直到不再变化 - // 这里使用迭代法,直到支配结点不再变化 - // TODO:Lengauer-Tarjan 算法可以更高效地计算支配结点 - // 或者按照CFG拓扑序遍历效率更高 - bool changed = true; - while (changed) { - changed = false; - // 循环非start结点 - for (auto &basicBlock : basicBlocks) { - if (basicBlock.get() != entry_block) { - auto olddom = - blockAnalysisInfo[basicBlock.get()]->getDominants(); - - std::unordered_set dom = - blockAnalysisInfo[basicBlock->getPredecessors().front()]->getDominants(); - - // 对于每个基本块,计算其支配结点 - // 取其前驱结点的支配结点的交集和自己 - for (auto pred : basicBlock->getPredecessors()) { - intersectOP4Dom(dom, blockAnalysisInfo[pred]->getDominants()); - } - dom.emplace(basicBlock.get()); - blockAnalysisInfo[basicBlock.get()]->setDominants(dom); - - if (dom != olddom) { - changed = true; - } - } - } - } - } -} - -// TODO: SEMI-NCA算法改进 -void ControlFlowAnalysis::computeDomTree() { - // 构造支配树 - auto &functions = pModule->getFunctions(); - for (const auto &function : functions) { - auto func = function.second.get(); - auto basicBlocks = func->getBasicBlocks(); - auto entry_block = func->getEntryBlock(); - - blockAnalysisInfo[entry_block]->setIdom(entry_block); - blockAnalysisInfo[entry_block]->setDomDepth(0); // 入口块深度为0 - - bool changed = true; - while (changed) { - changed = false; - - for (auto &basicBlock : basicBlocks) { - if (basicBlock.get() == entry_block) continue; - - BasicBlock *new_idom = nullptr; - for (auto pred : basicBlock->getPredecessors()) { - // 跳过未处理的前驱 - if (blockAnalysisInfo[pred]->getIdom() == nullptr) continue; - // new_idom = (new_idom == nullptr) ? pred : findCommonDominator(new_idom, pred); - if (new_idom == nullptr) - new_idom = pred; - else - new_idom = findCommonDominator(new_idom, pred); - } - // 更新直接支配节点 - if (new_idom && new_idom != blockAnalysisInfo[basicBlock.get()]->getIdom()) { - // 移除旧的支配关系 - if (blockAnalysisInfo[basicBlock.get()]->getIdom()) { - blockAnalysisInfo[const_cast(blockAnalysisInfo[basicBlock.get()]->getIdom())]->removeSdoms(basicBlock.get()); - } - // 设置新的支配关系 - - // std::cout << "Block: " << basicBlock->getName() - // << " New Idom: " << new_idom->getName() << std::endl; - - blockAnalysisInfo[basicBlock.get()]->setIdom(new_idom); - blockAnalysisInfo[new_idom]->addSdoms(basicBlock.get()); - // 更新深度 = 直接支配节点深度 + 1 - blockAnalysisInfo[basicBlock.get()]->setDomDepth( - blockAnalysisInfo[new_idom]->getDomDepth() + 1); - - changed = true; - } - } - } - } - // for (auto &basicBlock : basicBlocks) { - // if (basicBlock.get() != func->getEntryBlock()) { - // auto dominats = - // blockAnalysisInfo[basicBlock.get()]->getDominants(); - // bool found = false; - // // 从前驱结点开始寻找直接支配结点 - // std::queue q; - // for (auto pred : basicBlock->getPredecessors()) { - // q.push(pred); - // } - // // BFS遍历前驱结点,直到找到直接支配结点 - // while (!found && !q.empty()) { - // auto curr = q.front(); - // q.pop(); - // if (curr == basicBlock.get()) - // continue; - // if (dominats.count(curr) != 0U) { - // blockAnalysisInfo[basicBlock.get()]->setIdom(curr); - // blockAnalysisInfo[curr]->addSdoms(basicBlock.get()); - // found = true; - // } else { - // for (auto pred : curr->getPredecessors()) { - // q.push(pred); - // } - // } - // } - // } - // } -} - -// std::unordered_set ControlFlowAnalysis::computeDomFrontier(BasicBlock *block) { -// std::unordered_set ret_list; -// // 计算 localDF -// for (auto local_successor : block->getSuccessors()) { -// if (local_successor->getIdom() != block) { -// ret_list.emplace(local_successor); -// } -// } -// // 计算 upDF -// for (auto up_successor : block->getSdoms()) { -// auto childrenDF = computeDF(up_successor); -// for (auto w : childrenDF) { -// if (block != w->getIdom() || block == w) { -// ret_list.emplace(w); -// } -// } -// } - -// return ret_list; -// } - -void ControlFlowAnalysis::computeDomFrontierAllBlk() { - auto &functions = pModule->getFunctions(); - for (const auto &function : functions) { - auto func = function.second.get(); - auto basicBlocks = func->getBasicBlocks(); - - // 按支配树深度排序(从深到浅) - std::vector orderedBlocks; - for (auto &bb : basicBlocks) { - orderedBlocks.push_back(bb.get()); - } - std::sort(orderedBlocks.begin(), orderedBlocks.end(), - [this](BasicBlock *a, BasicBlock *b) { - return blockAnalysisInfo[a]->getDomDepth() > blockAnalysisInfo[b]->getDomDepth(); - }); - - // 计算支配边界 - for (auto block : orderedBlocks) { - std::unordered_set df; - - // Local DF: 直接后继中不被当前块支配的 - for (auto succ : block->getSuccessors()) { - // 当前块不支配该后继(即不是其直接支配节点) - if (blockAnalysisInfo[succ]->getIdom() != block) { - df.insert(succ); - } - } - - // Up DF: 从支配子树中继承 - for (auto child : blockAnalysisInfo[block]->getSdoms()) { - for (auto w : blockAnalysisInfo[child]->getDomFrontiers()) { - // 如果w不被当前块支配 - if (block != blockAnalysisInfo[w]->getIdom()) { - df.insert(w); - } - } - } - - blockAnalysisInfo[block]->setDomFrontiers(df); - } - } -} - -// ========================== -// dataflow analysis utils -// ========================== - -// 先引用学长的代码 -// TODO: Worklist 增加逆后序遍历机制 -void DataFlowAnalysisUtils::forwardAnalyze(Module *pModule){ - std::map workAnalysis; - for (auto &dataflow : forwardAnalysisList) { - dataflow->init(pModule); - } - - for (const auto &function : pModule->getFunctions()) { - for (auto &dataflow : forwardAnalysisList) { - workAnalysis.emplace(dataflow, false); - } - while (!workAnalysis.empty()) { - for (const auto &block : function.second->getBasicBlocks()) { - for (auto &elem : workAnalysis) { - if (elem.first->analyze(pModule, block.get())) { - elem.second = true; - } - } - } - std::map tmp; - std::remove_copy_if(workAnalysis.begin(), workAnalysis.end(), std::inserter(tmp, tmp.end()), - [](const std::pair &elem) -> bool { return !elem.second; }); - workAnalysis.swap(tmp); - - for (auto &elem : workAnalysis) { - elem.second = false; - } - } - } -} - -void DataFlowAnalysisUtils::backwardAnalyze(Module *pModule) { - std::map workAnalysis; - for (auto &dataflow : backwardAnalysisList) { - dataflow->init(pModule); - } - - for (const auto &function : pModule->getFunctions()) { - for (auto &dataflow : backwardAnalysisList) { - workAnalysis.emplace(dataflow, false); - } - while (!workAnalysis.empty()) { - for (const auto &block : function.second->getBasicBlocks()) { - for (auto &elem : workAnalysis) { - if (elem.first->analyze(pModule, block.get())) { - elem.second = true; - } - } - } - std::map tmp; - std::remove_copy_if(workAnalysis.begin(), workAnalysis.end(), std::inserter(tmp, tmp.end()), - [](const std::pair &elem) -> bool { return !elem.second; }); - workAnalysis.swap(tmp); - - for (auto &elem : workAnalysis) { - elem.second = false; - } - } - } -} - - -std::set ActiveVarAnalysis::getUsedSet(Instruction *inst) { - using Kind = Instruction::Kind; - std::vector operands; - for (const auto &operand : inst->getOperands()) { - operands.emplace_back(dynamic_cast(operand->getValue())); - } - std::set result; - switch (inst->getKind()) { - // phi op - case Kind::kPhi: - case Kind::kCall: - result.insert(std::next(operands.begin()), operands.end()); - break; - case Kind::kCondBr: - result.insert(operands[0]); - break; - case Kind::kBr: - case Kind::kAlloca: - break; - // mem op - case Kind::kStore: - // StoreInst 的第一个操作数是被存储的值,第二个操作数是存储的变量 - // 后续的是可能的数组维度 - result.insert(operands[0]); - result.insert(operands.begin() + 2, operands.end()); - break; - case Kind::kLoad: - case Kind::kLa: { - auto variable = dynamic_cast(operands[0]); - auto global = dynamic_cast(operands[0]); - auto constArray = dynamic_cast(operands[0]); - if ((variable != nullptr && variable->getNumDims() == 0) || (global != nullptr && global->getNumDims() == 0) || - (constArray != nullptr && constArray->getNumDims() == 0)) { - result.insert(operands[0]); - } - result.insert(std::next(operands.begin()), operands.end()); - break; - } - case Kind::kGetSubArray: { - for (unsigned i = 2; i < operands.size(); i++) { - // 数组的维度信息 - result.insert(operands[i]); - } - break; - } - case Kind::kMemset: { - result.insert(std::next(operands.begin()), operands.end()); - break; - } - case Kind::kInvalid: - // Binary - case Kind::kAdd: - case Kind::kSub: - case Kind::kMul: - case Kind::kDiv: - case Kind::kRem: - case Kind::kICmpEQ: - case Kind::kICmpNE: - case Kind::kICmpLT: - case Kind::kICmpLE: - case Kind::kICmpGT: - case Kind::kICmpGE: - case Kind::kFAdd: - case Kind::kFSub: - case Kind::kFMul: - case Kind::kFDiv: - case Kind::kFCmpEQ: - case Kind::kFCmpNE: - case Kind::kFCmpLT: - case Kind::kFCmpLE: - case Kind::kFCmpGT: - case Kind::kFCmpGE: - case Kind::kAnd: - case Kind::kOr: - // Unary - case Kind::kNeg: - case Kind::kNot: - case Kind::kFNot: - case Kind::kFNeg: - case Kind::kFtoI: - case Kind::kItoF: - // terminator - case Kind::kReturn: - result.insert(operands.begin(), operands.end()); - break; - default: - assert(false); - break; - } - result.erase(nullptr); - return result; -} - -User * ActiveVarAnalysis::getDefine(Instruction *inst) { - User *result = nullptr; - if (inst->isStore()) { - StoreInst* store = dynamic_cast(inst); - auto operand = store->getPointer(); - AllocaInst* variable = dynamic_cast(operand); - GlobalValue* global = dynamic_cast(operand); - if ((variable != nullptr && variable->getNumDims() != 0) || (global != nullptr && global->getNumDims() != 0)) { - // 如果是数组变量或者全局变量,则不返回定义 - // TODO:兼容数组变量 - result = nullptr; - } else { - result = dynamic_cast(operand); - } - } else if (inst->isPhi()) { - result = dynamic_cast(inst->getOperand(0)); - } else if (inst->isBinary() || inst->isUnary() || inst->isCall() || - inst->isLoad() || inst->isLa()) { - result = dynamic_cast(inst); - } - return result; -} - -void ActiveVarAnalysis::init(Module *pModule) { - for (const auto &function : pModule->getFunctions()) { - for (const auto &block : function.second->getBasicBlocks()) { - activeTable.emplace(block.get(), std::vector>{}); - for (unsigned i = 0; i < block->getNumInstructions() + 1; i++) - activeTable.at(block.get()).emplace_back(); - } - } -} - -// 活跃变量分析公式 每个块内的分析动作供分析器调用 -bool ActiveVarAnalysis::analyze(Module *pModule, BasicBlock *block) { - bool changed = false; // 标记数据流结果是否有变化 - std::set activeSet{}; // 当前计算的活跃变量集合 - - // 步骤1: 计算基本块出口的活跃变量集 (OUT[B]) - // 公式: OUT[B] = ∪_{S ∈ succ(B)} IN[S] - for (const auto &succ : block->getSuccessors()) { - // 获取后继块入口的活跃变量集 (IN[S]) - auto succActiveSet = activeTable.at(succ).front(); - // 合并所有后继块的入口活跃变量 - activeSet.insert(succActiveSet.begin(), succActiveSet.end()); - } - - // 步骤2: 处理基本块出口处的活跃变量集 - const auto &instructions = block->getInstructions(); - const auto numInstructions = instructions.size(); - - // 获取旧的出口活跃变量集 (block出口对应索引numInstructions) - const auto &oldEndActiveSet = activeTable.at(block)[numInstructions]; - - // 检查出口活跃变量集是否有变化 - if (!std::equal(activeSet.begin(), activeSet.end(), - oldEndActiveSet.begin(), oldEndActiveSet.end())) - { - changed = true; // 标记变化 - activeTable.at(block)[numInstructions] = activeSet; // 更新出口活跃变量集 - } - - // 步骤3: 逆序遍历基本块中的指令 - // 从最后一条指令开始向前计算每个程序点的活跃变量 - auto instructionIter = instructions.end(); - instructionIter--; // 指向最后一条指令 - - // 从出口向入口遍历 (索引从numInstructions递减到1) - for (unsigned i = numInstructions; i > 0; i--) { - auto inst = instructionIter->get(); // 当前指令 - - auto used = getUsedSet(inst); - User *defined = getDefine(inst); - - // 步骤3.3: 计算指令入口的活跃变量 (IN[i]) - // 公式: IN[i] = use_i ∪ (OUT[i] - def_i) - activeSet.erase(defined); // 移除被定义的变量 (OUT[i] - def_i) - activeSet.insert(used.begin(), used.end()); // 添加使用的变量 - - // 获取旧的入口活跃变量集 (位置i-1对应当前指令的入口) - const auto &oldActiveSet = activeTable.at(block)[i - 1]; - - // 检查活跃变量集是否有变化 - if (!std::equal(activeSet.begin(), activeSet.end(), - oldActiveSet.begin(), oldActiveSet.end())) - { - changed = true; // 标记变化 - activeTable.at(block)[i - 1] = activeSet; // 更新入口活跃变量集 - } - - instructionIter--; // 移动到前一条指令 - } - - return changed; // 返回数据流结果是否变化 -} - - - - -} // namespace sysy - diff --git a/src/SysYIRPassManager.cpp b/src/SysYIRPassManager.cpp deleted file mode 100644 index f66f74a..0000000 --- a/src/SysYIRPassManager.cpp +++ /dev/null @@ -1,36 +0,0 @@ -// PassManager.cpp -#include "SysYIRPassManager.h" -#include - -namespace sysy { - -void PassManager::run(Module& M) { - // 首先运行Module级别的Pass - for (auto& pass : modulePasses) { - std::cout << "Running Module Pass: " << pass->getPassName() << std::endl; - pass->runOnModule(M); - } - - // 然后对每个函数运行Function级别的Pass - auto& functions = M.getFunctions(); - for (auto& pair : functions) { - Function& F = *(pair.second); // 获取Function的引用 - std::cout << " Processing Function: " << F.getName() << std::endl; - - // 在每个函数上运行FunctionPasses - bool changedInFunction; - do { - changedInFunction = false; - for (auto& pass : functionPasses) { - // 对于FunctionPasses,可以考虑一个迭代执行的循环,直到稳定 - std::cout << " Running Function Pass: " << pass->getPassName() << std::endl; - changedInFunction |= pass->runOnFunction(F); - } - } while (changedInFunction); // 循环直到函数稳定,这模拟了您SysYCFGOpt的while(changed)逻辑 - } - - // 分析Pass的运行可以在其他Pass需要时触发,或者在特定的PassManager阶段触发 - // 对于依赖于分析结果的Pass,可以在其run方法中通过PassManager::getAnalysis()来获取 -} - -} // namespace sysy \ No newline at end of file diff --git a/src/backend/RISCv64/CMakeLists.txt b/src/backend/RISCv64/CMakeLists.txt new file mode 100644 index 0000000..eb9f37f --- /dev/null +++ b/src/backend/RISCv64/CMakeLists.txt @@ -0,0 +1,23 @@ +# src/backend/RISCv64/CMakeLists.txt +add_library(riscv64_backend_lib STATIC + RISCv64AsmPrinter.cpp + RISCv64Backend.cpp + RISCv64ISel.cpp + RISCv64LLIR.cpp + RISCv64RegAlloc.cpp + Handler/CalleeSavedHandler.cpp + Handler/LegalizeImmediates.cpp + Handler/PrologueEpilogueInsertion.cpp + Optimize/Peephole.cpp + Optimize/PostRA_Scheduler.cpp + Optimize/PreRA_Scheduler.cpp +) + +# 包含后端模块所需的头文件路径 +target_include_directories(riscv64_backend_lib PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR}/../../include/backend/RISCv64 # 后端顶层头文件 + ${CMAKE_CURRENT_SOURCE_DIR}/../../include/backend/RISCv64/Handler # 增加 Handler 头文件路径 + ${CMAKE_CURRENT_SOURCE_DIR}/../../include/backend/RISCv64/Optimize # 增加 Optimize 头文件路径 + ${CMAKE_CURRENT_SOURCE_DIR}/../../include/midend # 增加 midend 头文件路径 (已存在) + ${CMAKE_CURRENT_SOURCE_DIR}/../../include/midend/Pass # 增加 midend 头文件路径 (已存在) +) \ No newline at end of file diff --git a/src/CalleeSavedHandler.cpp b/src/backend/RISCv64/Handler/CalleeSavedHandler.cpp similarity index 100% rename from src/CalleeSavedHandler.cpp rename to src/backend/RISCv64/Handler/CalleeSavedHandler.cpp diff --git a/src/LegalizeImmediates.cpp b/src/backend/RISCv64/Handler/LegalizeImmediates.cpp similarity index 100% rename from src/LegalizeImmediates.cpp rename to src/backend/RISCv64/Handler/LegalizeImmediates.cpp diff --git a/src/PrologueEpilogueInsertion.cpp b/src/backend/RISCv64/Handler/PrologueEpilogueInsertion.cpp similarity index 100% rename from src/PrologueEpilogueInsertion.cpp rename to src/backend/RISCv64/Handler/PrologueEpilogueInsertion.cpp diff --git a/src/RISCv64Peephole.cpp b/src/backend/RISCv64/Optimize/Peephole.cpp similarity index 99% rename from src/RISCv64Peephole.cpp rename to src/backend/RISCv64/Optimize/Peephole.cpp index 16e3a12..936af92 100644 --- a/src/RISCv64Peephole.cpp +++ b/src/backend/RISCv64/Optimize/Peephole.cpp @@ -1,4 +1,4 @@ -#include "RISCv64Peephole.h" +#include "Peephole.h" #include namespace sysy { diff --git a/src/PostRA_Scheduler.cpp b/src/backend/RISCv64/Optimize/PostRA_Scheduler.cpp similarity index 100% rename from src/PostRA_Scheduler.cpp rename to src/backend/RISCv64/Optimize/PostRA_Scheduler.cpp diff --git a/src/PreRA_Scheduler.cpp b/src/backend/RISCv64/Optimize/PreRA_Scheduler.cpp similarity index 100% rename from src/PreRA_Scheduler.cpp rename to src/backend/RISCv64/Optimize/PreRA_Scheduler.cpp diff --git a/src/RISCv64AsmPrinter.cpp b/src/backend/RISCv64/RISCv64AsmPrinter.cpp similarity index 100% rename from src/RISCv64AsmPrinter.cpp rename to src/backend/RISCv64/RISCv64AsmPrinter.cpp diff --git a/src/RISCv64Backend.cpp b/src/backend/RISCv64/RISCv64Backend.cpp similarity index 100% rename from src/RISCv64Backend.cpp rename to src/backend/RISCv64/RISCv64Backend.cpp diff --git a/src/RISCv64ISel.cpp b/src/backend/RISCv64/RISCv64ISel.cpp similarity index 100% rename from src/RISCv64ISel.cpp rename to src/backend/RISCv64/RISCv64ISel.cpp diff --git a/src/RISCv64LLIR.cpp b/src/backend/RISCv64/RISCv64LLIR.cpp similarity index 100% rename from src/RISCv64LLIR.cpp rename to src/backend/RISCv64/RISCv64LLIR.cpp diff --git a/src/RISCv64RegAlloc.cpp b/src/backend/RISCv64/RISCv64RegAlloc.cpp similarity index 100% rename from src/RISCv64RegAlloc.cpp rename to src/backend/RISCv64/RISCv64RegAlloc.cpp diff --git a/src/frontend/CMakeLists.txt b/src/frontend/CMakeLists.txt new file mode 100644 index 0000000..3b522ea --- /dev/null +++ b/src/frontend/CMakeLists.txt @@ -0,0 +1,17 @@ +# src/frontend/CMakeLists.txt +add_library(frontend_lib STATIC + SysYBaseVisitor.cpp + SysY.g4 + SysYLexer.cpp + SysYParser.cpp + SysYVisitor.cpp +) + +# 包含前端模块所需的头文件路径 +target_include_directories(frontend_lib PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR}/../include/frontend # 前端头文件 + ${ANTLR_RUNTIME}/runtime/src # ANTLR 运行时头文件 +) + +# 链接 ANTLR 运行时库 +target_link_libraries(frontend_lib PRIVATE antlr4_shared) \ No newline at end of file diff --git a/src/SysY.g4 b/src/frontend/SysY.g4 similarity index 100% rename from src/SysY.g4 rename to src/frontend/SysY.g4 diff --git a/src/SysYBaseVisitor.cpp b/src/frontend/SysYBaseVisitor.cpp similarity index 100% rename from src/SysYBaseVisitor.cpp rename to src/frontend/SysYBaseVisitor.cpp diff --git a/src/SysYLexer.cpp b/src/frontend/SysYLexer.cpp similarity index 100% rename from src/SysYLexer.cpp rename to src/frontend/SysYLexer.cpp diff --git a/src/SysYParser.cpp b/src/frontend/SysYParser.cpp similarity index 100% rename from src/SysYParser.cpp rename to src/frontend/SysYParser.cpp diff --git a/src/SysYVisitor.cpp b/src/frontend/SysYVisitor.cpp similarity index 100% rename from src/SysYVisitor.cpp rename to src/frontend/SysYVisitor.cpp diff --git a/src/include/AddressCalculationExpansion.h b/src/include/AddressCalculationExpansion.h deleted file mode 100644 index ba6ee6d..0000000 --- a/src/include/AddressCalculationExpansion.h +++ /dev/null @@ -1,59 +0,0 @@ -#pragma once - -#include "IR.h" // 假设IR.h包含了Module, Function, BasicBlock, Instruction, Value, IRBuilder, Type等定义 -#include "IRBuilder.h" // 需要IRBuilder来创建新指令 -#include "SysYIRPrinter.h" // 新增: 用于调试输出 -#include -#include -#include -#include -#include // 用于迭代和修改指令列表 -#include // for std::reverse (if needed, although not used in final version) -#include // MODIFICATION: 用于警告输出 - -namespace sysy { - -/** - * @brief AddressCalculationExpansion Pass - * - * 这是一个IR优化Pass,用于将LoadInst和StoreInst中包含的多维数组索引 - * 显式地转换为IR中的BinaryInst(乘法和加法)序列,并生成带有线性偏移量的 - * LoadInst/StoreInst。 - * - * 目的:确保在寄存器分配之前,所有中间地址计算的结果都有明确的IR指令和对应的虚拟寄存器, - * 从而避免在后端DAG构建时临时创建值而导致寄存器分配缺失的问题。 - * - * SysY语言特性: - * - 无指针类型(所有数组访问的基地址是alloca或global的AllocaType/ArrayType) - * - 数据类型只有int和float,且都占用4字节。 - * - LoadInst和StoreInst直接接受多个索引作为额外操作数。 - */ -class AddressCalculationExpansion { -private: - Module* pModule; - IRBuilder* pBuilder; // 用于在IR中插入新指令 - - // 数组元素的固定大小,根据SysY特性,int和float都是4字节 - static const int ELEMENT_SIZE = 4; - - // 辅助函数:根据数组的维度信息和当前索引的维度,计算该索引的步长(字节数) - // dims: 包含所有维度大小的vector,例如 {2, 3, 4} - // currentDimIndex: 当前正在处理的索引在 dims 中的位置 (0, 1, 2...) - int calculateStride(const std::vector& dims, size_t currentDimIndex) { - int stride = ELEMENT_SIZE; // 最内层元素大小 (4字节) - // 乘以当前维度之后的所有维度的大小 - for (size_t i = currentDimIndex + 1; i < dims.size(); ++i) { - stride *= dims[i]; - } - return stride; - } - -public: - AddressCalculationExpansion(Module* module, IRBuilder* builder) - : pModule(module), pBuilder(builder) {} - - // 运行此Pass - bool run(); -}; - -} // namespace sysy \ No newline at end of file diff --git a/src/include/SysYIRAnalyser.h b/src/include/SysYIRAnalyser.h deleted file mode 100644 index 1837b99..0000000 --- a/src/include/SysYIRAnalyser.h +++ /dev/null @@ -1,465 +0,0 @@ -#pragma once - -#include "IR.h" - -namespace sysy { - -// 前向声明 - -class Loop; -// 基本块分析信息类 -class BlockAnalysisInfo { - -public: - using block_list = std::vector; - using block_set = std::unordered_set; - -protected: - // 支配树相关 - int domdepth = 0; ///< 支配节点所在深度 - BasicBlock* idom = nullptr; ///< 直接支配结点 - block_list sdoms; ///< 支配树后继 - block_set dominants; ///< 必经结点集合 - block_set dominant_frontiers; ///< 支配边界 - - // 后续添加循环分析相关 - // Loop* loopbelong = nullptr; ///< 所属循环 - // int loopdepth = 0; ///< 循环深度 - -public: - // getterface - const int getDomDepth() const { return domdepth; } - const BasicBlock* getIdom() const { return idom; } - const block_list& getSdoms() const { return sdoms; } - const block_set& getDominants() const { return dominants; } - const block_set& getDomFrontiers() const { return dominant_frontiers; } - - // 支配树操作 - void setDomDepth(int depth) { domdepth = depth; } - void setIdom(BasicBlock* block) { idom = block; } - void addSdoms(BasicBlock* block) { sdoms.push_back(block); } - void clearSdoms() { sdoms.clear(); } - void removeSdoms(BasicBlock* block) { - sdoms.erase(std::remove(sdoms.begin(), sdoms.end(), block), sdoms.end()); - } - void addDominants(BasicBlock* block) { dominants.emplace(block); } - void addDominants(const block_set& blocks) { dominants.insert(blocks.begin(), blocks.end()); } - void setDominants(BasicBlock* block) { - dominants.clear(); - addDominants(block); - } - void setDominants(const block_set& doms) { - dominants = doms; - } - void setDomFrontiers(const block_set& df) { - dominant_frontiers = df; - } - - // TODO:循环分析操作方法 - - // 清空所有分析信息 - void clear() { - domdepth = -1; - idom = nullptr; - sdoms.clear(); - dominants.clear(); - dominant_frontiers.clear(); - // loopbelong = nullptr; - // loopdepth = 0; - } -}; - -// 函数分析信息类 -class FunctionAnalysisInfo { - - -public: - // 函数属性 - enum FunctionAttribute : uint64_t { - PlaceHolder = 0x0UL, - Pure = 0x1UL << 0, - SelfRecursive = 0x1UL << 1, - SideEffect = 0x1UL << 2, - NoPureCauseMemRead = 0x1UL << 3 - }; - - // 数据结构 - using Loop_list = std::list>; - using block_loop_map = std::unordered_map; - using value_block_map = std::unordered_map; - using value_block_count_map = std::unordered_map>; - - // 分析数据 - FunctionAttribute attribute = PlaceHolder; ///< 函数属性 - std::set callees; ///< 函数调用集合 - Loop_list loops; ///< 所有循环 - Loop_list topLoops; ///< 顶层循环 - // block_loop_map basicblock2Loop; ///< 基本块到循环映射 - std::list> indirectAllocas; ///< 间接分配内存 - - // 值定义/使用信息 - value_block_map value2AllocBlocks; ///< 值分配位置映射 - value_block_count_map value2DefBlocks; ///< 值定义位置映射 - value_block_count_map value2UseBlocks; ///< 值使用位置映射 - - // 函数属性操作 - FunctionAttribute getAttribute() const { return attribute; } - void setAttribute(FunctionAttribute attr) { attribute = static_cast(attribute | attr); } - void clearAttribute() { attribute = PlaceHolder; } - - // 调用关系操作 - void addCallee(Function* callee) { callees.insert(callee); } - void removeCallee(Function* callee) { callees.erase(callee); } - void clearCallees() { callees.clear(); } - - - // 值-块映射操作 - BasicBlock* getAllocBlockByValue(Value* value) { - auto it = value2AllocBlocks.find(value); - return it != value2AllocBlocks.end() ? it->second : nullptr; - } - std::unordered_set getDefBlocksByValue(Value *value) { - std::unordered_set blocks; - if (value2DefBlocks.count(value) > 0) { - for (const auto &pair : value2DefBlocks[value]) { - blocks.insert(pair.first); - } - } - return blocks; - } - std::unordered_set getUseBlocksByValue(Value *value) { - std::unordered_set blocks; - if (value2UseBlocks.count(value) > 0) { - for (const auto &pair : value2UseBlocks[value]) { - blocks.insert(pair.first); - } - } - return blocks; - } - - // 值定义/使用操作 - void addValue2AllocBlocks(Value* value, BasicBlock* block) { value2AllocBlocks[value] = block; } - void addValue2DefBlocks(Value* value, BasicBlock* block) { ++value2DefBlocks[value][block]; } - void addValue2UseBlocks(Value* value, BasicBlock* block) { ++value2UseBlocks[value][block]; } - - - // 获取值定义/使用信息 - std::unordered_map& getValue2AllocBlocks() { - return value2AllocBlocks; - } - std::unordered_map>& getValue2DefBlocks() { - return value2DefBlocks; - } - std::unordered_map>& getValue2UseBlocks() { - return value2UseBlocks; - } - std::unordered_set getValuesOfDefBlock() { - std::unordered_set values; - for (const auto &pair : value2DefBlocks) { - values.insert(pair.first); - } - return values; - } - - // 删除信息操作 - void removeValue2AllocBlock(Value *value) { value2AllocBlocks.erase(value); } - bool removeValue2DefBlock(Value *value, BasicBlock *block) { - bool changed = false; - if (--value2DefBlocks[value][block] == 0) { - value2DefBlocks[value].erase(block); - if (value2DefBlocks[value].empty()) { - value2DefBlocks.erase(value); - changed = true; - } - } - return changed; - } - bool removeValue2UseBlock(Value *value, BasicBlock *block) { - bool changed = false; - if (--value2UseBlocks[value][block] == 0) { - value2UseBlocks[value].erase(block); - if (value2UseBlocks[value].empty()) { - value2UseBlocks.erase(value); - changed = true; - } - } - return changed; - } - - // 间接分配操作 - void addIndirectAlloca(AllocaInst* alloca) { indirectAllocas.emplace_back(alloca); } - std::list>& getIndirectAllocas() { return indirectAllocas; } - - // TODO:循环分析操作 - - // 清空所有分析信息 - void clear() { - attribute = PlaceHolder; - callees.clear(); - loops.clear(); - topLoops.clear(); - // basicblock2Loop.clear(); - indirectAllocas.clear(); - value2AllocBlocks.clear(); - value2DefBlocks.clear(); - value2UseBlocks.clear(); - } -}; -// 循环类 - 未实现优化 -class Loop { -public: - using block_list = std::vector; - using block_set = std::unordered_set; - using Loop_list = std::vector; - -protected: - Function *parent; // 所属函数 - block_list blocksInLoop; // 循环内的基本块 - BasicBlock *preheaderBlock = nullptr; // 前驱块 - BasicBlock *headerBlock = nullptr; // 循环头 - block_list latchBlock; // 回边块 - block_set exitingBlocks; // 退出块 - block_set exitBlocks; // 退出目标块 - Loop *parentloop = nullptr; // 父循环 - Loop_list subLoops; // 子循环 - size_t loopID; // 循环ID - unsigned loopDepth; // 循环深度 - - Instruction *indCondVar = nullptr; // 循环条件变量 - Instruction::Kind IcmpKind; // 比较类型 - Value *indEnd = nullptr; // 循环结束值 - AllocaInst *IndPhi = nullptr; // 循环变量 - - ConstantValue *indBegin = nullptr; // 循环起始值 - ConstantValue *indStep = nullptr; // 循环步长 - - std::set GlobalValuechange; // 循环内改变的全局变量 - - int StepType = 0; // 循环步长类型 - bool parallelable = false; // 是否可并行 - -public: - explicit Loop(BasicBlock *header, const std::string &name = "") - : headerBlock(header) { - blocksInLoop.push_back(header); - } - - void setloopID() { - static unsigned loopCount = 0; - loopCount = loopCount + 1; - loopID = loopCount; - } - ConstantValue* getindBegin() { return indBegin; } - ConstantValue* getindStep() { return indStep; } - void setindBegin(ConstantValue *indBegin2set) { indBegin = indBegin2set; } - void setindStep(ConstantValue *indStep2set) { indStep = indStep2set; } - void setStepType(int StepType2Set) { StepType = StepType2Set; } - int getStepType() { return StepType; } - size_t getLoopID() { return loopID; } - - BasicBlock* getHeader() const { return headerBlock; } - BasicBlock* getPreheaderBlock() const { return preheaderBlock; } - block_list& getLatchBlocks() { return latchBlock; } - block_set& getExitingBlocks() { return exitingBlocks; } - block_set& getExitBlocks() { return exitBlocks; } - Loop* getParentLoop() const { return parentloop; } - void setParentLoop(Loop *parent) { parentloop = parent; } - void addBasicBlock(BasicBlock *bb) { blocksInLoop.push_back(bb); } - void addSubLoop(Loop *loop) { subLoops.push_back(loop); } - void setLoopDepth(unsigned depth) { loopDepth = depth; } - block_list& getBasicBlocks() { return blocksInLoop; } - Loop_list& getSubLoops() { return subLoops; } - unsigned getLoopDepth() const { return loopDepth; } - - bool isLoopContainsBasicBlock(BasicBlock *bb) const { - return std::find(blocksInLoop.begin(), blocksInLoop.end(), bb) != blocksInLoop.end(); - } - - void addExitingBlock(BasicBlock *bb) { exitingBlocks.insert(bb); } - void addExitBlock(BasicBlock *bb) { exitBlocks.insert(bb); } - void addLatchBlock(BasicBlock *bb) { latchBlock.push_back(bb); } - void setPreheaderBlock(BasicBlock *bb) { preheaderBlock = bb; } - - void setIndexCondInstr(Instruction *instr) { indCondVar = instr; } - void setIcmpKind(Instruction::Kind kind) { IcmpKind = kind; } - Instruction::Kind getIcmpKind() const { return IcmpKind; } - - bool isSimpleLoopInvariant(Value *value) ; - - void setIndEnd(Value *value) { indEnd = value; } - void setIndPhi(AllocaInst *phi) { IndPhi = phi; } - Value* getIndEnd() const { return indEnd; } - AllocaInst* getIndPhi() const { return IndPhi; } - Instruction* getIndCondVar() const { return indCondVar; } - - void addGlobalValuechange(GlobalValue *globalvaluechange2add) { - GlobalValuechange.insert(globalvaluechange2add); - } - std::set& getGlobalValuechange() { - return GlobalValuechange; - } - - void setParallelable(bool flag) { parallelable = flag; } - bool isParallelable() const { return parallelable; } -}; - -// 控制流分析类 -class ControlFlowAnalysis { -private: - Module *pModule; ///< 模块 - std::unordered_map blockAnalysisInfo; // 基本块分析信息表 - std::unordered_map functionAnalysisInfo; // 函数分析信息 - -public: - explicit ControlFlowAnalysis(Module *pMoudle) : pModule(pMoudle) {} - - // 获取基本块分析信息 - BlockAnalysisInfo* getBlockAnalysisInfo(BasicBlock *block) { - auto it = blockAnalysisInfo.find(block); - if (it != blockAnalysisInfo.end()) { - return it->second; - } - return nullptr; // 如果未找到,返回nullptr - } - FunctionAnalysisInfo* getFunctionAnalysisInfo(Function *func) { - auto it = functionAnalysisInfo.find(func); - if (it != functionAnalysisInfo.end()) { - return it->second; - } - return nullptr; // 如果未找到,返回nullptr - } - - void init(); // 初始化分析器 - void computeDomNode(); // 计算必经结点 - void computeDomTree(); // 构造支配树 - // std::unordered_set computeDomFrontier(BasicBlock *block) ; // 计算单个块的支配边界(弃用) - void computeDomFrontierAllBlk(); // 计算所有块的支配边界 - void runControlFlowAnalysis(); // 运行控制流分析(主要是支配树和支配边界) - void clear(){ - for (auto &pair : blockAnalysisInfo) { - delete pair.second; // 清理基本块分析信息 - } - blockAnalysisInfo.clear(); - - for (auto &pair : functionAnalysisInfo) { - delete pair.second; // 清理函数分析信息 - } - functionAnalysisInfo.clear(); - } // 清空分析结果 - ~ControlFlowAnalysis() { - clear(); // 析构时清理所有分析信息 - } - -private: - void intersectOP4Dom(std::unordered_set &dom, const std::unordered_set &other); // 交集运算, - BasicBlock* findCommonDominator(BasicBlock *a, BasicBlock *b); // 查找两个基本块的共同支配结点 -}; - -// 数据流分析类 -// 该类为抽象类,具体的数据流分析器需要继承此类 -// 因为每个数据流分析器的分析动作都不一样,所以需要继承并实现analyze方法 -class DataFlowAnalysis { - public: - virtual ~DataFlowAnalysis() = default; - - public: - virtual void init(Module *pModule) {} ///< 分析器初始化 - virtual auto analyze(Module *pModule, BasicBlock *block) -> bool { return true; } ///< 分析动作,若完成则返回true; - virtual void clear() {} ///< 清空 -}; - -// 数据流分析工具类 -// 该类用于管理多个数据流分析器,提供统一的前向与后向分析接口 -class DataFlowAnalysisUtils { -private: - std::vector forwardAnalysisList; ///< 前向分析器列表 - std::vector backwardAnalysisList; ///< 后向分析器列表 - -public: - DataFlowAnalysisUtils() = default; - ~DataFlowAnalysisUtils() { - clear(); // 析构时清理所有分析器 - } - // 统一添加接口 - void addAnalyzers( - std::vector forwardList, - std::vector backwardList = {}) - { - forwardAnalysisList.insert( - forwardAnalysisList.end(), - forwardList.begin(), - forwardList.end()); - - backwardAnalysisList.insert( - backwardAnalysisList.end(), - backwardList.begin(), - backwardList.end()); - } - - // 单独添加接口 - void addForwardAnalyzer(DataFlowAnalysis *analyzer) { - forwardAnalysisList.push_back(analyzer); - } - - void addBackwardAnalyzer(DataFlowAnalysis *analyzer) { - backwardAnalysisList.push_back(analyzer); - } - - // 设置分析器列表 - void setAnalyzers( - std::vector forwardList, - std::vector backwardList) - { - forwardAnalysisList = std::move(forwardList); - backwardAnalysisList = std::move(backwardList); - } - - // 清空列表 - void clear() { - forwardAnalysisList.clear(); - backwardAnalysisList.clear(); - } - - // 访问器 - const auto& getForwardAnalyzers() const { return forwardAnalysisList; } - const auto& getBackwardAnalyzers() const { return backwardAnalysisList; } - -public: - void forwardAnalyze(Module *pModule); ///< 执行前向分析 - void backwardAnalyze(Module *pModule); ///< 执行后向分析 -}; - -// 活跃变量分析类 -// 提供def - use分析 -// 未兼容数组变量但是考虑了维度的use信息 -class ActiveVarAnalysis : public DataFlowAnalysis { - private: - std::map>> activeTable; ///< 活跃信息表,存储每个基本块内的的活跃变量信息 - - public: - ActiveVarAnalysis() = default; - ~ActiveVarAnalysis() override = default; - - public: - static std::set getUsedSet(Instruction *inst); - static User* getDefine(Instruction *inst); - - public: - void init(Module *pModule) override; - bool analyze(Module *pModule, BasicBlock *block) override; - // 外部活跃信息表访问器 - const std::map>> &getActiveTable() const; - void clear() override { - activeTable.clear(); // 清空活跃信息表 - } -}; - -// 分析管理器 后续实现 -// class AnalysisManager { - -// }; - - - - -} // namespace sysy \ No newline at end of file diff --git a/src/include/SysYIRPassManager.h b/src/include/SysYIRPassManager.h deleted file mode 100644 index 310b50f..0000000 --- a/src/include/SysYIRPassManager.h +++ /dev/null @@ -1,58 +0,0 @@ -// PassManager.h -#pragma once - -#include -#include -#include // For std::type_index -#include -#include "SysYIRPass.h" -#include "IR.h" // 假设你的IR.h定义了Module, Function等 - -namespace sysy { - -class PassManager { -public: - PassManager() = default; - - // 添加一个FunctionPass - void addPass(std::unique_ptr pass) { - functionPasses.push_back(std::move(pass)); - } - - // 添加一个ModulePass - void addPass(std::unique_ptr pass) { - modulePasses.push_back(std::move(pass)); - } - - // 添加一个AnalysisPass - template - T* addAnalysisPass(Args&&... args) { - static_assert(std::is_base_of::value, "T must derive from AnalysisPass"); - auto analysis = std::make_unique(std::forward(args)...); - T* rawPtr = analysis.get(); - analysisPasses[std::type_index(typeid(T))] = std::move(analysis); - return rawPtr; - } - - // 获取分析结果(用于其他Pass访问) - template - T* getAnalysis() { - static_assert(std::is_base_of::value, "T must derive from AnalysisPass"); - auto it = analysisPasses.find(std::type_index(typeid(T))); - if (it != analysisPasses.end()) { - return static_cast(it->second.get()); - } - return nullptr; // 或者抛出异常 - } - - // 运行所有注册的遍 - void run(Module& M); - -private: - std::vector> functionPasses; - std::vector> modulePasses; - std::unordered_map> analysisPasses; - // 未来可以添加AnalysisPass的缓存机制 -}; - -} // namespace sysy \ No newline at end of file diff --git a/src/include/CalleeSavedHandler.h b/src/include/backend/RISCv64/Handler/CalleeSavedHandler.h similarity index 100% rename from src/include/CalleeSavedHandler.h rename to src/include/backend/RISCv64/Handler/CalleeSavedHandler.h diff --git a/src/include/LegalizeImmediates.h b/src/include/backend/RISCv64/Handler/LegalizeImmediates.h similarity index 100% rename from src/include/LegalizeImmediates.h rename to src/include/backend/RISCv64/Handler/LegalizeImmediates.h diff --git a/src/include/PrologueEpilogueInsertion.h b/src/include/backend/RISCv64/Handler/PrologueEpilogueInsertion.h similarity index 100% rename from src/include/PrologueEpilogueInsertion.h rename to src/include/backend/RISCv64/Handler/PrologueEpilogueInsertion.h diff --git a/src/include/RISCv64Peephole.h b/src/include/backend/RISCv64/Optimize/Peephole.h similarity index 100% rename from src/include/RISCv64Peephole.h rename to src/include/backend/RISCv64/Optimize/Peephole.h diff --git a/src/include/PostRA_Scheduler.h b/src/include/backend/RISCv64/Optimize/PostRA_Scheduler.h similarity index 100% rename from src/include/PostRA_Scheduler.h rename to src/include/backend/RISCv64/Optimize/PostRA_Scheduler.h diff --git a/src/include/PreRA_Scheduler.h b/src/include/backend/RISCv64/Optimize/PreRA_Scheduler.h similarity index 100% rename from src/include/PreRA_Scheduler.h rename to src/include/backend/RISCv64/Optimize/PreRA_Scheduler.h diff --git a/src/include/RISCv64AsmPrinter.h b/src/include/backend/RISCv64/RISCv64AsmPrinter.h similarity index 100% rename from src/include/RISCv64AsmPrinter.h rename to src/include/backend/RISCv64/RISCv64AsmPrinter.h diff --git a/src/include/RISCv64Backend.h b/src/include/backend/RISCv64/RISCv64Backend.h similarity index 100% rename from src/include/RISCv64Backend.h rename to src/include/backend/RISCv64/RISCv64Backend.h diff --git a/src/include/RISCv64ISel.h b/src/include/backend/RISCv64/RISCv64ISel.h similarity index 100% rename from src/include/RISCv64ISel.h rename to src/include/backend/RISCv64/RISCv64ISel.h diff --git a/src/include/RISCv64LLIR.h b/src/include/backend/RISCv64/RISCv64LLIR.h similarity index 100% rename from src/include/RISCv64LLIR.h rename to src/include/backend/RISCv64/RISCv64LLIR.h diff --git a/src/include/RISCv64Passes.h b/src/include/backend/RISCv64/RISCv64Passes.h similarity index 91% rename from src/include/RISCv64Passes.h rename to src/include/backend/RISCv64/RISCv64Passes.h index 4888589..de08882 100644 --- a/src/include/RISCv64Passes.h +++ b/src/include/backend/RISCv64/RISCv64Passes.h @@ -2,7 +2,7 @@ #define RISCV64_PASSES_H #include "RISCv64LLIR.h" -#include "RISCv64Peephole.h" +#include "Peephole.h" #include "PreRA_Scheduler.h" #include "PostRA_Scheduler.h" #include "CalleeSavedHandler.h" diff --git a/src/include/RISCv64RegAlloc.h b/src/include/backend/RISCv64/RISCv64RegAlloc.h similarity index 100% rename from src/include/RISCv64RegAlloc.h rename to src/include/backend/RISCv64/RISCv64RegAlloc.h diff --git a/src/include/SysYBaseVisitor.h b/src/include/frontend/SysYBaseVisitor.h similarity index 100% rename from src/include/SysYBaseVisitor.h rename to src/include/frontend/SysYBaseVisitor.h diff --git a/src/include/SysYLexer.h b/src/include/frontend/SysYLexer.h similarity index 100% rename from src/include/SysYLexer.h rename to src/include/frontend/SysYLexer.h diff --git a/src/include/SysYParser.h b/src/include/frontend/SysYParser.h similarity index 100% rename from src/include/SysYParser.h rename to src/include/frontend/SysYParser.h diff --git a/src/include/SysYVisitor.h b/src/include/frontend/SysYVisitor.h similarity index 100% rename from src/include/SysYVisitor.h rename to src/include/frontend/SysYVisitor.h diff --git a/src/include/IR.h b/src/include/midend/IR.h similarity index 100% rename from src/include/IR.h rename to src/include/midend/IR.h diff --git a/src/include/IRBuilder.h b/src/include/midend/IRBuilder.h similarity index 100% rename from src/include/IRBuilder.h rename to src/include/midend/IRBuilder.h diff --git a/src/include/Dom.h b/src/include/midend/Pass/Analysis/Dom.h similarity index 100% rename from src/include/Dom.h rename to src/include/midend/Pass/Analysis/Dom.h diff --git a/src/include/Liveness.h b/src/include/midend/Pass/Analysis/Liveness.h similarity index 100% rename from src/include/Liveness.h rename to src/include/midend/Pass/Analysis/Liveness.h diff --git a/src/include/DCE.h b/src/include/midend/Pass/Optimize/DCE.h similarity index 100% rename from src/include/DCE.h rename to src/include/midend/Pass/Optimize/DCE.h diff --git a/src/include/Mem2Reg.h b/src/include/midend/Pass/Optimize/Mem2Reg.h similarity index 100% rename from src/include/Mem2Reg.h rename to src/include/midend/Pass/Optimize/Mem2Reg.h diff --git a/src/include/Reg2Mem.h b/src/include/midend/Pass/Optimize/Reg2Mem.h similarity index 100% rename from src/include/Reg2Mem.h rename to src/include/midend/Pass/Optimize/Reg2Mem.h diff --git a/src/include/SCCP.h b/src/include/midend/Pass/Optimize/SCCP.h similarity index 100% rename from src/include/SCCP.h rename to src/include/midend/Pass/Optimize/SCCP.h diff --git a/src/include/SysYIRCFGOpt.h b/src/include/midend/Pass/Optimize/SysYIRCFGOpt.h similarity index 100% rename from src/include/SysYIRCFGOpt.h rename to src/include/midend/Pass/Optimize/SysYIRCFGOpt.h diff --git a/src/include/SysYIROptUtils.h b/src/include/midend/Pass/Optimize/SysYIROptUtils.h similarity index 100% rename from src/include/SysYIROptUtils.h rename to src/include/midend/Pass/Optimize/SysYIROptUtils.h diff --git a/src/include/Pass.h b/src/include/midend/Pass/Pass.h similarity index 100% rename from src/include/Pass.h rename to src/include/midend/Pass/Pass.h diff --git a/src/include/SysYIRGenerator.h b/src/include/midend/SysYIRGenerator.h similarity index 100% rename from src/include/SysYIRGenerator.h rename to src/include/midend/SysYIRGenerator.h diff --git a/src/include/SysYIRPrinter.h b/src/include/midend/SysYIRPrinter.h similarity index 100% rename from src/include/SysYIRPrinter.h rename to src/include/midend/SysYIRPrinter.h diff --git a/src/include/range.h b/src/include/midend/range.h similarity index 100% rename from src/include/range.h rename to src/include/midend/range.h diff --git a/src/midend/CMakeLists.txt b/src/midend/CMakeLists.txt new file mode 100644 index 0000000..4830893 --- /dev/null +++ b/src/midend/CMakeLists.txt @@ -0,0 +1,23 @@ +# src/midend/CMakeLists.txt +add_library(midend_lib STATIC + IR.cpp + SysYIRGenerator.cpp + SysYIRPrinter.cpp + Pass/Pass.cpp + Pass/Analysis/Dom.cpp + Pass/Analysis/Liveness.cpp + Pass/Optimize/DCE.cpp + Pass/Optimize/Mem2Reg.cpp + Pass/Optimize/Reg2Mem.cpp + Pass/Optimize/SysYIRCFGOpt.cpp +) + +# 包含中端模块所需的头文件路径 +target_include_directories(midend_lib PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR}/../include/midend # 中端顶层头文件 + ${CMAKE_CURRENT_SOURCE_DIR}/../include/midend/Pass # 增加 Pass 头文件路径 + ${CMAKE_CURRENT_SOURCE_DIR}/../include/midend/Pass/Analysis # 增加 Pass/Analysis 头文件路径 + ${CMAKE_CURRENT_SOURCE_DIR}/../include/midend/Pass/Optimize # 增加 Pass/Optimize 头文件路径 + ${CMAKE_CURRENT_SOURCE_DIR}/../include/frontend # 增加 frontend 头文件路径 (已存在) + ${ANTLR_RUNTIME}/runtime/src # ANTLR运行时库头文件 +) \ No newline at end of file diff --git a/src/IR.cpp b/src/midend/IR.cpp similarity index 100% rename from src/IR.cpp rename to src/midend/IR.cpp diff --git a/src/Dom.cpp b/src/midend/Pass/Analysis/Dom.cpp similarity index 100% rename from src/Dom.cpp rename to src/midend/Pass/Analysis/Dom.cpp diff --git a/src/Liveness.cpp b/src/midend/Pass/Analysis/Liveness.cpp similarity index 100% rename from src/Liveness.cpp rename to src/midend/Pass/Analysis/Liveness.cpp diff --git a/src/DCE.cpp b/src/midend/Pass/Optimize/DCE.cpp similarity index 100% rename from src/DCE.cpp rename to src/midend/Pass/Optimize/DCE.cpp diff --git a/src/Mem2Reg.cpp b/src/midend/Pass/Optimize/Mem2Reg.cpp similarity index 100% rename from src/Mem2Reg.cpp rename to src/midend/Pass/Optimize/Mem2Reg.cpp diff --git a/src/Reg2Mem.cpp b/src/midend/Pass/Optimize/Reg2Mem.cpp similarity index 100% rename from src/Reg2Mem.cpp rename to src/midend/Pass/Optimize/Reg2Mem.cpp diff --git a/src/SysYIRCFGOpt.cpp b/src/midend/Pass/Optimize/SysYIRCFGOpt.cpp similarity index 100% rename from src/SysYIRCFGOpt.cpp rename to src/midend/Pass/Optimize/SysYIRCFGOpt.cpp diff --git a/src/Pass.cpp b/src/midend/Pass/Pass.cpp similarity index 100% rename from src/Pass.cpp rename to src/midend/Pass/Pass.cpp diff --git a/src/SysYIRGenerator.cpp b/src/midend/SysYIRGenerator.cpp similarity index 88% rename from src/SysYIRGenerator.cpp rename to src/midend/SysYIRGenerator.cpp index 2fa2be8..38fa52a 100644 --- a/src/SysYIRGenerator.cpp +++ b/src/midend/SysYIRGenerator.cpp @@ -94,7 +94,11 @@ std::any SysYIRGenerator::visitGlobalConstDecl(SysYParser::GlobalConstDeclContex Utils::tree2Array(type, root, dims, dims.size(), values, &builder); delete root; // 创建全局常量变量,并更新符号表 - module->createConstVar(name, Type::getPointerType(type), values, dims); + Type* variableType = type; + if (!dims.empty()) { // 如果有维度,说明是数组 + variableType = buildArrayType(type, dims); // 构建完整的 ArrayType + } + module->createConstVar(name, Type::getPointerType(variableType), values, dims); } return std::any(); } @@ -145,7 +149,12 @@ std::any SysYIRGenerator::visitConstDecl(SysYParser::ConstDeclContext *ctx){ Utils::tree2Array(type, root, dims, dims.size(), values, &builder); delete root; - module->createConstVar(name, Type::getPointerType(type), values, dims); + // 创建局部常量,并更新符号表 + Type* variableType = type; + if (!dims.empty()) { + variableType = buildArrayType(type, dims); // 构建完整的 ArrayType + } + module->createConstVar(name, Type::getPointerType(variableType), values, dims); } return 0; } @@ -518,12 +527,25 @@ std::any SysYIRGenerator::visitAssignStmt(SysYParser::AssignStmtContext *ctx) { Type* RType = RValue->getType(); if (LType != RType) { - ConstantValue * constValue = dynamic_cast(RValue); + ConstantValue *constValue = dynamic_cast(RValue); if (constValue != nullptr) { if (LType == Type::getFloatType()) { - RValue = ConstantFloating::get(static_cast(constValue->getFloat())); + if(dynamic_cast(constValue)) { + // 如果是整型常量,转换为浮点型 + RValue = ConstantFloating::get(static_cast(constValue->getInt())); + } else if (dynamic_cast(constValue)) { + // 如果是浮点型常量,直接使用 + RValue = ConstantFloating::get(static_cast(constValue->getFloat())); + } } else { // 假设如果不是浮点型,就是整型 + if(dynamic_cast(constValue)) { + // 如果是浮点型常量,转换为整型 + RValue = ConstantInteger::get(static_cast(constValue->getFloat())); + } else if (dynamic_cast(constValue)) { + // 如果是整型常量,直接使用 RValue = ConstantInteger::get(static_cast(constValue->getInt())); + + } } } else { if (LType == Type::getFloatType()) { @@ -712,22 +734,34 @@ std::any SysYIRGenerator::visitReturnStmt(SysYParser::ReturnStmtContext *ctx) { } Type* funcType = builder.getBasicBlock()->getParent()->getReturnType(); - if (returnValue != nullptr && funcType!= returnValue->getType()) { - ConstantValue * constValue = dynamic_cast(returnValue); - if (constValue != nullptr) { - if (funcType == Type::getFloatType()) { - returnValue = ConstantInteger::get(static_cast(constValue->getInt())); - } else { - returnValue = ConstantFloating::get(static_cast(constValue->getFloat())); + if (returnValue != nullptr && funcType!= returnValue->getType()) { + ConstantValue * constValue = dynamic_cast(returnValue); + if (constValue != nullptr) { + if (funcType == Type::getFloatType()) { + if(dynamic_cast(constValue)) { + // 如果是整型常量,转换为浮点型 + returnValue = ConstantFloating::get(static_cast(constValue->getInt())); + } else if (dynamic_cast(constValue)) { + // 如果是浮点型常量,直接使用 + returnValue = ConstantFloating::get(static_cast(constValue->getInt())); } } else { - if (funcType == Type::getFloatType()) { - returnValue = builder.createIToFInst(returnValue); - } else { - returnValue = builder.createFtoIInst(returnValue); + if(dynamic_cast(constValue)) { + // 如果是浮点型常量,转换为整型 + returnValue = ConstantInteger::get(static_cast(constValue->getFloat())); + } else if (dynamic_cast(constValue)) { + // 如果是整型常量,直接使用 + returnValue = ConstantInteger::get(static_cast(constValue->getFloat())); } } + } else { + if (funcType == Type::getFloatType()) { + returnValue = builder.createIToFInst(returnValue); + } else { + returnValue = builder.createFtoIInst(returnValue); + } } + } builder.createReturnInst(returnValue); return std::any(); @@ -1045,20 +1079,34 @@ std::any SysYIRGenerator::visitMulExp(SysYParser::MulExpContext *ctx) { // 如果有一个操作数是浮点数,则将两个操作数都转换为浮点数 if (operandType != floatType) { ConstantValue * constValue = dynamic_cast(operand); - if (constValue != nullptr) - operand = ConstantFloating::get(static_cast(constValue->getInt())); + if (constValue != nullptr) { + if(dynamic_cast(constValue)) { + // 如果是整型常量,转换为浮点型 + operand = ConstantFloating::get(static_cast(constValue->getInt())); + } else if (dynamic_cast(constValue)) { + // 如果是浮点型常量,直接使用 + operand = ConstantFloating::get(static_cast(constValue->getFloat())); + } + } else operand = builder.createIToFInst(operand); } else if (resultType != floatType) { ConstantValue* constResult = dynamic_cast(result); - if (constResult != nullptr) - result = ConstantFloating::get(static_cast(constResult->getInt())); - else + if (constResult != nullptr) { + if(dynamic_cast(constResult)) { + // 如果是整型常量,转换为浮点型 + result = ConstantFloating::get(static_cast(constResult->getInt())); + } else if (dynamic_cast(constResult)) { + // 如果是浮点型常量,直接使用 + result = ConstantFloating::get(static_cast(constResult->getFloat())); + } + } + else result = builder.createIToFInst(result); } - ConstantValue* constResult = dynamic_cast(result); - ConstantValue* constOperand = dynamic_cast(operand); + ConstantFloating* constResult = dynamic_cast(result); + ConstantFloating* constOperand = dynamic_cast(operand); if (opType == SysYParser::MUL) { if ((constOperand != nullptr) && (constResult != nullptr)) { result = ConstantFloating::get(constResult->getFloat() * @@ -1079,8 +1127,8 @@ std::any SysYIRGenerator::visitMulExp(SysYParser::MulExpContext *ctx) { assert(false); } } else { - ConstantValue * constResult = dynamic_cast(result); - ConstantValue * constOperand = dynamic_cast(operand); + ConstantInteger *constResult = dynamic_cast(result); + ConstantInteger *constOperand = dynamic_cast(operand); if (opType == SysYParser::MUL) { if ((constOperand != nullptr) && (constResult != nullptr)) result = ConstantInteger::get(constResult->getInt() * constOperand->getInt()); @@ -1120,20 +1168,34 @@ std::any SysYIRGenerator::visitAddExp(SysYParser::AddExpContext *ctx) { // 类型转换 if (operandType != floatType) { ConstantValue * constOperand = dynamic_cast(operand); - if (constOperand != nullptr) - operand = ConstantFloating::get(static_cast(constOperand->getInt())); + if (constOperand != nullptr) { + if(dynamic_cast(constOperand)) { + // 如果是整型常量,转换为浮点型 + operand = ConstantFloating::get(static_cast(constOperand->getInt())); + } else if (dynamic_cast(constOperand)) { + // 如果是浮点型常量,直接使用 + operand = ConstantFloating::get(static_cast(constOperand->getFloat())); + } + } else operand = builder.createIToFInst(operand); } else if (resultType != floatType) { ConstantValue * constResult = dynamic_cast(result); - if (constResult != nullptr) - result = ConstantFloating::get(static_cast(constResult->getInt())); + if (constResult != nullptr) { + if(dynamic_cast(constResult)) { + // 如果是整型常量,转换为浮点型 + result = ConstantFloating::get(static_cast(constResult->getInt())); + } else if (dynamic_cast(constResult)) { + // 如果是浮点型常量,直接使用 + result = ConstantFloating::get(static_cast(constResult->getFloat())); + } + } else result = builder.createIToFInst(result); } - ConstantValue * constResult = dynamic_cast(result); - ConstantValue * constOperand = dynamic_cast(operand); + ConstantFloating *constResult = dynamic_cast(result); + ConstantFloating *constOperand = dynamic_cast(operand); if (opType == SysYParser::ADD) { if ((constResult != nullptr) && (constOperand != nullptr)) result = ConstantFloating::get(constResult->getFloat() + constOperand->getFloat()); @@ -1146,8 +1208,8 @@ std::any SysYIRGenerator::visitAddExp(SysYParser::AddExpContext *ctx) { result = builder.createFSubInst(result, operand); } } else { - ConstantValue * constResult = dynamic_cast(result); - ConstantValue * constOperand = dynamic_cast(operand); + ConstantInteger *constResult = dynamic_cast(result); + ConstantInteger *constOperand = dynamic_cast(operand); if (opType == SysYParser::ADD) { if ((constResult != nullptr) && (constOperand != nullptr)) result = ConstantInteger::get(constResult->getInt() + constOperand->getInt()); @@ -1201,15 +1263,29 @@ std::any SysYIRGenerator::visitRelExp(SysYParser::RelExpContext *ctx) { // 浮点数处理 if (resultType == floatType || operandType == floatType) { if (resultType != floatType) { - if (constResult != nullptr) - result = ConstantFloating::get(static_cast(constResult->getInt())); + if (constResult != nullptr){ + if(dynamic_cast(constResult)) { + // 如果是整型常量,转换为浮点型 + result = ConstantFloating::get(static_cast(constResult->getInt())); + } else if (dynamic_cast(constResult)) { + // 如果是浮点型常量,直接使用 + result = ConstantFloating::get(static_cast(constResult->getFloat())); + } + } else result = builder.createIToFInst(result); } if (operandType != floatType) { - if (constOperand != nullptr) - operand = ConstantFloating::get(static_cast(constOperand->getInt())); + if (constOperand != nullptr) { + if(dynamic_cast(constOperand)) { + // 如果是整型常量,转换为浮点型 + operand = ConstantFloating::get(static_cast(constOperand->getInt())); + } else if (dynamic_cast(constOperand)) { + // 如果是浮点型常量,直接使用 + operand = ConstantFloating::get(static_cast(constOperand->getFloat())); + } + } else operand = builder.createIToFInst(operand); @@ -1266,14 +1342,28 @@ std::any SysYIRGenerator::visitEqExp(SysYParser::EqExpContext *ctx) { if (resultType == floatType || operandType == floatType) { if (resultType != floatType) { - if (constResult != nullptr) - result = ConstantFloating::get(static_cast(constResult->getInt())); + if (constResult != nullptr){ + if(dynamic_cast(constResult)) { + // 如果是整型常量,转换为浮点型 + result = ConstantFloating::get(static_cast(constResult->getInt())); + } else if (dynamic_cast(constResult)) { + // 如果是浮点型常量,直接使用 + result = ConstantFloating::get(static_cast(constResult->getFloat())); + } + } else result = builder.createIToFInst(result); } if (operandType != floatType) { - if (constOperand != nullptr) - operand = ConstantFloating::get(static_cast(constOperand->getInt())); + if (constOperand != nullptr) { + if(dynamic_cast(constOperand)) { + // 如果是整型常量,转换为浮点型 + operand = ConstantFloating::get(static_cast(constOperand->getInt())); + } else if (dynamic_cast(constOperand)) { + // 如果是浮点型常量,直接使用 + operand = ConstantFloating::get(static_cast(constOperand->getFloat())); + } + } else operand = builder.createIToFInst(operand); } @@ -1375,15 +1465,27 @@ void Utils::tree2Array(Type *type, ArrayValueTree *root, } else { if (type == Type::getFloatType()) { ConstantValue* constValue = dynamic_cast(value); - if (constValue != nullptr) - result.push_back(ConstantFloating::get(static_cast(constValue->getInt()))); + if (constValue != nullptr) { + if(dynamic_cast(constValue)) + result.push_back(ConstantFloating::get(static_cast(constValue->getInt()))); + else if (dynamic_cast(constValue)) + result.push_back(ConstantFloating::get(static_cast(constValue->getFloat()))); + else + assert(false && "Unknown constant type for float conversion."); + } else result.push_back(builder->createIToFInst(value)); } else { ConstantValue* constValue = dynamic_cast(value); - if (constValue != nullptr) - result.push_back(ConstantInteger::get(static_cast(constValue->getFloat()))); + if (constValue != nullptr){ + if(dynamic_cast(constValue)) + result.push_back(ConstantInteger::get(constValue->getInt())); + else if (dynamic_cast(constValue)) + result.push_back(ConstantInteger::get(static_cast(constValue->getFloat()))); + else + assert(false && "Unknown constant type for int conversion."); + } else result.push_back(builder->createFtoIInst(value)); diff --git a/src/SysYIRPrinter.cpp b/src/midend/SysYIRPrinter.cpp similarity index 100% rename from src/SysYIRPrinter.cpp rename to src/midend/SysYIRPrinter.cpp diff --git a/src/sysyc.cpp b/src/sysyc.cpp index 3f79108..04da485 100644 --- a/src/sysyc.cpp +++ b/src/sysyc.cpp @@ -16,7 +16,6 @@ using namespace antlr4; #include "SysYIRCFGOpt.h" // 包含 CFG 优化 #include "RISCv64Backend.h" #include "Pass.h" // 包含新的 Pass 框架 -#include "AddressCalculationExpansion.h" using namespace sysy; @@ -139,69 +138,6 @@ int main(int argc, char **argv) { // 好像都不用传递module和builder了,因为 PassManager 初始化了 passManager.runOptimizationPipeline(moduleIR, builder, optLevel); - - - - AddressCalculationExpansion ace(moduleIR, builder); - if (ace.run()) { - if (DEBUG) cout << "AddressCalculationExpansion made changes.\n"; - // 如果 ACE 改变了IR,并且 DEBUG 模式开启,可以考虑打印IR - if (DEBUG) { - cout << "=== After AddressCalculationExpansion ===\n"; - SysYPrinter(moduleIR).printIR(); - } - } else { - if (DEBUG) cout << "AddressCalculationExpansion made no changes.\n"; - } - - - // 根据优化级别,执行额外的优化 pass - if (optLevel >= 1) { - if (DEBUG) cout << "Applying additional -O" << optLevel << " optimizations...\n"; - // 放置 -O1 及其以上级别要启用的额外优化 pass - // 例如: - // MyNewOptimizationPass newOpt(moduleIR, builder); - // newOpt.run(); - - // 占位符注释,替换为你的具体优化 pass - // cout << "--- Additional Pass: MyCustomOpt1 ---" << endl; - // MyCustomOpt1 opt1_pass(moduleIR, builder); - // opt1_pass.run(); - - // cout << "--- Additional Pass: MyCustomOpt2 ---" << endl; - // MyCustomOpt2 opt2_pass(moduleIR, builder, &cfa); // 假设需要CFA - // opt2_pass.run(); - // ... 更多 -O1 特有的优化 - // DeadCodeElimination dce(moduleIR, &cfa, &ava); - // dce.runDCEPipeline(); - // if (DEBUG) { - // cout << "=== After 1st DCE (Default) ===\n"; - // SysYPrinter(moduleIR).printIR(); - // } - - // Mem2Reg mem2reg(moduleIR, builder, &cfa, &ava); - // mem2reg.mem2regPipeline(); - // if (DEBUG) { - // cout << "=== After Mem2Reg (Default) ===\n"; - // SysYPrinter(moduleIR).printIR(); - // } - - // Reg2Mem reg2mem(moduleIR, builder); - // reg2mem.DeletePhiInst(); - // if (DEBUG) { - // cout << "=== After Reg2Mem (Default) ===\n"; - // SysYPrinter(moduleIR).printIR(); - // } - - // dce.runDCEPipeline(); // 第二次 DCE (默认) - // if (DEBUG) { - // cout << "=== After 2nd DCE (Default) ===\n"; - // SysYPrinter(moduleIR).printIR(); - // } - } else { - if (DEBUG) cout << "No additional middle-end optimizations applied for -O" << optLevel << ".\n"; - } - // 5. 根据 argStopAfter 决定后续操作 // a) 如果指定停止在 IR 阶段,则打印最终 IR 并退出 if (argStopAfter == "ir" || argStopAfter == "ird") { @@ -218,6 +154,7 @@ int main(int argc, char **argv) { DEBUG = 1; DEEPDEBUG = 1; } + sysy::RISCv64CodeGen codegen(moduleIR); // 传入优化后的 moduleIR string asmCode = codegen.code_gen(); diff --git a/test/01_add.sy b/test/01_add.sy deleted file mode 100644 index f773ad9..0000000 --- a/test/01_add.sy +++ /dev/null @@ -1,8 +0,0 @@ -//test add - -int main(){ - int a, b; - a = 10; - b = 2; - return a + b; -} diff --git a/test/10_test.sy b/test/10_test.sy deleted file mode 100644 index bfee47a..0000000 --- a/test/10_test.sy +++ /dev/null @@ -1,14 +0,0 @@ -//test file for backend lab - -int main() { - const int a = 1; - const int b = 2; - int c; - - if (a != b) - c = b - a + 20; // 21 <- this - else - c = a * b + b + b + 10; // 16 - - return c; -} diff --git a/test/11_add2.sy b/test/11_add2.sy deleted file mode 100644 index 7a662d7..0000000 --- a/test/11_add2.sy +++ /dev/null @@ -1,13 +0,0 @@ -//test add - -int mul(int x, int y) { - return x * y; -} - -int main(){ - int a, b; - a = 10; - b = 3; - a = mul(a, b); //60 - return a + b; //66 -} diff --git a/test/20_test_licm_sr.sy b/test/20_test_licm_sr.sy deleted file mode 100644 index aadadd6..0000000 --- a/test/20_test_licm_sr.sy +++ /dev/null @@ -1,20 +0,0 @@ -//test file for loop-invariant code motion (licm) and strength reduction (sr is optional) - -int main(){ - const int a = 1; - const int b = 2; - int c, d, f; - - int i = 0; - while(i < 100){ - c = a + b; - d = c * 2; - - if(i > 50){ - f = i * d; - } - i = i + 1; - } - - return f; -} \ No newline at end of file diff --git a/test/21_test_cse.sy b/test/21_test_cse.sy deleted file mode 100644 index e8000d8..0000000 --- a/test/21_test_cse.sy +++ /dev/null @@ -1,18 +0,0 @@ -//test file for common subexpression eliminiation (cse) -int main(){ - - int a = 1; - int b = 2; - int c, d, e, f; - - c = a + b; - - if(c > 0){ - b = 3; - d = a + b; - } - - e = a + b; - - return e; -} diff --git a/test/22_test_dce.sy b/test/22_test_dce.sy deleted file mode 100644 index 8cd9c73..0000000 --- a/test/22_test_dce.sy +++ /dev/null @@ -1,15 +0,0 @@ -//test file for dead code eliminiation (dce) -int main(){ - - int i = 0; - int j = 0; - int a[100]; - - while(j < 100){ - a[j] = j; - i = i * 2; - j = j + 1; - } - - return a[j-1]; -} diff --git a/test/23_test_vn.sy b/test/23_test_vn.sy deleted file mode 100644 index cf62584..0000000 --- a/test/23_test_vn.sy +++ /dev/null @@ -1,11 +0,0 @@ -//test file for value numbering (vn) -int main(){ - - int a, b, c, d; - a = 1; - b = a + 1; - c = a; - d = c + 1; - - return d; -} \ No newline at end of file diff --git a/test/24_test_cp_cf.sy b/test/24_test_cp_cf.sy deleted file mode 100644 index 78a0666..0000000 --- a/test/24_test_cp_cf.sy +++ /dev/null @@ -1,14 +0,0 @@ -//test file for constant propogation (cp) and constant folding (cf) -int main(){ - - int b = 5; - int c = 4 * b; - int d, g; - - if(c > 8){ - d = b + c; - } - g = c * d; - - return g; -} diff --git a/test/30_test_reg_alloc.sy b/test/30_test_reg_alloc.sy deleted file mode 100644 index 54ca8d8..0000000 --- a/test/30_test_reg_alloc.sy +++ /dev/null @@ -1,94 +0,0 @@ -int a1 = 1; -int a2 = 2; -int a3 = 3; -int a4 = 4; -int a5 = 5; -int a6 = 6; -int a7 = 7; -int a8 = 8; -int a9 = 9; -int a10 = 10; -int a11 = 11; -int a12 = 12; -int a13 = 13; -int a14 = 14; -int a15 = 15; -int a16 = 16; -int a17 = 1; -int a18 = 2; -int a19 = 3; -int a20 = 4; -int a21 = 5; -int a22 = 6; -int a23 = 7; -int a24 = 8; -int a25 = 9; -int a26 = 10; -int a27 = 11; -int a28 = 12; -int a29 = 13; -int a30 = 14; -int a31 = 15; -int a32 = 16; - -int func(int a, int b){ - int i; - i = a + b; - - int c1;int c2;int c3;int c4; - int d1;int d2;int d3;int d4; - int e1;int e2;int e3;int e4; - int f1;int f2;int f3;int f4; - int g1;int g2;int g3;int g4; - int h1;int h2;int h3;int h4; - int i1;int i2;int i3;int i4; - int j1;int j2;int j3;int j4; - int k1;int k2;int k3;int k4; - c1 = getint();c2 = getint();c3 = getint();c4 = getint(); - d1 = 1 + c1 + a1;d2 = 2 + c2 + a2;d3 = 3 + c3 + a3;d4 = 4 + c4 + a4; - e1 = 1 + d1 + a5;e2 = 2 + d2 + a6;e3 = 3 + d3 + a7;e4 = 4 + d4 + a8; - f1 = 1 + e1 + a9;f2 = 2 + e2 + a10;f3 = 3 + e3 + a11;f4 = 4 + e4 + a12; - g1 = 1 + f1 + a13;g2 = 2 + f2 + a14;g3 = 3 + f3 + a15;g4 = 4 + f4 + a16; - h1 = 1 + g1 + a17;h2 = 2 + g2 + a18;h3 = 3 + g3 + a19;h4 = 4 + g4 + a20; - i1 = 1 + h1 + a21;i2 = 2 + h2 + a22;i3 = 3 + h3 + a23;i4 = 4 + h4 + a24; - j1 = 1 + i1 + a25;j2 = 2 + i2 + a26;j3 = 3 + i3 + a27;j4 = 4 + i4 + a28; - k1 = 1 + j1 + a29;k2 = 2 + j2 + a30;k3 = 3 + j3 + a31;k4 = 4 + j4 + a32; - - i = a - b + 10; - k1 = 1 + j1 + a29;k2 = 2 + j2 + a30;k3 = 3 + j3 + a31;k4 = 4 + j4 + a32; - j1 = 1 + i1 + a25;j2 = 2 + i2 + a26;j3 = 3 + i3 + a27;j4 = 4 + i4 + a28; - i1 = 1 + h1 + a21;i2 = 2 + h2 + a22;i3 = 3 + h3 + a23;i4 = 4 + h4 + a24; - h1 = 1 + g1 + a17;h2 = 2 + g2 + a18;h3 = 3 + g3 + a19;h4 = 4 + g4 + a20; - g1 = 1 + f1 + a13;g2 = 2 + f2 + a14;g3 = 3 + f3 + a15;g4 = 4 + f4 + a16; - f1 = 1 + e1 + a9;f2 = 2 + e2 + a10;f3 = 3 + e3 + a11;f4 = 4 + e4 + a12; - e1 = 1 + d1 + a5;e2 = 2 + d2 + a6;e3 = 3 + d3 + a7;e4 = 4 + d4 + a8; - d1 = 1 + c1 + a1;d2 = 2 + c2 + a2;d3 = 3 + c3 + a3;d4 = 4 + c4 + a4; - d1 = 1 + c1 + a1;d2 = 2 + c2 + a2;d3 = 3 + c3 + a3;d4 = 4 + c4 + a4; - return i + c1 + c2 + c3 + c4 - - d1 - d2 - d3 - d4 - + e1 + e2 + e3 + e4 - - f1 - f2 - f3 - f4 - + g1 + g2 + g3 + g4 - - h1 - h2 - h3 - h4 - + i1 + i2 + i3 + i4 - - j1 - j2 - j3 - j4 - + k1 + k2 + k3 + k4 - + a1 - a2 + a3 - a4 - + a5 - a6 + a7 - a8 - + a9 - a10 + a11 - a12 - + a13 - a14 + a15 - a16 - + a17 - a18 + a19 - a20 - + a21 - a22 + a23 - a24 - + a25 - a26 + a27 - a28 - + a29 - a30 + a31 - a32; -} - -int main(){ - int a; - int b; - a = getint(); - b = a + 2 * 9; - a = func(a, b); - putint(a); - return a; -} \ No newline at end of file diff --git a/test/bug1.sy b/test/bug1.sy deleted file mode 100644 index c7dcb0c..0000000 --- a/test/bug1.sy +++ /dev/null @@ -1,7 +0,0 @@ -// bug1: getint(; - -int main() { - int a; - a = getint(; - return 0; -} \ No newline at end of file diff --git a/test/format-ref.sy b/test/format-ref.sy deleted file mode 100644 index b34ec8a..0000000 --- a/test/format-ref.sy +++ /dev/null @@ -1,31 +0,0 @@ -int get_one(int a) { - return 1; -} - -int deepWhileBr(int a, int b) { - int c; - c = a + b; - while (c < 75) { - int d; - d = 42; - if (c < 100) { - c = c + d; - if (c > 99) { - int e; - e = d * 2; - if (get_one(0) == 1) { - c = e * 2; - } - } - } - } - return (c); -} - -int main() { - int p; - p = 2; - p = deepWhileBr(p, p); - putint(p); - return 0; -} diff --git a/test/format-test.sy b/test/format-test.sy deleted file mode 100644 index 756e5f8..0000000 --- a/test/format-test.sy +++ /dev/null @@ -1,30 +0,0 @@ -int get_one(int a) -{ - return 1; -} - - - -int deepWhileBr(int a,int b){ - int c; - c = a + b; - while(c<75) { - int d; d=42; - if (c<100) { - c =c+d; - if (c > 99) { - int e; - e = d*2; - if (get_one(0)==1) c=e * 2; - } - } - } - return (c); -} -int main() { - int p; - p = 2; - p = deepWhileBr(p, p); - putint(p); - return 0; -} diff --git a/test/funcrparams.sy b/test/funcrparams.sy deleted file mode 100644 index 9358f3a..0000000 --- a/test/funcrparams.sy +++ /dev/null @@ -1 +0,0 @@ -1,0xa , 011, "hellow",1.1