forked from NUDT-compiler/nudt-compiler-cpp
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
48 lines
1.3 KiB
48 lines
1.3 KiB
#include "irgen/IRGen.h"
|
|
|
|
#include <stdexcept>
|
|
|
|
#include "SysYParser.h"
|
|
#include "ir/IR.h"
|
|
|
|
namespace {
|
|
|
|
void VerifyFunctionStructure(const ir::Function& func) {
|
|
// 当前 IRGen 仍是单入口、顺序生成;这里在生成结束后补一层块终结校验。
|
|
for (const auto& bb : func.blocks()) {
|
|
if (!bb || !bb->HasTerminator()) {
|
|
throw std::runtime_error("[irgen] 基本块未正确终结: " +
|
|
(bb ? bb->name() : std::string("<null>")));
|
|
}
|
|
}
|
|
}
|
|
|
|
} // namespace
|
|
|
|
IRGenImpl::IRGenImpl(ir::Module& module)
|
|
: module_(module), func_(nullptr), builder_(nullptr) {}
|
|
|
|
void IRGenImpl::Gen(SysYParser::CompUnitContext& cu) {
|
|
if (!cu.funcDef()) {
|
|
throw std::runtime_error("[irgen] 缺少 main 定义");
|
|
}
|
|
GenFuncDef(*cu.funcDef());
|
|
}
|
|
|
|
void IRGenImpl::GenFuncDef(SysYParser::FuncDefContext& func) {
|
|
if (!func.block()) {
|
|
throw std::runtime_error("[irgen] 函数体为空");
|
|
}
|
|
if (!func.Ident()) {
|
|
throw std::runtime_error("[irgen] 缺少函数名");
|
|
}
|
|
|
|
func_ = module_.CreateFunction(func.Ident()->getText(), ir::Type::Int32());
|
|
builder_.SetInsertPoint(func_->entry());
|
|
locals_.clear();
|
|
|
|
GenBlock(*func.block());
|
|
// 语义正确性主要由 sema 保证,这里只兜底检查 IR 结构是否合法。
|
|
VerifyFunctionStructure(*func_);
|
|
}
|