// 将语法树翻译为 IR。 // 实现拆分在 IRGenFunc/IRGenStmt/IRGenExp/IRGenDecl。 #pragma once #include #include #include #include "SysYParser.h" #include "ir/IR.h" #include "sem/Sema.h" namespace ir { class Module; class Function; class IRBuilder; class Value; } class IRGenImpl { public: IRGenImpl(ir::Module& module, const SemanticContext& sema); void Gen(SysYParser::CompUnitContext& cu); private: void GenFuncDef(SysYParser::FuncDefContext& func); void GenBlock(SysYParser::BlockContext& block); bool GenBlockItem(SysYParser::BlockItemContext& item); void GenDecl(SysYParser::DeclContext& decl); bool GenStmt(SysYParser::StmtContext& stmt); void GenVarDecl(SysYParser::VarDeclContext& decl); void GenReturnStmt(SysYParser::ReturnStmtContext& ret); ir::Value* GenExpr(SysYParser::ExpContext& expr); ir::Value* GenAddExpr(SysYParser::AddExpContext& add); ir::Value* GenPrimary(SysYParser::PrimaryContext& primary); ir::Module& module_; const SemanticContext& sema_; ir::Function* func_; ir::IRBuilder builder_; // 名称绑定由 Sema 负责;IRGen 只维护“声明 -> 存储槽位”的代码生成状态。 std::unordered_map storage_map_; }; std::unique_ptr GenerateIR(SysYParser::CompUnitContext& tree, const SemanticContext& sema);