Compare commits

...

35 Commits

Author SHA1 Message Date
pw6fhtz7q 4b5152c826 实验三
1 week ago
mxr 70234dde70 fix(mir)修改临时寄存器使用
2 weeks ago
mxr cc41bb60ae feat(mir)修改浮点数处理
2 weeks ago
pw6fhtz7q 95b3b88ed7 Merge pull request '实验二' (#6) from feature/lab2 into master
2 weeks ago
mxr 35885f3eba (mir)修正编译程序死循环问题
1 month ago
mxr fdeb3fc66e (mir)修复寄存器重用冲突错误和浮点比较逻辑
1 month ago
mxr d0ecc5c2e9 (mir)修复传递参数是指针时存在的问题
1 month ago
mxr 1cf6ed53f1 (test)输出文件格式不匹配
1 month ago
compile b9151b866e 修复GEP中32位整型索引变量误用问题
2 months ago
mxr 34d483ed47 feat(mir)本地编译SysY静态库
2 months ago
mxr bbfb8f2c69 feat(mir)链接完整的 SysY 运行时库
2 months ago
ftt 966b5b9c7f 修改多维数组索引
2 months ago
mxr d5a8affe83 feat(mir)修正栈帧分配错误
2 months ago
ftt 0fd3f4b841 解决对应值栈槽问题
2 months ago
mxr 7438c366fd feat(mir)修正全局变量地址计算和数据段生成
2 months ago
mxr 5e492f531b feat(mir)处理指令立即数超出范围
2 months ago
mxr c9f73980ea feat(mir)修改数组分配逻辑
2 months ago
mxr 596b0ee334 feat(mir)添加Movk指令加载大立即数
2 months ago
mxr 4132f0b5ca feat(mir)实现多条指令访问栈帧
2 months ago
mxr 4f00d05c86 fix(mir)修复Ret返回void问题
2 months ago
ftt 8b4ffdde44 修改condbr
2 months ago
ftt 7d8ee45a42 值对应栈槽问题
2 months ago
ftt 288d0ec3b0 Merge remote-tracking branch 'refs/remotes/origin/feature/mir' into feature/mir
2 months ago
ftt bf21e9c437 处理浮点常量
2 months ago
mxr 9c9f5a2013 feat(mir)调试控制流生成
2 months ago
mxr 4f4842ae3a feat(mir)修复函数序言插入问题
2 months ago
mxr f0706adcc0 feat(mir)修改基本块名
2 months ago
mxr 34ec79c399 feat(mir)修复栈帧指令遍历处理
2 months ago
ftt c24a078bf5 补充寄存器
2 months ago
ftt 653c091993 完成二三四阶段,解决支持多函数问题等
2 months ago
mxr 6e804e2091 test(test)更新测试脚本并统一输出目录
2 months ago
mxr f966869fb1 feat(mir)扩展汇编指令生成
2 months ago
ftt 1a48e369e7 第一阶段:扩展 MIR 指令集
2 months ago
mxr 1c7cc33e4b chore(test)修改调试输出
2 months ago
pw6fhtz7q 6f649c0ad5 Merge pull request '语义分析与ir生成' (#5) from feature/ir-final into feature/lab2
2 months ago

1
.gitignore vendored

@ -74,3 +74,4 @@ test/test_result/
# ========================= # =========================
result.txt result.txt
build.sh build.sh
gdb.sh

@ -8,12 +8,22 @@
#include <string> #include <string>
#include <unordered_map> #include <unordered_map>
#include <unordered_set> #include <unordered_set>
#include <iostream>
#include "SysYBaseVisitor.h" #include "SysYBaseVisitor.h"
#include "SysYParser.h" #include "SysYParser.h"
#include "ir/IR.h" #include "ir/IR.h"
#include "sem/Sema.h" #include "sem/Sema.h"
//#define DEBUG_IRGen
#ifdef DEBUG_IRGen
#include <iostream>
#define DEBUG_MSG(msg) std::cerr << "[IRGen Debug] " << msg << std::endl
#else
#define DEBUG_MSG(msg)
#endif
namespace ir { namespace ir {
class Module; class Module;
class Function; class Function;

@ -19,41 +19,161 @@ class MIRContext {
MIRContext& DefaultContext(); MIRContext& DefaultContext();
enum class PhysReg { W0, W8, W9, X29, X30, SP }; enum class PhysReg {
//W0, W8, W9, X29, X30, SP
// 32位通用寄存器
W0, W1, W2, W3, W4, W5, W6, W7, // 参数传递/临时
W8, W9, // 临时寄存器(当前主要使用)
W10, W11, W12, W13, W14, W15, // 临时寄存器(扩展)
W16, W17, // intra-procedure-call 临时
W18, // 平台预留
W19, W20, W21, W22, W23, W24, // 被调用者保存(扩展用)
W25, W26, W27, W28, // 被调用者保存
W29, // 帧指针 (FP)
W30, // 链接寄存器 (LR)
// 64位版本
X0, X1, X2, X3, X4, X5, X6, X7,
X8, X9, X10, X11, X12, X13, X14, X15,
X16, X17, X18,
X19, X20, X21, X22, X23, X24, X25, X26, X27, X28,
X29, // FP
X30, // LR
// 浮点寄存器 (32位)
S0, S1, S2, S3, S4, S5, S6, S7,
S8, S9, S10, S11, S12, S13, S14, S15,
S16, S17, S18, S19, S20, S21, S22, S23,
S24, S25, S26, S27, S28, S29, S30, S31,
// 特殊寄存器
SP, // 栈指针
ZR, // 零寄存器
};
const char* PhysRegName(PhysReg reg); const char* PhysRegName(PhysReg reg);
// ========== 条件码枚举(用于 BCond 指令)==========
enum class CondCode {
EQ, // 相等 (equal)
NE, // 不等 (not equal)
CS, // 进位设置 (carry set) / 无符号大于等于
CC, // 进位清除 (carry clear) / 无符号小于
MI, // 负数 (minus)
PL, // 非负数 (plus)
VS, // 溢出 (overflow set)
VC, // 无溢出 (overflow clear)
HI, // 无符号大于 (higher)
LS, // 无符号小于等于 (lower or same)
GE, // 有符号大于等于 (greater or equal)
LT, // 有符号小于 (less than)
GT, // 有符号大于 (greater than)
LE, // 有符号小于等于 (less or equal)
AL, // 总是 (always)
};
const char* CondCodeName(CondCode cc);
// ========== MIR 指令操作码枚举 ==========
enum class Opcode { enum class Opcode {
Prologue, // ---------- 栈帧相关 ----------
Epilogue, Prologue, // 函数序言(伪指令)
MovImm, Epilogue, // 函数尾声(伪指令)
LoadStack,
StoreStack, // ---------- 数据传输 ----------
AddRR, MovImm, // 立即数移动到寄存器: MOV w8, #imm
Ret, MovReg, // 寄存器之间移动: MOV w8, w9
LoadStack, // 从栈槽加载: LDR w8, [sp, #offset]
StoreStack, // 存储到栈槽: STR w8, [sp, #offset]
LoadStackPair,// 成对加载: LDP x29, x30, [sp], #16
StoreStackPair,// 成对存储: STP x29, x30, [sp, #-16]!
// ---------- 整数算术运算 ----------
AddRR, // 加法: ADD w8, w8, w9
AddRI, // 加法(立即数): ADD w8, w8, #imm
SubRR, // 减法: SUB w8, w8, w9
SubRI, // 减法(立即数): SUB w8, w8, #imm
MulRR, // 乘法: MUL w8, w8, w9
SDivRR, // 有符号除法: SDIV w8, w8, w9
UDivRR, // 无符号除法: UDIV w8, w8, w9
// ---------- 浮点算术运算 ----------
FAddRR, // 浮点加法: FADD s0, s0, s1
FSubRR, // 浮点减法: FSUB s0, s0, s1
FMulRR, // 浮点乘法: FMUL s0, s0, s1
FDivRR, // 浮点除法: FDIV s0, s0, s1
// ---------- 比较运算 ----------
CmpRR, // 比较(寄存器): CMP w8, w9
CmpRI, // 比较(立即数): CMP w8, #imm
FCmpRR, // 浮点比较: FCMP s0, s1
// ---------- 类型转换 ----------
SIToFP, // 有符号整数转浮点: SCVTF s0, w0
FPToSI, // 浮点转有符号整数: FCVTZS w0, s0
ZExt, // 零扩展i1 -> i32: AND w8, w8, #1
// ---------- 控制流 ----------
B, // 无条件跳转: B label
BCond, // 条件跳转: B.EQ label, B.NE label, B.GT label 等
Call, // 函数调用: BL target
Ret, // 函数返回: RET
// ---------- 逻辑运算 ----------
AndRR, // 按位与: AND w8, w8, w9
OrRR, // 按位或: ORR w8, w8, w9
EorRR, // 按位异或: EOR w8, w8, w9
LslRR, // 逻辑左移: LSL w8, w8, w9
LsrRR, // 逻辑右移: LSR w8, w8, w9
AsrRR, // 算术右移: ASR w8, w8, w9
// ---------- 特殊 ----------
Nop, // 空操作: NOP
Label, // 内联标签,不生成实际指令,仅输出标签名
// 添加
Movk, // movk Rd, #imm16, lsl #shift
// 添加
LoadStackAddr, // 将栈帧地址加载到寄存器 (add xd, sp, #offset)
// 用于全局变量地址计算
Adrp, // ADRP Xd, label
AddLabel, // ADD Xd, Xn, :lo12:label
// 新增
Sxtw, // 符号扩展字到双字sxtw Xd, Wn
}; };
// ========== 操作数类 ==========
class Operand { class Operand {
public: public:
enum class Kind { Reg, Imm, FrameIndex }; enum class Kind { Reg, Imm, FrameIndex, Cond, Label };
static Operand Reg(PhysReg reg); static Operand Reg(PhysReg reg);
static Operand Imm(int value); static Operand Imm(int value);
static Operand FrameIndex(int index); static Operand FrameIndex(int index);
static Operand Cond(CondCode cc);
static Operand Label(const std::string& label);
Kind GetKind() const { return kind_; } Kind GetKind() const { return kind_; }
PhysReg GetReg() const { return reg_; } PhysReg GetReg() const { return reg_; }
int GetImm() const { return imm_; } int GetImm() const { return imm_; }
int GetFrameIndex() const { return imm_; } int GetFrameIndex() const { return imm_; }
CondCode GetCondCode() const { return cc_; }
const std::string& GetLabel() const { return label_; }
private: private:
Operand(Kind kind, PhysReg reg, int imm); Operand(Kind kind, PhysReg reg, int imm, CondCode cc, const std::string& label);
Kind kind_; Kind kind_;
PhysReg reg_; PhysReg reg_;
int imm_; int imm_;
CondCode cc_;
std::string label_;
}; };
// ========== MIR 指令类 ==========
class MachineInstr { class MachineInstr {
public: public:
MachineInstr(Opcode opcode, std::vector<Operand> operands = {}); MachineInstr(Opcode opcode, std::vector<Operand> operands = {});
@ -66,12 +186,14 @@ class MachineInstr {
std::vector<Operand> operands_; std::vector<Operand> operands_;
}; };
// ========== 栈槽结构 ==========
struct FrameSlot { struct FrameSlot {
int index = 0; int index = 0;
int size = 4; int size = 4;
int offset = 0; int offset = 0;
}; };
// ========== MIR 基本块 ==========
class MachineBasicBlock { class MachineBasicBlock {
public: public:
explicit MachineBasicBlock(std::string name); explicit MachineBasicBlock(std::string name);
@ -82,38 +204,133 @@ class MachineBasicBlock {
MachineInstr& Append(Opcode opcode, MachineInstr& Append(Opcode opcode,
std::initializer_list<Operand> operands = {}); std::initializer_list<Operand> operands = {});
MachineInstr& Append(Opcode opcode, std::vector<Operand> operands);
// 控制流信息
std::vector<MachineBasicBlock*>& GetSuccessors() { return successors_; }
const std::vector<MachineBasicBlock*>& GetSuccessors() const { return successors_; }
void AddSuccessor(MachineBasicBlock* succ) { successors_.push_back(succ); }
private: private:
std::string name_; std::string name_;
std::vector<MachineInstr> instructions_; std::vector<MachineInstr> instructions_;
std::vector<MachineBasicBlock*> successors_;
}; };
// ========== MIR 函数 ==========
class MachineFunction { class MachineFunction {
public: public:
explicit MachineFunction(std::string name); explicit MachineFunction(std::string name);
const std::string& GetName() const { return name_; } const std::string& GetName() const { return name_; }
// 基本块管理
MachineBasicBlock& GetEntry() { return entry_; } MachineBasicBlock& GetEntry() { return entry_; }
const MachineBasicBlock& GetEntry() const { return entry_; } const MachineBasicBlock& GetEntry() const { return entry_; }
std::vector<std::unique_ptr<MachineBasicBlock>>& GetBasicBlocks() {
return basic_blocks_;
}
const std::vector<std::unique_ptr<MachineBasicBlock>>& GetBasicBlocks() const {
return basic_blocks_;
}
void AddBasicBlock(std::unique_ptr<MachineBasicBlock> bb) {
basic_blocks_.push_back(std::move(bb));
}
// 栈槽管理
int CreateFrameIndex(int size = 4); int CreateFrameIndex(int size = 4);
FrameSlot& GetFrameSlot(int index); FrameSlot& GetFrameSlot(int index);
const FrameSlot& GetFrameSlot(int index) const; const FrameSlot& GetFrameSlot(int index) const;
std::vector<FrameSlot>& GetFrameSlots() { return frame_slots_; }
const std::vector<FrameSlot>& GetFrameSlots() const { return frame_slots_; } const std::vector<FrameSlot>& GetFrameSlots() const { return frame_slots_; }
// 栈帧大小
int GetFrameSize() const { return frame_size_; } int GetFrameSize() const { return frame_size_; }
void SetFrameSize(int size) { frame_size_ = size; } void SetFrameSize(int size) { frame_size_ = size; }
private: private:
std::string name_; std::string name_;
MachineBasicBlock entry_; MachineBasicBlock entry_;
std::vector<std::unique_ptr<MachineBasicBlock>> basic_blocks_;
std::vector<FrameSlot> frame_slots_; std::vector<FrameSlot> frame_slots_;
int frame_size_ = 0; int frame_size_ = 0;
}; };
std::unique_ptr<MachineFunction> LowerToMIR(const ir::Module& module); // ========== MIR 模块 ==========
class MachineModule {
public:
MachineModule() = default;
// 添加 MachineFunction
void AddFunction(std::unique_ptr<MachineFunction> func) {
functions_.push_back(std::move(func));
}
// 获取所有函数
const std::vector<std::unique_ptr<MachineFunction>>& GetFunctions() const {
return functions_;
}
std::vector<std::unique_ptr<MachineFunction>>& GetFunctions() {
return functions_;
}
// 根据名称查找函数
MachineFunction* GetFunction(const std::string& name) {
for (auto& func : functions_) {
if (func->GetName() == name) {
return func.get();
}
}
return nullptr;
}
const MachineFunction* GetFunction(const std::string& name) const {
for (const auto& func : functions_) {
if (func->GetName() == name) {
return func.get();
}
}
return nullptr;
}
struct GlobalDecl {
std::string name;
int size; // 字节大小
int alignment; // 对齐要求(通常为 4 或 8
bool is_zero_init; // 是否为零初始化
bool has_init_data; // 是否包含初始化数据(用于标量常量)
uint64_t init_data; // 初始化数据≤8字节
// 构造函数,默认零初始化
GlobalDecl(const std::string& n, int sz, int align, bool zero = true,
bool has_data = false, uint64_t data = 0)
: name(n), size(sz), alignment(align), is_zero_init(zero),
has_init_data(has_data), init_data(data) {}
};
void AddGlobal(const std::string& name, int size, int alignment,
bool is_zero_init = true,
bool has_init_data = false, uint64_t init_data = 0) {
globals_.emplace_back(name, size, alignment, is_zero_init,
has_init_data, init_data);
}
const std::vector<GlobalDecl>& GetGlobals() const { return globals_; }
private:
std::vector<std::unique_ptr<MachineFunction>> functions_;
std::vector<GlobalDecl> globals_;
};
// ========== 后端流程函数 ==========
/* std::unique_ptr<MachineFunction> LowerToMIR(const ir::Module& module);
void RunRegAlloc(MachineFunction& function); void RunRegAlloc(MachineFunction& function);
void RunFrameLowering(MachineFunction& function); void RunFrameLowering(MachineFunction& function);
void PrintAsm(const MachineFunction& function, std::ostream& os); void PrintAsm(const MachineFunction& function, std::ostream& os); */
std::unique_ptr<MachineModule> LowerToMIR(const ir::Module& module);
void RunRegAlloc(MachineModule& module);
void RunFrameLowering(MachineModule& module);
void PrintAsm(const MachineModule& module, std::ostream& os);
} // namespace mir } // namespace mir

File diff suppressed because it is too large Load Diff

@ -4,6 +4,7 @@ set -euo pipefail
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
COMPILER="$ROOT_DIR/build/bin/compiler" COMPILER="$ROOT_DIR/build/bin/compiler"
TMP_DIR="$ROOT_DIR/build/test_compiler" TMP_DIR="$ROOT_DIR/build/test_compiler"
RESULT_BASE_DIR="$ROOT_DIR/test/test_result"
TEST_DIRS=("$ROOT_DIR/test/test_case/functional" "$ROOT_DIR/test/test_case/performance") TEST_DIRS=("$ROOT_DIR/test/test_case/functional" "$ROOT_DIR/test/test_case/performance")
CC_BIN="${CC:-cc}" CC_BIN="${CC:-cc}"
RUNTIME_SRC="$ROOT_DIR/sylib/sylib.c" RUNTIME_SRC="$ROOT_DIR/sylib/sylib.c"
@ -66,7 +67,17 @@ for test_dir in "${TEST_DIRS[@]}"; do
ir_total=$((ir_total+1)) ir_total=$((ir_total+1))
base=$(basename "$input") base=$(basename "$input")
stem=${base%.sy} stem=${base%.sy}
out_dir="$TMP_DIR/$(basename "$test_dir")" case "$(basename "$test_dir")" in
functional)
out_dir="$RESULT_BASE_DIR/functional/ir"
;;
performance)
out_dir="$RESULT_BASE_DIR/performance/ir"
;;
*)
out_dir="$RESULT_BASE_DIR/$(basename "$test_dir")"
;;
esac
mkdir -p "$out_dir" mkdir -p "$out_dir"
ll_file="$out_dir/$stem.ll" ll_file="$out_dir/$stem.ll"
stdout_file="$out_dir/$stem.stdout" stdout_file="$out_dir/$stem.stdout"

@ -0,0 +1,167 @@
#!/bin/bash
# 测试脚本(支持动态输出目录)
# 用法: ./run_tests.sh [--verbose] [--mode <模式>] [<单个测试文件>]
# 模式: parse-tree, ir, asm, run (默认 run)
COMPILER="./build/bin/compiler"
TEST_SCRIPT="./scripts/verify_asm.sh"
TEST_DIR="test/test_case"
RESULT_FILE="result.txt"
VERBOSE=0
MODE="run" # 默认模式为完整测试
# 解析参数
while [[ $# -gt 0 ]]; do
case "$1" in
--verbose|-v)
VERBOSE=1
shift
;;
--mode)
MODE="$2"
shift 2
;;
--emit-parse-tree)
MODE="parse-tree"
shift
;;
--emit-ir)
MODE="ir"
shift
;;
--emit-asm)
MODE="asm"
shift
;;
--run)
MODE="run"
shift
;;
-*)
echo "未知选项: $1"
exit 1
;;
*)
# 非选项参数视为测试文件
SINGLE_FILE="$1"
shift
;;
esac
done
# 检查编译器是否存在
if [ ! -f "$COMPILER" ]; then
echo "错误: 编译器未找到于 $COMPILER"
echo "请先完成项目构建 (cmake 和 make)"
exit 1
fi
# 如果是 run 模式,检查测试脚本是否存在
if [ "$MODE" = "run" ] && [ ! -f "$TEST_SCRIPT" ]; then
echo "错误: 测试脚本未找到于 $TEST_SCRIPT"
exit 1
fi
# 如果指定了单个文件,检查文件是否存在
if [ -n "$SINGLE_FILE" ] && [ ! -f "$SINGLE_FILE" ]; then
echo "错误: 文件 $SINGLE_FILE 不存在"
exit 1
fi
# 清空(或创建)结果文件
> "$RESULT_FILE"
# 计数器
total=0
passed=0
failed=0
echo "开始测试 (模式: $MODE)..."
echo "输出将保存到 $RESULT_FILE"
echo "------------------------"
# 确定测试文件列表
if [ -n "$SINGLE_FILE" ]; then
TEST_FILES=("$SINGLE_FILE")
else
mapfile -t TEST_FILES < <(find "$TEST_DIR" -type f -name "*.sy" | sort)
fi
# 根据模式执行测试
for file in "${TEST_FILES[@]}"; do
((total++))
if [ $VERBOSE -eq 1 ]; then
echo "测试文件: $file"
else
echo -n "测试 $file ... "
fi
echo "========== $file ==========" >> "$RESULT_FILE"
# 根据模式构建命令
case "$MODE" in
parse-tree)
cmd="$COMPILER --emit-parse-tree \"$file\""
;;
ir)
cmd="$COMPILER --emit-ir \"$file\""
;;
asm)
cmd="$COMPILER --emit-asm \"$file\""
;;
run)
# 根据输入文件所在子目录确定输出目录
# 提取 test/test_case/ 之后的子目录名functional 或 performance
rel_path="${file#$TEST_DIR/}"
subdir=$(echo "$rel_path" | cut -d'/' -f1)
if [[ "$subdir" != "functional" && "$subdir" != "performance" ]]; then
echo "警告: 未知子目录 $subdir,使用默认输出目录" >> "$RESULT_FILE"
out_dir="test/test_result/asm"
else
out_dir="test/test_result/$subdir/asm"
fi
cmd="$TEST_SCRIPT \"$file\" \"$out_dir\" --run"
;;
*)
echo "未知模式: $MODE" >&2
exit 1
;;
esac
if [ $VERBOSE -eq 1 ]; then
eval "$cmd" 2>&1 | tee -a "$RESULT_FILE"
result=${PIPESTATUS[0]}
else
eval "$cmd" >> "$RESULT_FILE" 2>&1
result=$?
fi
echo "" >> "$RESULT_FILE"
if [ $result -eq 0 ]; then
if [ $VERBOSE -eq 0 ]; then
echo "通过"
fi
((passed++))
else
if [ $VERBOSE -eq 0 ]; then
echo "失败"
else
echo ">>> 测试失败: $file"
fi
((failed++))
fi
done
echo "------------------------"
echo "总计: $total"
echo "通过: $passed"
echo "失败: $failed"
echo "详细输出已保存至 $RESULT_FILE"
if [ $failed -gt 0 ]; then
exit 1
else
exit 0
fi

@ -52,7 +52,8 @@ expected_file="$input_dir/$stem.out"
"$compiler" --emit-asm "$input" > "$asm_file" "$compiler" --emit-asm "$input" > "$asm_file"
echo "汇编已生成: $asm_file" echo "汇编已生成: $asm_file"
aarch64-linux-gnu-gcc "$asm_file" -o "$exe" # 静态链接
aarch64-linux-gnu-gcc -no-pie "$asm_file" -L./sylib -lsysy -static -o "$exe"
echo "可执行文件已生成: $exe" echo "可执行文件已生成: $exe"
if [[ "$run_exec" == true ]]; then if [[ "$run_exec" == true ]]; then
@ -83,7 +84,7 @@ if [[ "$run_exec" == true ]]; then
} > "$actual_file" } > "$actual_file"
if [[ -f "$expected_file" ]]; then if [[ -f "$expected_file" ]]; then
if diff -u "$expected_file" "$actual_file"; then if diff -w -u "$expected_file" "$actual_file"; then
echo "输出匹配: $expected_file" echo "输出匹配: $expected_file"
else else
echo "输出不匹配: $expected_file" >&2 echo "输出不匹配: $expected_file" >&2

@ -14,6 +14,7 @@ size_t Type::Size() const {
case Kind::PtrInt32: return 8; // 假设 64 位指针 case Kind::PtrInt32: return 8; // 假设 64 位指针
case Kind::PtrFloat: return 8; case Kind::PtrFloat: return 8;
case Kind::Label: return 8; // 标签地址大小(指针大小) case Kind::Label: return 8; // 标签地址大小(指针大小)
case Kind::PtrInt1: return 8; // 指向 i1 的指针大小
default: return 0; // 派生类应重写 default: return 0; // 派生类应重写
} }
} }

@ -100,14 +100,14 @@ std::string MakeStaticArrayName(const ir::Function& func,
// visitDecl: 处理声明 // visitDecl: 处理声明
std::any IRGenImpl::visitDecl(SysYParser::DeclContext* ctx) { std::any IRGenImpl::visitDecl(SysYParser::DeclContext* ctx) {
std::cerr << "[DEBUG] visitDecl: 开始处理声明" << std::endl; DEBUG_MSG("[DEBUG] visitDecl: 开始处理声明");
if (!ctx) { if (!ctx) {
throw std::runtime_error(FormatError("irgen", "缺少变量声明")); throw std::runtime_error(FormatError("irgen", "缺少变量声明"));
} }
// 处理 varDecl // 处理 varDecl
if (auto* varDecl = ctx->varDecl()) { if (auto* varDecl = ctx->varDecl()) {
std::cerr << "[DEBUG] visitDecl: 处理变量声明" << std::endl; DEBUG_MSG("[DEBUG] visitDecl: 处理变量声明");
for (auto* varDef : varDecl->varDef()) { for (auto* varDef : varDecl->varDef()) {
varDef->accept(this); varDef->accept(this);
} }
@ -115,20 +115,20 @@ std::any IRGenImpl::visitDecl(SysYParser::DeclContext* ctx) {
// 处理 constDecl // 处理 constDecl
if (ctx->constDecl()) { if (ctx->constDecl()) {
std::cerr << "[DEBUG] visitDecl: 处理常量声明" << std::endl; DEBUG_MSG("[DEBUG] visitDecl: 处理常量声明");
auto* constDecl = ctx->constDecl(); auto* constDecl = ctx->constDecl();
for (auto* constDef : constDecl->constDef()) { for (auto* constDef : constDecl->constDef()) {
constDef->accept(this); constDef->accept(this);
} }
} }
std::cerr << "[DEBUG] visitDecl: 声明处理完成" << std::endl; DEBUG_MSG("[DEBUG] visitDecl: 声明处理完成");
return {}; return {};
} }
// visitConstDecl: 处理常量声明 // visitConstDecl: 处理常量声明
std::any IRGenImpl::visitConstDecl(SysYParser::ConstDeclContext* ctx) { std::any IRGenImpl::visitConstDecl(SysYParser::ConstDeclContext* ctx) {
std::cerr << "[DEBUG] visitConstDecl: 开始处理常量声明" << std::endl; DEBUG_MSG("[DEBUG] visitConstDecl: 开始处理常量声明");
if (!ctx) { if (!ctx) {
throw std::runtime_error(FormatError("irgen", "非法常量声明")); throw std::runtime_error(FormatError("irgen", "非法常量声明"));
} }
@ -139,13 +139,13 @@ std::any IRGenImpl::visitConstDecl(SysYParser::ConstDeclContext* ctx) {
} }
} }
std::cerr << "[DEBUG] visitConstDecl: 常量声明处理完成" << std::endl; DEBUG_MSG("[DEBUG] visitConstDecl: 常量声明处理完成");
return {}; return {};
} }
// visitConstDef: 处理常量定义 - 从符号表获取常量值 // visitConstDef: 处理常量定义 - 从符号表获取常量值
std::any IRGenImpl::visitConstDef(SysYParser::ConstDefContext* ctx) { std::any IRGenImpl::visitConstDef(SysYParser::ConstDefContext* ctx) {
std::cerr << "[DEBUG] visitConstDef: 开始处理常量定义" << std::endl; DEBUG_MSG("[DEBUG] visitConstDef: 开始处理常量定义");
if (!ctx || !ctx->Ident()) { if (!ctx || !ctx->Ident()) {
throw std::runtime_error(FormatError("irgen", "非法常量定义")); throw std::runtime_error(FormatError("irgen", "非法常量定义"));
} }
@ -158,8 +158,8 @@ std::any IRGenImpl::visitConstDef(SysYParser::ConstDefContext* ctx) {
throw std::runtime_error(FormatError("irgen", "常量符号未找到: " + const_name)); throw std::runtime_error(FormatError("irgen", "常量符号未找到: " + const_name));
} }
std::cerr << "[DEBUG] visitConstDef: 从符号表获取常量 " << const_name DEBUG_MSG("[DEBUG] visitConstDef: 从符号表获取常量 " << const_name
<< ", is_array_const: " << sym->IsArrayConstant() << std::endl; << ", is_array_const: " << sym->IsArrayConstant());
// 根据符号表中的常量值创建 IR 常量 // 根据符号表中的常量值创建 IR 常量
if (sym->IsArrayConstant()) { if (sym->IsArrayConstant()) {
@ -270,12 +270,12 @@ std::any IRGenImpl::visitConstDef(SysYParser::ConstDefContext* ctx) {
ir::ConstantValue* const_value = nullptr; ir::ConstantValue* const_value = nullptr;
if (sym->type->IsInt32()) { if (sym->type->IsInt32()) {
const_value = builder_.CreateConstInt(sym->GetIntConstant()); const_value = builder_.CreateConstInt(sym->GetIntConstant());
std::cerr << "[DEBUG] visitConstDef: 整型常量 " << const_name DEBUG_MSG("[DEBUG] visitConstDef: 整型常量 " << const_name
<< " = " << sym->GetIntConstant() << std::endl; << " = " << sym->GetIntConstant());
} else if (sym->type->IsFloat()) { } else if (sym->type->IsFloat()) {
const_value = builder_.CreateConstFloat(sym->GetFloatConstant()); const_value = builder_.CreateConstFloat(sym->GetFloatConstant());
std::cerr << "[DEBUG] visitConstDef: 浮点常量 " << const_name DEBUG_MSG("[DEBUG] visitConstDef: 浮点常量 " << const_name
<< " = " << sym->GetFloatConstant() << std::endl; << " = " << sym->GetFloatConstant());
} }
const_value_map_[const_name] = const_value; const_value_map_[const_name] = const_value;
@ -287,13 +287,13 @@ std::any IRGenImpl::visitConstDef(SysYParser::ConstDefContext* ctx) {
// visitVarDef: 处理变量定义 - 从符号表获取类型信息 // visitVarDef: 处理变量定义 - 从符号表获取类型信息
std::any IRGenImpl::visitVarDef(SysYParser::VarDefContext* ctx) { std::any IRGenImpl::visitVarDef(SysYParser::VarDefContext* ctx) {
std::cerr << "[DEBUG] visitVarDef: 开始处理变量定义" << std::endl; DEBUG_MSG("[DEBUG] visitVarDef: 开始处理变量定义");
if (!ctx || !ctx->Ident()) { if (!ctx || !ctx->Ident()) {
throw std::runtime_error(FormatError("irgen", "非法变量定义")); throw std::runtime_error(FormatError("irgen", "非法变量定义"));
} }
std::string varName = ctx->Ident()->getText(); std::string varName = ctx->Ident()->getText();
std::cerr << "[DEBUG] visitVarDef: 变量名称: " << varName << std::endl; DEBUG_MSG("[DEBUG] visitVarDef: 变量名称: " << varName);
// 防止重复分配 // 防止重复分配
if (storage_map_.find(ctx) != storage_map_.end()) { if (storage_map_.find(ctx) != storage_map_.end()) {
@ -306,17 +306,17 @@ std::any IRGenImpl::visitVarDef(SysYParser::VarDefContext* ctx) {
throw std::runtime_error(FormatError("irgen", "变量符号未找到: " + varName)); throw std::runtime_error(FormatError("irgen", "变量符号未找到: " + varName));
} }
std::cerr << "[DEBUG] visitVarDef: 变量类型: " DEBUG_MSG("[DEBUG] visitVarDef: 变量类型: "
<< (sym->type->IsInt32() ? "int" : << (sym->type->IsInt32() ? "int" :
sym->type->IsFloat() ? "float" : sym->type->IsFloat() ? "float" :
sym->type->IsArray() ? "array" : "unknown") << std::endl; sym->type->IsArray() ? "array" : "unknown"));
// 根据作用域处理 // 根据作用域处理
if (func_ == nullptr) { if (func_ == nullptr) {
std::cerr << "[DEBUG] visitVarDef: 处理全局变量" << std::endl; DEBUG_MSG("[DEBUG] visitVarDef: 处理全局变量");
return HandleGlobalVariable(ctx, varName, sym); return HandleGlobalVariable(ctx, varName, sym);
} else { } else {
std::cerr << "[DEBUG] visitVarDef: 处理局部变量" << std::endl; DEBUG_MSG("[DEBUG] visitVarDef: 处理局部变量");
return HandleLocalVariable(ctx, varName, sym); return HandleLocalVariable(ctx, varName, sym);
} }
} }
@ -325,7 +325,7 @@ std::any IRGenImpl::visitVarDef(SysYParser::VarDefContext* ctx) {
std::any IRGenImpl::HandleGlobalVariable(SysYParser::VarDefContext* ctx, std::any IRGenImpl::HandleGlobalVariable(SysYParser::VarDefContext* ctx,
const std::string& varName, const std::string& varName,
const Symbol* sym) { const Symbol* sym) {
std::cerr << "[DEBUG] HandleGlobalVariable: 开始处理全局变量 " << varName << std::endl; DEBUG_MSG("[DEBUG] HandleGlobalVariable: 开始处理全局变量 " << varName);
if (!sym) { if (!sym) {
throw std::runtime_error(FormatError("irgen", "符号表信息缺失: " + varName)); throw std::runtime_error(FormatError("irgen", "符号表信息缺失: " + varName));
@ -349,9 +349,9 @@ std::any IRGenImpl::HandleGlobalVariable(SysYParser::VarDefContext* ctx,
const auto& dimensions = array_ty->GetDimensions(); const auto& dimensions = array_ty->GetDimensions();
size_t total_size = array_ty->GetElementCount(); size_t total_size = array_ty->GetElementCount();
std::cerr << "[DEBUG] HandleGlobalVariable: 全局数组 " << varName << " 维度: "; DEBUG_MSG("[DEBUG] HandleGlobalVariable: 全局数组 " << varName << " 维度: ");
for (int d : dimensions) std::cerr << d << " "; for (int d : dimensions) DEBUG_MSG(d << " ");
std::cerr << ", 总大小: " << total_size << std::endl; DEBUG_MSG(", 总大小: " << total_size);
// 创建全局数组 // 创建全局数组
ir::GlobalValue* global_array = module_.CreateGlobal(varName, sym->type); ir::GlobalValue* global_array = module_.CreateGlobal(varName, sym->type);
@ -359,7 +359,7 @@ std::any IRGenImpl::HandleGlobalVariable(SysYParser::VarDefContext* ctx,
// 处理初始化值(使用带维度感知的展平) // 处理初始化值(使用带维度感知的展平)
std::vector<ir::ConstantValue*> init_consts; std::vector<ir::ConstantValue*> init_consts;
if (auto* initVal = ctx->initVal()) { if (auto* initVal = ctx->initVal()) {
std::cerr << "[DEBUG] HandleGlobalVariable: 处理初始化值" << std::endl; DEBUG_MSG("[DEBUG] HandleGlobalVariable: 处理初始化值");
// 全局变量的初始化必须是常量表达式(语义检查已保证) // 全局变量的初始化必须是常量表达式(语义检查已保证)
std::vector<ir::Value*> flat_vals = FlattenInitVal( std::vector<ir::Value*> flat_vals = FlattenInitVal(
initVal, dimensions, is_float); initVal, dimensions, is_float);
@ -439,7 +439,7 @@ std::any IRGenImpl::HandleGlobalVariable(SysYParser::VarDefContext* ctx,
global_map_[varName] = global_var; global_map_[varName] = global_var;
} }
std::cerr << "[DEBUG] HandleGlobalVariable: 全局变量处理完成" << std::endl; DEBUG_MSG("[DEBUG] HandleGlobalVariable: 全局变量处理完成");
return {}; return {};
} }
@ -447,7 +447,7 @@ std::any IRGenImpl::HandleGlobalVariable(SysYParser::VarDefContext* ctx,
std::any IRGenImpl::HandleLocalVariable(SysYParser::VarDefContext* ctx, std::any IRGenImpl::HandleLocalVariable(SysYParser::VarDefContext* ctx,
const std::string& varName, const std::string& varName,
const Symbol* sym) { const Symbol* sym) {
std::cerr << "[DEBUG] HandleLocalVariable: 开始处理局部变量 " << varName << std::endl; DEBUG_MSG("[DEBUG] HandleLocalVariable: 开始处理局部变量 " << varName);
if (!sym) { if (!sym) {
throw std::runtime_error(FormatError("irgen", "符号表信息缺失: " + varName)); throw std::runtime_error(FormatError("irgen", "符号表信息缺失: " + varName));
@ -473,8 +473,8 @@ std::any IRGenImpl::HandleLocalVariable(SysYParser::VarDefContext* ctx,
const bool use_heap_storage = const bool use_heap_storage =
current_function_is_recursive_ || total_bytes > kLocalArrayHeapThresholdBytes; current_function_is_recursive_ || total_bytes > kLocalArrayHeapThresholdBytes;
std::cerr << "[DEBUG] HandleLocalVariable: 局部数组 " << varName DEBUG_MSG("[DEBUG] HandleLocalVariable: 局部数组 " << varName
<< " 总大小: " << total_size << std::endl; << " 总大小: " << total_size);
ir::Value* array_slot = nullptr; ir::Value* array_slot = nullptr;
if (use_heap_storage) { if (use_heap_storage) {
@ -520,8 +520,8 @@ std::any IRGenImpl::HandleLocalVariable(SysYParser::VarDefContext* ctx,
if (is_all_zero_init && !use_heap_storage) { if (is_all_zero_init && !use_heap_storage) {
builder_.CreateStore(module_.GetContext().GetAggregateZero(sym->type), builder_.CreateStore(module_.GetContext().GetAggregateZero(sym->type),
array_slot); array_slot);
std::cerr << "[DEBUG] HandleLocalVariable: aggregate zeroinitializer store for " DEBUG_MSG("[DEBUG] HandleLocalVariable: aggregate zeroinitializer store for "
<< varName << std::endl; << varName);
return {}; return {};
} }
@ -617,35 +617,35 @@ std::any IRGenImpl::HandleLocalVariable(SysYParser::VarDefContext* ctx,
builder_.CreateStore(init, slot); builder_.CreateStore(init, slot);
} }
std::cerr << "[DEBUG] HandleLocalVariable: 局部变量处理完成" << std::endl; DEBUG_MSG("[DEBUG] HandleLocalVariable: 局部变量处理完成");
return {}; return {};
} }
// visitInitVal: 处理初始化值 // visitInitVal: 处理初始化值
std::any IRGenImpl::visitInitVal(SysYParser::InitValContext* ctx) { std::any IRGenImpl::visitInitVal(SysYParser::InitValContext* ctx) {
std::cerr << "[DEBUG] visitInitVal: 开始处理初始化值" << std::endl; DEBUG_MSG("[DEBUG] visitInitVal: 开始处理初始化值");
if (!ctx) { if (!ctx) {
throw std::runtime_error(FormatError("irgen", "非法初始化值")); throw std::runtime_error(FormatError("irgen", "非法初始化值"));
} }
// 如果是单个表达式 // 如果是单个表达式
if (ctx->exp()) { if (ctx->exp()) {
std::cerr << "[DEBUG] visitInitVal: 处理表达式初始化" << std::endl; DEBUG_MSG("[DEBUG] visitInitVal: 处理表达式初始化");
return EvalExpr(*ctx->exp()); return EvalExpr(*ctx->exp());
} }
// 如果是聚合初始化(花括号列表) // 如果是聚合初始化(花括号列表)
else if (!ctx->initVal().empty()) { else if (!ctx->initVal().empty()) {
std::cerr << "[DEBUG] visitInitVal: 处理聚合初始化" << std::endl; DEBUG_MSG("[DEBUG] visitInitVal: 处理聚合初始化");
return ProcessNestedInitVals(ctx); return ProcessNestedInitVals(ctx);
} }
std::cerr << "[DEBUG] visitInitVal: 空初始化列表" << std::endl; DEBUG_MSG("[DEBUG] visitInitVal: 空初始化列表");
return std::vector<ir::Value*>{}; return std::vector<ir::Value*>{};
} }
// ProcessNestedInitVals: 处理嵌套聚合初始化 // ProcessNestedInitVals: 处理嵌套聚合初始化
std::vector<ir::Value*> IRGenImpl::ProcessNestedInitVals(SysYParser::InitValContext* ctx) { std::vector<ir::Value*> IRGenImpl::ProcessNestedInitVals(SysYParser::InitValContext* ctx) {
std::cerr << "[DEBUG] ProcessNestedInitVals: 开始处理嵌套初始化值" << std::endl; DEBUG_MSG("[DEBUG] ProcessNestedInitVals: 开始处理嵌套初始化值");
std::vector<ir::Value*> all_values; std::vector<ir::Value*> all_values;
for (auto* init_val : ctx->initVal()) { for (auto* init_val : ctx->initVal()) {
@ -655,18 +655,18 @@ std::vector<ir::Value*> IRGenImpl::ProcessNestedInitVals(SysYParser::InitValCont
// 尝试获取单个值 // 尝试获取单个值
ir::Value* value = std::any_cast<ir::Value*>(result); ir::Value* value = std::any_cast<ir::Value*>(result);
all_values.push_back(value); all_values.push_back(value);
std::cerr << "[DEBUG] ProcessNestedInitVals: 获取到单个值" << std::endl; DEBUG_MSG("[DEBUG] ProcessNestedInitVals: 获取到单个值");
} catch (const std::bad_any_cast&) { } catch (const std::bad_any_cast&) {
try { try {
// 尝试获取值列表(嵌套情况) // 尝试获取值列表(嵌套情况)
std::vector<ir::Value*> nested_values = std::vector<ir::Value*> nested_values =
std::any_cast<std::vector<ir::Value*>>(result); std::any_cast<std::vector<ir::Value*>>(result);
std::cerr << "[DEBUG] ProcessNestedInitVals: 获取到嵌套值列表, 大小: " DEBUG_MSG("[DEBUG] ProcessNestedInitVals: 获取到嵌套值列表, 大小: "
<< nested_values.size() << std::endl; << nested_values.size());
all_values.insert(all_values.end(), all_values.insert(all_values.end(),
nested_values.begin(), nested_values.end()); nested_values.begin(), nested_values.end());
} catch (const std::bad_any_cast&) { } catch (const std::bad_any_cast&) {
std::cerr << "[ERROR] ProcessNestedInitVals: 不支持的初始化值类型" << std::endl; DEBUG_MSG("[ERROR] ProcessNestedInitVals: 不支持的初始化值类型");
throw std::runtime_error( throw std::runtime_error(
FormatError("irgen", "不支持的初始化值类型")); FormatError("irgen", "不支持的初始化值类型"));
} }
@ -674,8 +674,8 @@ std::vector<ir::Value*> IRGenImpl::ProcessNestedInitVals(SysYParser::InitValCont
} }
} }
std::cerr << "[DEBUG] ProcessNestedInitVals: 共获取 " << all_values.size() DEBUG_MSG("[DEBUG] ProcessNestedInitVals: 共获取 " << all_values.size()
<< " 个初始化值" << std::endl; << " 个初始化值");
return all_values; return all_values;
} }

@ -23,50 +23,50 @@
// 表达式生成 // 表达式生成
ir::Value* IRGenImpl::EvalExpr(SysYParser::ExpContext& expr) { ir::Value* IRGenImpl::EvalExpr(SysYParser::ExpContext& expr) {
std::cerr << "[DEBUG IRGEN] EvalExpr: 开始处理表达式 " << expr.getText() << std::endl; DEBUG_MSG("[DEBUG IRGEN] EvalExpr: 开始处理表达式 " << expr.getText());
try { try {
auto result_any = expr.accept(this); auto result_any = expr.accept(this);
if (!result_any.has_value()) { if (!result_any.has_value()) {
std::cerr << "[ERROR] EvalExpr: result_any has no value" << std::endl; DEBUG_MSG("[ERROR] EvalExpr: result_any has no value");
throw std::runtime_error("表达式求值结果为空"); throw std::runtime_error("表达式求值结果为空");
} }
try { try {
ir::Value* result = std::any_cast<ir::Value*>(result_any); ir::Value* result = std::any_cast<ir::Value*>(result_any);
std::cerr << "[DEBUG] EvalExpr: success, result = " << (void*)result << std::endl; DEBUG_MSG("[DEBUG] EvalExpr: success, result = " << (void*)result);
return result; return result;
} catch (const std::bad_any_cast& e) { } catch (const std::bad_any_cast& e) {
std::cerr << "[ERROR] EvalExpr: bad any_cast - " << e.what() << std::endl; DEBUG_MSG("[ERROR] EvalExpr: bad any_cast - " << e.what());
std::cerr << " Type info: " << result_any.type().name() << std::endl; DEBUG_MSG(" Type info: " << result_any.type().name());
throw std::runtime_error(FormatError("irgen", "表达式求值返回了错误的类型")); throw std::runtime_error(FormatError("irgen", "表达式求值返回了错误的类型"));
} }
} catch (const std::exception& e) { } catch (const std::exception& e) {
std::cerr << "[ERROR] Exception in EvalExpr: " << e.what() << std::endl; DEBUG_MSG("[ERROR] Exception in EvalExpr: " << e.what());
throw; throw;
} }
} }
ir::Value* IRGenImpl::EvalCond(SysYParser::CondContext& cond) { ir::Value* IRGenImpl::EvalCond(SysYParser::CondContext& cond) {
std::cerr << "[DEBUG IRGEN] EvalCond: 开始处理条件表达式 " << cond.getText() << std::endl; DEBUG_MSG("[DEBUG IRGEN] EvalCond: 开始处理条件表达式 " << cond.getText());
return std::any_cast<ir::Value*>(cond.accept(this)); return std::any_cast<ir::Value*>(cond.accept(this));
} }
// 基本表达式:数字、变量、括号表达式 // 基本表达式:数字、变量、括号表达式
std::any IRGenImpl::visitPrimaryExp(SysYParser::PrimaryExpContext* ctx) { std::any IRGenImpl::visitPrimaryExp(SysYParser::PrimaryExpContext* ctx) {
std::cerr << "[DEBUG IRGEN] visitPrimaryExp: 开始处理基本表达式 " << (ctx ? ctx->getText() : "<null>") << std::endl; DEBUG_MSG("[DEBUG IRGEN] visitPrimaryExp: 开始处理基本表达式 " << (ctx ? ctx->getText() : "<null>"));
if (!ctx) { if (!ctx) {
throw std::runtime_error(FormatError("irgen", "缺少基本表达式")); throw std::runtime_error(FormatError("irgen", "缺少基本表达式"));
} }
std::cerr << "[DEBUG] visitPrimaryExp" << std::endl; DEBUG_MSG("[DEBUG] visitPrimaryExp");
// 处理数字字面量 // 处理数字字面量
if (ctx->DECIMAL_INT()) { if (ctx->DECIMAL_INT()) {
int value = std::stoi(ctx->DECIMAL_INT()->getText()); int value = std::stoi(ctx->DECIMAL_INT()->getText());
ir::Value* const_int = builder_.CreateConstInt(value); ir::Value* const_int = builder_.CreateConstInt(value);
std::cerr << "[DEBUG] visitPrimaryExp: constant int " << value DEBUG_MSG("[DEBUG] visitPrimaryExp: constant int " << value
<< " created as " << (void*)const_int << std::endl; << " created as " << (void*)const_int);
return static_cast<ir::Value*>(const_int); return static_cast<ir::Value*>(const_int);
} }
@ -76,13 +76,13 @@ std::any IRGenImpl::visitPrimaryExp(SysYParser::PrimaryExpContext* ctx) {
try { try {
value = std::stof(hex_float_str); value = std::stof(hex_float_str);
} catch (const std::exception& e) { } catch (const std::exception& e) {
std::cerr << "[WARNING] 无法解析十六进制浮点数: " << hex_float_str DEBUG_MSG("[WARNING] 无法解析十六进制浮点数: " << hex_float_str
<< "使用0.0代替" << std::endl; << "使用0.0代替");
value = 0.0f; value = 0.0f;
} }
ir::Value* const_float = builder_.CreateConstFloat(value); ir::Value* const_float = builder_.CreateConstFloat(value);
std::cerr << "[DEBUG] visitPrimaryExp: constant hex float " << value DEBUG_MSG("[DEBUG] visitPrimaryExp: constant hex float " << value
<< " created as " << (void*)const_float << std::endl; << " created as " << (void*)const_float);
return static_cast<ir::Value*>(const_float); return static_cast<ir::Value*>(const_float);
} }
@ -92,13 +92,13 @@ std::any IRGenImpl::visitPrimaryExp(SysYParser::PrimaryExpContext* ctx) {
try { try {
value = std::stof(dec_float_str); value = std::stof(dec_float_str);
} catch (const std::exception& e) { } catch (const std::exception& e) {
std::cerr << "[WARNING] 无法解析十进制浮点数: " << dec_float_str DEBUG_MSG("[WARNING] 无法解析十进制浮点数: " << dec_float_str
<< "使用0.0代替" << std::endl; << "使用0.0代替");
value = 0.0f; value = 0.0f;
} }
ir::Value* const_float = builder_.CreateConstFloat(value); ir::Value* const_float = builder_.CreateConstFloat(value);
std::cerr << "[DEBUG] visitPrimaryExp: constant dec float " << value DEBUG_MSG("[DEBUG] visitPrimaryExp: constant dec float " << value
<< " created as " << (void*)const_float << std::endl; << " created as " << (void*)const_float);
return static_cast<ir::Value*>(const_float); return static_cast<ir::Value*>(const_float);
} }
@ -106,8 +106,8 @@ std::any IRGenImpl::visitPrimaryExp(SysYParser::PrimaryExpContext* ctx) {
std::string hex = ctx->HEX_INT()->getText(); std::string hex = ctx->HEX_INT()->getText();
int value = std::stoi(hex, nullptr, 16); int value = std::stoi(hex, nullptr, 16);
ir::Value* const_int = builder_.CreateConstInt(value); ir::Value* const_int = builder_.CreateConstInt(value);
std::cerr << "[DEBUG] visitPrimaryExp: constant hex int " << value DEBUG_MSG("[DEBUG] visitPrimaryExp: constant hex int " << value
<< " created as " << (void*)const_int << std::endl; << " created as " << (void*)const_int);
return static_cast<ir::Value*>(const_int); return static_cast<ir::Value*>(const_int);
} }
@ -115,42 +115,42 @@ std::any IRGenImpl::visitPrimaryExp(SysYParser::PrimaryExpContext* ctx) {
std::string oct = ctx->OCTAL_INT()->getText(); std::string oct = ctx->OCTAL_INT()->getText();
int value = std::stoi(oct, nullptr, 8); int value = std::stoi(oct, nullptr, 8);
ir::Value* const_int = builder_.CreateConstInt(value); ir::Value* const_int = builder_.CreateConstInt(value);
std::cerr << "[DEBUG] visitPrimaryExp: constant octal int " << value DEBUG_MSG("[DEBUG] visitPrimaryExp: constant octal int " << value
<< " created as " << (void*)const_int << std::endl; << " created as " << (void*)const_int);
return static_cast<ir::Value*>(const_int); return static_cast<ir::Value*>(const_int);
} }
if (ctx->ZERO()) { if (ctx->ZERO()) {
ir::Value* const_int = builder_.CreateConstInt(0); ir::Value* const_int = builder_.CreateConstInt(0);
std::cerr << "[DEBUG] visitPrimaryExp: constant zero int created" << std::endl; DEBUG_MSG("[DEBUG] visitPrimaryExp: constant zero int created");
return static_cast<ir::Value*>(const_int); return static_cast<ir::Value*>(const_int);
} }
// 处理变量 // 处理变量
if (ctx->lVal()) { if (ctx->lVal()) {
std::cerr << "[DEBUG] visitPrimaryExp: visiting lVal" << std::endl; DEBUG_MSG("[DEBUG] visitPrimaryExp: visiting lVal");
return ctx->lVal()->accept(this); return ctx->lVal()->accept(this);
} }
// 处理括号表达式 // 处理括号表达式
if (ctx->L_PAREN() && ctx->exp()) { if (ctx->L_PAREN() && ctx->exp()) {
std::cerr << "[DEBUG] visitPrimaryExp: visiting parenthesized expression" << std::endl; DEBUG_MSG("[DEBUG] visitPrimaryExp: visiting parenthesized expression");
return EvalExpr(*ctx->exp()); return EvalExpr(*ctx->exp());
} }
std::cerr << "[ERROR] visitPrimaryExp: unsupported primary expression type" << std::endl; DEBUG_MSG("[ERROR] visitPrimaryExp: unsupported primary expression type");
throw std::runtime_error(FormatError("irgen", "不支持的基本表达式类型")); throw std::runtime_error(FormatError("irgen", "不支持的基本表达式类型"));
} }
// 左值(变量)处理 // 左值(变量)处理
std::any IRGenImpl::visitLVal(SysYParser::LValContext* ctx) { std::any IRGenImpl::visitLVal(SysYParser::LValContext* ctx) {
std::cerr << "[DEBUG IRGEN] visitLVal: 开始处理左值 " << (ctx ? ctx->getText() : "<null>") << std::endl; DEBUG_MSG("[DEBUG IRGEN] visitLVal: 开始处理左值 " << (ctx ? ctx->getText() : "<null>"));
if (!ctx || !ctx->Ident()) { if (!ctx || !ctx->Ident()) {
throw std::runtime_error(FormatError("irgen", "非法左值")); throw std::runtime_error(FormatError("irgen", "非法左值"));
} }
std::string varName = ctx->Ident()->getText(); std::string varName = ctx->Ident()->getText();
std::cerr << "[DEBUG] visitLVal: " << varName << std::endl; DEBUG_MSG("[DEBUG] visitLVal: " << varName);
// 先检查语义分析中常量绑定 // 先检查语义分析中常量绑定
const SysYParser::ConstDefContext* const_decl = sema_.ResolveConstUse(ctx); const SysYParser::ConstDefContext* const_decl = sema_.ResolveConstUse(ctx);
@ -166,7 +166,7 @@ std::any IRGenImpl::visitLVal(SysYParser::LValContext* ctx) {
// 如果是常量,直接返回常量值 // 如果是常量,直接返回常量值
if (sym && sym->kind == SymbolKind::Constant) { if (sym && sym->kind == SymbolKind::Constant) {
std::cerr << "[DEBUG] visitLVal: 找到常量 " << varName << std::endl; DEBUG_MSG("[DEBUG] visitLVal: 找到常量 " << varName);
if (sym->IsScalarConstant()) { if (sym->IsScalarConstant()) {
if (sym->type->IsInt32()) { if (sym->type->IsInt32()) {
@ -394,7 +394,7 @@ std::any IRGenImpl::visitLVal(SysYParser::LValContext* ctx) {
} }
std::any IRGenImpl::visitAddExp(SysYParser::AddExpContext* ctx) { std::any IRGenImpl::visitAddExp(SysYParser::AddExpContext* ctx) {
std::cerr << "[DEBUG IRGEN] visitAddExp: 开始处理加法表达式 " << (ctx ? ctx->getText() : "<null>") << std::endl; DEBUG_MSG("[DEBUG IRGEN] visitAddExp: 开始处理加法表达式 " << (ctx ? ctx->getText() : "<null>"));
if (!ctx) { if (!ctx) {
throw std::runtime_error(FormatError("irgen", "非法加法表达式")); throw std::runtime_error(FormatError("irgen", "非法加法表达式"));
} }
@ -418,10 +418,10 @@ std::any IRGenImpl::visitAddExp(SysYParser::AddExpContext* ctx) {
} }
ir::Value* right = std::any_cast<ir::Value*>(right_any); ir::Value* right = std::any_cast<ir::Value*>(right_any);
std::cerr << "[DEBUG] visitAddExp: left=" << (void*)left DEBUG_MSG("[DEBUG] visitAddExp: left=" << (void*)left
<< ", type=" << (left->GetType()->IsFloat() ? "float" : "int") << ", type=" << (left->GetType()->IsFloat() ? "float" : "int")
<< ", right=" << (void*)right << ", right=" << (void*)right
<< ", type=" << (right->GetType()->IsFloat() ? "float" : "int") << std::endl; << ", type=" << (right->GetType()->IsFloat() ? "float" : "int"));
// 处理类型转换:如果操作数类型不同,需要进行类型转换 // 处理类型转换:如果操作数类型不同,需要进行类型转换
if (left->GetType()->IsFloat() != right->GetType()->IsFloat()) { if (left->GetType()->IsFloat() != right->GetType()->IsFloat()) {
@ -458,7 +458,7 @@ std::any IRGenImpl::visitAddExp(SysYParser::AddExpContext* ctx) {
std::any IRGenImpl::visitMulExp(SysYParser::MulExpContext* ctx) { std::any IRGenImpl::visitMulExp(SysYParser::MulExpContext* ctx) {
std::cerr << "[DEBUG IRGEN] visitMulExp: 开始处理乘法表达式 " << (ctx ? ctx->getText() : "<null>") << std::endl; DEBUG_MSG("[DEBUG IRGEN] visitMulExp: 开始处理乘法表达式 " << (ctx ? ctx->getText() : "<null>"));
if (!ctx) { if (!ctx) {
throw std::runtime_error(FormatError("irgen", "非法乘法表达式")); throw std::runtime_error(FormatError("irgen", "非法乘法表达式"));
} }
@ -482,10 +482,10 @@ std::any IRGenImpl::visitMulExp(SysYParser::MulExpContext* ctx) {
} }
ir::Value* right = std::any_cast<ir::Value*>(right_any); ir::Value* right = std::any_cast<ir::Value*>(right_any);
std::cerr << "[DEBUG] visitMulExp: left=" << (void*)left DEBUG_MSG("[DEBUG] visitMulExp: left=" << (void*)left
<< ", type=" << (left->GetType()->IsFloat() ? "float" : "int") << ", type=" << (left->GetType()->IsFloat() ? "float" : "int")
<< ", right=" << (void*)right << ", right=" << (void*)right
<< ", type=" << (right->GetType()->IsFloat() ? "float" : "int") << std::endl; << ", type=" << (right->GetType()->IsFloat() ? "float" : "int"));
// 处理类型转换:如果操作数类型不同,需要进行类型转换 // 处理类型转换:如果操作数类型不同,需要进行类型转换
if (left->GetType()->IsFloat() != right->GetType()->IsFloat()) { if (left->GetType()->IsFloat() != right->GetType()->IsFloat()) {
@ -532,7 +532,7 @@ std::any IRGenImpl::visitMulExp(SysYParser::MulExpContext* ctx) {
// 逻辑与 // 逻辑与
std::any IRGenImpl::visitLAndExp(SysYParser::LAndExpContext* ctx) { std::any IRGenImpl::visitLAndExp(SysYParser::LAndExpContext* ctx) {
std::cerr << "[DEBUG IRGEN] visitLAndExp: 开始处理逻辑与表达式 " << (ctx ? ctx->getText() : "<null>") << std::endl; DEBUG_MSG("[DEBUG IRGEN] visitLAndExp: 开始处理逻辑与表达式 " << (ctx ? ctx->getText() : "<null>"));
if (!ctx) throw std::runtime_error(FormatError("irgen", "非法逻辑与表达式")); if (!ctx) throw std::runtime_error(FormatError("irgen", "非法逻辑与表达式"));
if (!ctx->lAndExp()) { if (!ctx->lAndExp()) {
@ -562,7 +562,7 @@ std::any IRGenImpl::visitLAndExp(SysYParser::LAndExpContext* ctx) {
// 逻辑或 // 逻辑或
std::any IRGenImpl::visitLOrExp(SysYParser::LOrExpContext* ctx) { std::any IRGenImpl::visitLOrExp(SysYParser::LOrExpContext* ctx) {
std::cerr << "[DEBUG IRGEN] visitLOrExp: 开始处理逻辑或表达式 " << (ctx ? ctx->getText() : "<null>") << std::endl; DEBUG_MSG("[DEBUG IRGEN] visitLOrExp: 开始处理逻辑或表达式 " << (ctx ? ctx->getText() : "<null>"));
if (!ctx) throw std::runtime_error(FormatError("irgen", "非法逻辑或表达式")); if (!ctx) throw std::runtime_error(FormatError("irgen", "非法逻辑或表达式"));
if (!ctx->lOrExp()) { if (!ctx->lOrExp()) {
@ -591,32 +591,32 @@ std::any IRGenImpl::visitLOrExp(SysYParser::LOrExpContext* ctx) {
} }
std::any IRGenImpl::visitExp(SysYParser::ExpContext* ctx) { std::any IRGenImpl::visitExp(SysYParser::ExpContext* ctx) {
std::cerr << "[DEBUG IRGEN] visitExp: 开始处理表达式 " << (ctx ? ctx->getText() : "<null>") << std::endl; DEBUG_MSG("[DEBUG IRGEN] visitExp: 开始处理表达式 " << (ctx ? ctx->getText() : "<null>"));
if (!ctx) throw std::runtime_error(FormatError("irgen", "非法表达式")); if (!ctx) throw std::runtime_error(FormatError("irgen", "非法表达式"));
return ctx->addExp()->accept(this); return ctx->addExp()->accept(this);
} }
std::any IRGenImpl::visitCond(SysYParser::CondContext* ctx) { std::any IRGenImpl::visitCond(SysYParser::CondContext* ctx) {
std::cerr << "[DEBUG IRGEN] visitCond: 开始处理条件 " << (ctx ? ctx->getText() : "<null>") << std::endl; DEBUG_MSG("[DEBUG IRGEN] visitCond: 开始处理条件 " << (ctx ? ctx->getText() : "<null>"));
if (!ctx) throw std::runtime_error(FormatError("irgen", "非法条件表达式")); if (!ctx) throw std::runtime_error(FormatError("irgen", "非法条件表达式"));
return ctx->lOrExp()->accept(this); return ctx->lOrExp()->accept(this);
} }
std::any IRGenImpl::visitCallExp(SysYParser::UnaryExpContext* ctx) { std::any IRGenImpl::visitCallExp(SysYParser::UnaryExpContext* ctx) {
std::cerr << "[DEBUG IRGEN] visitCallExp: 开始处理函数调用 " << (ctx ? ctx->getText() : "<null>") << std::endl; DEBUG_MSG("[DEBUG IRGEN] visitCallExp: 开始处理函数调用 " << (ctx ? ctx->getText() : "<null>"));
if (!ctx || !ctx->Ident()) { if (!ctx || !ctx->Ident()) {
throw std::runtime_error(FormatError("irgen", "非法函数调用")); throw std::runtime_error(FormatError("irgen", "非法函数调用"));
} }
std::string funcName = ctx->Ident()->getText(); std::string funcName = ctx->Ident()->getText();
std::cout << "[DEBUG IRGEN] visitCallExp: 调用函数 " << funcName << std::endl; DEBUG_MSG("[DEBUG IRGEN] visitCallExp: 调用函数 " << funcName);
// 查找函数对象 // 查找函数对象
ir::Function* callee = module_.FindFunction(funcName); ir::Function* callee = module_.FindFunction(funcName);
// 如果没找到,可能是运行时函数还没声明,尝试动态声明 // 如果没找到,可能是运行时函数还没声明,尝试动态声明
if (!callee) { if (!callee) {
std::cout << "[DEBUG IRGEN] 函数 " << funcName << " 未找到,尝试动态声明" << std::endl; DEBUG_MSG("[DEBUG IRGEN] 函数 " << funcName << " 未找到,尝试动态声明");
// 根据函数名动态创建运行时函数声明 // 根据函数名动态创建运行时函数声明
callee = CreateRuntimeFunctionDecl(funcName); callee = CreateRuntimeFunctionDecl(funcName);
@ -631,9 +631,9 @@ std::any IRGenImpl::visitCallExp(SysYParser::UnaryExpContext* ctx) {
auto argList = ctx->funcRParams()->accept(this); auto argList = ctx->funcRParams()->accept(this);
try { try {
args = std::any_cast<std::vector<ir::Value*>>(argList); args = std::any_cast<std::vector<ir::Value*>>(argList);
std::cout << "[DEBUG IRGEN] visitCallExp: 收集到 " << args.size() << " 个参数" << std::endl; DEBUG_MSG("[DEBUG IRGEN] visitCallExp: 收集到 " << args.size() << " 个参数");
} catch (const std::bad_any_cast& e) { } catch (const std::bad_any_cast& e) {
std::cerr << "[ERROR] visitCallExp: 函数调用参数类型错误: " << e.what() << std::endl; DEBUG_MSG("[ERROR] visitCallExp: 函数调用参数类型错误: " << e.what());
} }
} }
@ -673,13 +673,13 @@ std::any IRGenImpl::visitCallExp(SysYParser::UnaryExpContext* ctx) {
return static_cast<ir::Value*>(builder_.CreateConstInt(0)); return static_cast<ir::Value*>(builder_.CreateConstInt(0));
} }
std::cout << "[DEBUG IRGEN] visitCallExp: 函数调用完成,返回值 " << (void*)callResult << std::endl; DEBUG_MSG("[DEBUG IRGEN] visitCallExp: 函数调用完成,返回值 " << (void*)callResult);
return static_cast<ir::Value*>(callResult); return static_cast<ir::Value*>(callResult);
} }
// 动态创建运行时函数声明的辅助函数 // 动态创建运行时函数声明的辅助函数
ir::Function* IRGenImpl::CreateRuntimeFunctionDecl(const std::string& funcName) { ir::Function* IRGenImpl::CreateRuntimeFunctionDecl(const std::string& funcName) {
std::cerr << "[DEBUG IRGEN] CreateRuntimeFunctionDecl: 开始创建运行时函数声明 " << funcName << std::endl; DEBUG_MSG("[DEBUG IRGEN] CreateRuntimeFunctionDecl: 开始创建运行时函数声明 " << funcName);
// 根据常见运行时函数名创建对应的函数类型 // 根据常见运行时函数名创建对应的函数类型
if (funcName == "getint" || funcName == "getch") { if (funcName == "getint" || funcName == "getch") {
@ -792,7 +792,7 @@ ir::Function* IRGenImpl::CreateRuntimeFunctionDecl(const std::string& funcName)
} }
std::any IRGenImpl::visitUnaryExp(SysYParser::UnaryExpContext* ctx) { std::any IRGenImpl::visitUnaryExp(SysYParser::UnaryExpContext* ctx) {
std::cerr << "[DEBUG IRGEN] visitUnaryExp: 开始处理一元表达式 " << (ctx ? ctx->getText() : "<null>") << std::endl; DEBUG_MSG("[DEBUG IRGEN] visitUnaryExp: 开始处理一元表达式 " << (ctx ? ctx->getText() : "<null>"));
if (!ctx) { if (!ctx) {
throw std::runtime_error(FormatError("irgen", "非法一元表达式")); throw std::runtime_error(FormatError("irgen", "非法一元表达式"));
} }
@ -852,7 +852,7 @@ std::any IRGenImpl::visitUnaryExp(SysYParser::UnaryExpContext* ctx) {
// 实现函数调用 // 实现函数调用
std::any IRGenImpl::visitFuncRParams(SysYParser::FuncRParamsContext* ctx) { std::any IRGenImpl::visitFuncRParams(SysYParser::FuncRParamsContext* ctx) {
std::cerr << "[DEBUG IRGEN] visitFuncRParams: 开始处理函数参数 " << (ctx ? ctx->getText() : "<null>") << std::endl; DEBUG_MSG("[DEBUG IRGEN] visitFuncRParams: 开始处理函数参数 " << (ctx ? ctx->getText() : "<null>"));
if (!ctx) return std::vector<ir::Value*>{}; if (!ctx) return std::vector<ir::Value*>{};
std::vector<ir::Value*> args; std::vector<ir::Value*> args;
for (auto* exp : ctx->exp()) { for (auto* exp : ctx->exp()) {
@ -863,7 +863,7 @@ std::any IRGenImpl::visitFuncRParams(SysYParser::FuncRParamsContext* ctx) {
// visitConstExp - 处理常量表达式 // visitConstExp - 处理常量表达式
std::any IRGenImpl::visitConstExp(SysYParser::ConstExpContext* ctx) { std::any IRGenImpl::visitConstExp(SysYParser::ConstExpContext* ctx) {
std::cerr << "[DEBUG IRGEN] visitConstExp: 开始处理常量表达式 " << (ctx ? ctx->getText() : "<null>") << std::endl; DEBUG_MSG("[DEBUG IRGEN] visitConstExp: 开始处理常量表达式 " << (ctx ? ctx->getText() : "<null>"));
if (!ctx || !ctx->addExp()) { if (!ctx || !ctx->addExp()) {
throw std::runtime_error(FormatError("irgen", "非法常量表达式")); throw std::runtime_error(FormatError("irgen", "非法常量表达式"));
} }
@ -884,7 +884,7 @@ std::any IRGenImpl::visitConstExp(SysYParser::ConstExpContext* ctx) {
// visitConstInitVal - 处理常量初始化值 // visitConstInitVal - 处理常量初始化值
std::any IRGenImpl::visitConstInitVal(SysYParser::ConstInitValContext* ctx) { std::any IRGenImpl::visitConstInitVal(SysYParser::ConstInitValContext* ctx) {
std::cerr << "[DEBUG IRGEN] visitConstInitVal: 开始处理常量初始化值 " << (ctx ? ctx->getText() : "<null>") << std::endl; DEBUG_MSG("[DEBUG IRGEN] visitConstInitVal: 开始处理常量初始化值 " << (ctx ? ctx->getText() : "<null>"));
if (!ctx) { if (!ctx) {
throw std::runtime_error(FormatError("irgen", "非法常量初始化值")); throw std::runtime_error(FormatError("irgen", "非法常量初始化值"));
} }
@ -929,7 +929,7 @@ std::any IRGenImpl::visitConstInitVal(SysYParser::ConstInitValContext* ctx) {
} }
std::any IRGenImpl::visitRelExp(SysYParser::RelExpContext* ctx) { std::any IRGenImpl::visitRelExp(SysYParser::RelExpContext* ctx) {
std::cerr << "[DEBUG IRGEN] visitRelExp: 开始处理关系表达式 " << (ctx ? ctx->getText() : "<null>") << std::endl; DEBUG_MSG("[DEBUG IRGEN] visitRelExp: 开始处理关系表达式 " << (ctx ? ctx->getText() : "<null>"));
if (!ctx) { if (!ctx) {
throw std::runtime_error(FormatError("irgen", "非法关系表达式")); throw std::runtime_error(FormatError("irgen", "非法关系表达式"));
} }
@ -940,10 +940,10 @@ std::any IRGenImpl::visitRelExp(SysYParser::RelExpContext* ctx) {
auto* lhs = std::any_cast<ir::Value*>(left_any); auto* lhs = std::any_cast<ir::Value*>(left_any);
auto* rhs = std::any_cast<ir::Value*>(right_any); auto* rhs = std::any_cast<ir::Value*>(right_any);
std::cerr << "[DEBUG] visitRelExp: left=" << (void*)lhs DEBUG_MSG("[DEBUG] visitRelExp: left=" << (void*)lhs
<< ", type=" << (lhs->GetType()->IsFloat() ? "float" : "int") << ", type=" << (lhs->GetType()->IsFloat() ? "float" : "int")
<< ", right=" << (void*)rhs << ", right=" << (void*)rhs
<< ", type=" << (rhs->GetType()->IsFloat() ? "float" : "int") << std::endl; << ", type=" << (rhs->GetType()->IsFloat() ? "float" : "int"));
// 处理类型转换:如果操作数类型不同,需要进行类型转换 // 处理类型转换:如果操作数类型不同,需要进行类型转换
if (lhs->GetType()->IsFloat() != rhs->GetType()->IsFloat()) { if (lhs->GetType()->IsFloat() != rhs->GetType()->IsFloat()) {
@ -1004,7 +1004,7 @@ std::any IRGenImpl::visitRelExp(SysYParser::RelExpContext* ctx) {
} }
std::any IRGenImpl::visitEqExp(SysYParser::EqExpContext* ctx) { std::any IRGenImpl::visitEqExp(SysYParser::EqExpContext* ctx) {
std::cerr << "[DEBUG IRGEN] visitEqExp: 开始处理相等表达式 " << (ctx ? ctx->getText() : "<null>") << std::endl; DEBUG_MSG("[DEBUG IRGEN] visitEqExp: 开始处理相等表达式 " << (ctx ? ctx->getText() : "<null>"));
if (!ctx) { if (!ctx) {
throw std::runtime_error(FormatError("irgen", "非法相等表达式")); throw std::runtime_error(FormatError("irgen", "非法相等表达式"));
} }
@ -1015,10 +1015,10 @@ std::any IRGenImpl::visitEqExp(SysYParser::EqExpContext* ctx) {
auto* lhs = std::any_cast<ir::Value*>(left_any); auto* lhs = std::any_cast<ir::Value*>(left_any);
auto* rhs = std::any_cast<ir::Value*>(right_any); auto* rhs = std::any_cast<ir::Value*>(right_any);
std::cerr << "[DEBUG] visitEqExp: left=" << (void*)lhs DEBUG_MSG("[DEBUG] visitEqExp: left=" << (void*)lhs
<< ", type=" << (lhs->GetType()->IsFloat() ? "float" : "int") << ", type=" << (lhs->GetType()->IsFloat() ? "float" : "int")
<< ", right=" << (void*)rhs << ", right=" << (void*)rhs
<< ", type=" << (rhs->GetType()->IsFloat() ? "float" : "int") << std::endl; << ", type=" << (rhs->GetType()->IsFloat() ? "float" : "int"));
// 处理类型转换:如果操作数类型不同,需要进行类型转换 // 处理类型转换:如果操作数类型不同,需要进行类型转换
if (lhs->GetType()->IsFloat() != rhs->GetType()->IsFloat()) { if (lhs->GetType()->IsFloat() != rhs->GetType()->IsFloat()) {
@ -1062,8 +1062,8 @@ std::any IRGenImpl::visitEqExp(SysYParser::EqExpContext* ctx) {
ir::Value* IRGenImpl::EvalAssign(SysYParser::StmtContext* ctx) { ir::Value* IRGenImpl::EvalAssign(SysYParser::StmtContext* ctx) {
std::cerr << "[DEBUG IRGEN] EvalAssign: 开始处理赋值语句 " << (ctx ? ctx->getText() : "<null>") << std::endl; DEBUG_MSG("[DEBUG IRGEN] EvalAssign: 开始处理赋值语句 " << (ctx ? ctx->getText() : "<null>"));
std::cout << "[DEBUG IRGEN] visitCond: " << (ctx ? ctx->getText() : "<null>") << std::endl; DEBUG_MSG("[DEBUG IRGEN] visitCond: " << (ctx ? ctx->getText() : "<null>"));
if (!ctx || !ctx->lVal() || !ctx->exp()) { if (!ctx || !ctx->lVal() || !ctx->exp()) {
throw std::runtime_error(FormatError("irgen", "非法赋值语句")); throw std::runtime_error(FormatError("irgen", "非法赋值语句"));
} }
@ -1127,12 +1127,12 @@ ir::Value* IRGenImpl::EvalAssign(SysYParser::StmtContext* ctx) {
} else { } else {
// 普通标量赋值 // 普通标量赋值
// 调试输出指针类型 // 调试输出指针类型
std::cerr << "[DEBUG] base_ptr type: " << base_ptr->GetType() << std::endl; DEBUG_MSG("[DEBUG] base_ptr type: " << base_ptr->GetType());
std::cerr << "[DEBUG] rhs type: " << rhs->GetType()<< std::endl; DEBUG_MSG("[DEBUG] rhs type: " << rhs->GetType());
// 如果 base_ptr 不是标量指针类型,可能需要特殊处理 // 如果 base_ptr 不是标量指针类型,可能需要特殊处理
if (!base_ptr->GetType()->IsPtrInt32() && !base_ptr->GetType()->IsPtrFloat()) { if (!base_ptr->GetType()->IsPtrInt32() && !base_ptr->GetType()->IsPtrFloat()) {
std::cerr << "[ERROR] base_ptr is not a pointer type!" << std::endl; DEBUG_MSG("[ERROR] base_ptr is not a pointer type!");
throw std::runtime_error("尝试存储到非指针类型"); throw std::runtime_error("尝试存储到非指针类型");
} }
rhs = convert_for_store(rhs, base_ptr); rhs = convert_for_store(rhs, base_ptr);

@ -54,7 +54,7 @@ IRGenImpl::IRGenImpl(ir::Module& module,
} }
void IRGenImpl::AddRuntimeFunctions() { void IRGenImpl::AddRuntimeFunctions() {
std::cerr << "[DEBUG IRGEN] 添加运行时库函数声明" << std::endl; DEBUG_MSG("[DEBUG IRGEN] 添加运行时库函数声明");
// 输入函数(返回 int // 输入函数(返回 int
module_.CreateFunction("getint", module_.CreateFunction("getint",
@ -155,21 +155,21 @@ void IRGenImpl::AddRuntimeFunctions() {
ir::Type::GetVoidType(), ir::Type::GetVoidType(),
{ir::Type::GetPtrFloatType(), ir::Type::GetInt32Type()})); {ir::Type::GetPtrFloatType(), ir::Type::GetInt32Type()}));
std::cerr << "[DEBUG IRGEN] 运行时库函数声明完成" << std::endl; DEBUG_MSG("[DEBUG IRGEN] 运行时库函数声明完成");
} }
// 修正:没有 mainFuncDef通过函数名找到 main // 修正:没有 mainFuncDef通过函数名找到 main
std::any IRGenImpl::visitCompUnit(SysYParser::CompUnitContext* ctx) { std::any IRGenImpl::visitCompUnit(SysYParser::CompUnitContext* ctx) {
std::cerr << "[DEBUG IRGEN] visitCompUnit" << std::endl; DEBUG_MSG("[DEBUG IRGEN] visitCompUnit");
std::cerr << "[DEBUG] IRGen: 符号表地址 = " << &symbol_table_ << std::endl; DEBUG_MSG("[DEBUG] IRGen: 符号表地址 = " << &symbol_table_);
std::cerr << "[DEBUG] IRGen: 开始生成 IR" << std::endl; DEBUG_MSG("[DEBUG] IRGen: 开始生成 IR");
// 尝试查找 main 函数 // 尝试查找 main 函数
const Symbol* main_sym = symbol_table_.lookup("main"); const Symbol* main_sym = symbol_table_.lookup("main");
if (main_sym) { if (main_sym) {
std::cerr << "[DEBUG] IRGen: 找到 main 函数符号" << std::endl; DEBUG_MSG("[DEBUG] IRGen: 找到 main 函数符号");
} else { } else {
std::cerr << "[DEBUG] IRGen: 未找到 main 函数符号" << std::endl; DEBUG_MSG("[DEBUG] IRGen: 未找到 main 函数符号");
} }
if (!ctx) { if (!ctx) {
throw std::runtime_error(FormatError("irgen", "缺少编译单元")); throw std::runtime_error(FormatError("irgen", "缺少编译单元"));
@ -193,7 +193,7 @@ std::any IRGenImpl::visitCompUnit(SysYParser::CompUnitContext* ctx) {
} }
std::any IRGenImpl::visitFuncDef(SysYParser::FuncDefContext* ctx) { std::any IRGenImpl::visitFuncDef(SysYParser::FuncDefContext* ctx) {
std::cerr << "[DEBUG IRGEN] visitFuncDef: " << (ctx && ctx->Ident() ? ctx->Ident()->getText() : "<null>") << std::endl; DEBUG_MSG("[DEBUG IRGEN] visitFuncDef: " << (ctx && ctx->Ident() ? ctx->Ident()->getText() : "<null>"));
if (!ctx) { if (!ctx) {
throw std::runtime_error(FormatError("irgen", "缺少函数定义")); throw std::runtime_error(FormatError("irgen", "缺少函数定义"));
} }
@ -255,25 +255,25 @@ std::any IRGenImpl::visitFuncDef(SysYParser::FuncDefContext* ctx) {
auto func_type = ir::Type::GetFunctionType(ret_type, param_types); auto func_type = ir::Type::GetFunctionType(ret_type, param_types);
// 调试输出 // 调试输出
std::cerr << "[DEBUG] visitFuncDef: 创建函数 " << funcName DEBUG_MSG("[DEBUG] visitFuncDef: 创建函数 " << funcName
<< ",返回类型: " << (ret_type->IsVoid() ? "void" : ret_type->IsFloat() ? "float" : "int") << ",返回类型: " << (ret_type->IsVoid() ? "void" : ret_type->IsFloat() ? "float" : "int")
<< ",参数数量: " << param_types.size() << std::endl; << ",参数数量: " << param_types.size());
// 创建函数对象 // 创建函数对象
func_ = module_.CreateFunction(funcName, func_type); func_ = module_.CreateFunction(funcName, func_type);
// 检查函数是否成功创建 // 检查函数是否成功创建
if (!func_) { if (!func_) {
std::cerr << "[ERROR] visitFuncDef: 创建函数失败func_ 为 nullptr!" << std::endl; DEBUG_MSG("[ERROR] visitFuncDef: 创建函数失败func_ 为 nullptr!");
throw std::runtime_error(FormatError("irgen", "创建函数失败: " + funcName)); throw std::runtime_error(FormatError("irgen", "创建函数失败: " + funcName));
} }
std::cerr << "[DEBUG] visitFuncDef: 函数对象地址: " << (void*)func_ << std::endl; DEBUG_MSG("[DEBUG] visitFuncDef: 函数对象地址: " << (void*)func_);
// 设置插入点 // 设置插入点
auto* entry_block = func_->GetEntry(); auto* entry_block = func_->GetEntry();
if (!entry_block) { if (!entry_block) {
std::cerr << "[ERROR] visitFuncDef: 函数入口基本块为空!" << std::endl; DEBUG_MSG("[ERROR] visitFuncDef: 函数入口基本块为空!");
throw std::runtime_error(FormatError("irgen", "函数入口基本块为空: " + funcName)); throw std::runtime_error(FormatError("irgen", "函数入口基本块为空: " + funcName));
} }
@ -324,15 +324,15 @@ std::any IRGenImpl::visitFuncDef(SysYParser::FuncDefContext* ctx) {
// 检查函数对象是否有效 // 检查函数对象是否有效
if (!func_) { if (!func_) {
std::cerr << "[ERROR] visitFuncDef: func_ 在添加参数时变为 nullptr!" << std::endl; DEBUG_MSG("[ERROR] visitFuncDef: func_ 在添加参数时变为 nullptr!");
throw std::runtime_error(FormatError("irgen", "函数对象无效")); throw std::runtime_error(FormatError("irgen", "函数对象无效"));
} }
std::cerr << "[DEBUG] visitFuncDef: 为函数 " << funcName DEBUG_MSG("[DEBUG] visitFuncDef: 为函数 " << funcName
<< " 添加参数 " << name << ",类型: " << " 添加参数 " << name << ",类型: "
<< (param_ty->IsInt32() ? "int32" : param_ty->IsFloat() ? "float" : << (param_ty->IsInt32() ? "int32" : param_ty->IsFloat() ? "float" :
param_ty->IsPtrInt32() ? "ptr_int32" : param_ty->IsPtrFloat() ? "ptr_float" : "other") param_ty->IsPtrInt32() ? "ptr_int32" : param_ty->IsPtrFloat() ? "ptr_float" : "other")
<< std::endl; );
// 创建参数并添加到函数 // 创建参数并添加到函数
auto arg = std::make_unique<ir::Argument>(param_ty, name); auto arg = std::make_unique<ir::Argument>(param_ty, name);
@ -344,7 +344,7 @@ std::any IRGenImpl::visitFuncDef(SysYParser::FuncDefContext* ctx) {
auto* added_arg = func_->AddArgument(std::move(arg)); auto* added_arg = func_->AddArgument(std::move(arg));
if (!added_arg) { if (!added_arg) {
std::cerr << "[ERROR] visitFuncDef: AddArgument 返回 nullptr!" << std::endl; DEBUG_MSG("[ERROR] visitFuncDef: AddArgument 返回 nullptr!");
throw std::runtime_error(FormatError("irgen", "添加参数失败: " + name)); throw std::runtime_error(FormatError("irgen", "添加参数失败: " + name));
} }
@ -371,17 +371,17 @@ std::any IRGenImpl::visitFuncDef(SysYParser::FuncDefContext* ctx) {
pointer_param_names_.erase(name); pointer_param_names_.erase(name);
} }
std::cerr << "[DEBUG] visitFuncDef: 参数 " << name << " 处理完成" << std::endl; DEBUG_MSG("[DEBUG] visitFuncDef: 参数 " << name << " 处理完成");
} }
} }
// 生成函数体 // 生成函数体
std::cerr << "[DEBUG] visitFuncDef: 开始生成函数体" << std::endl; DEBUG_MSG("[DEBUG] visitFuncDef: 开始生成函数体");
ctx->block()->accept(this); ctx->block()->accept(this);
// 如果当前插入块没有终止指令,添加默认返回 // 如果当前插入块没有终止指令,添加默认返回
if (auto* cur = builder_.GetInsertBlock(); cur && !cur->HasTerminator()) { if (auto* cur = builder_.GetInsertBlock(); cur && !cur->HasTerminator()) {
std::cerr << "[DEBUG] visitFuncDef: 函数体没有终止指令,添加默认返回" << std::endl; DEBUG_MSG("[DEBUG] visitFuncDef: 函数体没有终止指令,添加默认返回");
if (function_cleanup_block_) { if (function_cleanup_block_) {
if (ret_type->IsFloat()) { if (ret_type->IsFloat()) {
builder_.CreateStore(builder_.CreateConstFloat(0.0f), function_return_slot_); builder_.CreateStore(builder_.CreateConstFloat(0.0f), function_return_slot_);
@ -416,11 +416,11 @@ std::any IRGenImpl::visitFuncDef(SysYParser::FuncDefContext* ctx) {
try { try {
VerifyFunctionStructure(*func_); VerifyFunctionStructure(*func_);
} catch (const std::exception& e) { } catch (const std::exception& e) {
std::cerr << "[ERROR] visitFuncDef: 验证函数结构失败: " << e.what() << std::endl; DEBUG_MSG("[ERROR] visitFuncDef: 验证函数结构失败: " << e.what());
throw; throw;
} }
std::cerr << "[DEBUG] visitFuncDef: 函数 " << funcName << " 生成完成" << std::endl; DEBUG_MSG("[DEBUG] visitFuncDef: 函数 " << funcName << " 生成完成");
func_ = nullptr; func_ = nullptr;
current_function_name_.clear(); current_function_name_.clear();
current_function_is_recursive_ = false; current_function_is_recursive_ = false;
@ -467,7 +467,7 @@ ir::AllocaInst* IRGenImpl::CreateEntryAllocaFloat(const std::string& name) {
std::any IRGenImpl::visitBlock(SysYParser::BlockContext* ctx) { std::any IRGenImpl::visitBlock(SysYParser::BlockContext* ctx) {
std::cerr << "[DEBUG IRGEN] visitBlock: " << (ctx ? ctx->getText() : "<null>") << std::endl; DEBUG_MSG("[DEBUG IRGEN] visitBlock: " << (ctx ? ctx->getText() : "<null>"));
if (!ctx) { if (!ctx) {
throw std::runtime_error(FormatError("irgen", "缺少语句块")); throw std::runtime_error(FormatError("irgen", "缺少语句块"));
} }
@ -482,8 +482,8 @@ std::any IRGenImpl::visitBlock(SysYParser::BlockContext* ctx) {
} }
auto* cur = builder_.GetInsertBlock(); auto* cur = builder_.GetInsertBlock();
std::cerr << "[DEBUG] current insert block: " DEBUG_MSG("[DEBUG] current insert block: "
<< (cur ? cur->GetName() : "<null>") << std::endl; << (cur ? cur->GetName() : "<null>"));
if (cur && cur->HasTerminator()) { if (cur && cur->HasTerminator()) {
break; break;
} }
@ -500,7 +500,7 @@ IRGenImpl::BlockFlow IRGenImpl::VisitBlockItemResult(
} }
// 用于遍历块内项,返回是否继续访问后续项(如遇到 return/break/continue 则终止访问) // 用于遍历块内项,返回是否继续访问后续项(如遇到 return/break/continue 则终止访问)
std::any IRGenImpl::visitBlockItem(SysYParser::BlockItemContext* ctx) { std::any IRGenImpl::visitBlockItem(SysYParser::BlockItemContext* ctx) {
std::cerr << "[DEBUG IRGEN] visitBlockItem: " << (ctx ? ctx->getText() : "<null>") << std::endl; DEBUG_MSG("[DEBUG IRGEN] visitBlockItem: " << (ctx ? ctx->getText() : "<null>"));
if (!ctx) { if (!ctx) {
throw std::runtime_error(FormatError("irgen", "缺少块内项")); throw std::runtime_error(FormatError("irgen", "缺少块内项"));
} }

@ -16,7 +16,7 @@
// - 空语句、块语句嵌套分发之外的更多语句形态 // - 空语句、块语句嵌套分发之外的更多语句形态
std::any IRGenImpl::visitStmt(SysYParser::StmtContext* ctx) { std::any IRGenImpl::visitStmt(SysYParser::StmtContext* ctx) {
std::cerr << "[DEBUG IRGEN] visitStmt: " << (ctx ? ctx->getText() : "<null>") << std::endl; DEBUG_MSG("[DEBUG IRGEN] visitStmt: " << (ctx ? ctx->getText() : "<null>"));
if (!ctx) { if (!ctx) {
throw std::runtime_error(FormatError("irgen", "缺少语句")); throw std::runtime_error(FormatError("irgen", "缺少语句"));
} }
@ -65,7 +65,7 @@ std::any IRGenImpl::visitStmt(SysYParser::StmtContext* ctx) {
// 修改 HandleReturnStmt 函数 // 修改 HandleReturnStmt 函数
IRGenImpl::BlockFlow IRGenImpl::HandleReturnStmt(SysYParser::StmtContext* ctx) { IRGenImpl::BlockFlow IRGenImpl::HandleReturnStmt(SysYParser::StmtContext* ctx) {
std::cerr << "[DEBUG IRGEN] HandleReturnStmt: " << (ctx ? ctx->getText() : "<null>") << std::endl; DEBUG_MSG("[DEBUG IRGEN] HandleReturnStmt: " << (ctx ? ctx->getText() : "<null>"));
if (!ctx) { if (!ctx) {
throw std::runtime_error(FormatError("irgen", "缺少 return 语句")); throw std::runtime_error(FormatError("irgen", "缺少 return 语句"));
} }
@ -132,7 +132,7 @@ IRGenImpl::BlockFlow IRGenImpl::HandleReturnStmt(SysYParser::StmtContext* ctx) {
// if语句待实现 // if语句待实现
IRGenImpl::BlockFlow IRGenImpl::HandleIfStmt(SysYParser::StmtContext* ctx) { IRGenImpl::BlockFlow IRGenImpl::HandleIfStmt(SysYParser::StmtContext* ctx) {
std::cerr << "[DEBUG IRGEN] HandleIfStmt: " << (ctx ? ctx->getText() : "<null>") << std::endl; DEBUG_MSG("[DEBUG IRGEN] HandleIfStmt: " << (ctx ? ctx->getText() : "<null>"));
auto* cond = ctx->cond(); auto* cond = ctx->cond();
auto* thenStmt = ctx->stmt(0); auto* thenStmt = ctx->stmt(0);
@ -148,11 +148,11 @@ IRGenImpl::BlockFlow IRGenImpl::HandleIfStmt(SysYParser::StmtContext* ctx) {
auto* elseBlock = (ctx->Else() && elseStmt) ? func_->CreateBlock(uniq("else")) : nullptr; auto* elseBlock = (ctx->Else() && elseStmt) ? func_->CreateBlock(uniq("else")) : nullptr;
auto* mergeBlock = func_->CreateBlock(uniq("merge")); auto* mergeBlock = func_->CreateBlock(uniq("merge"));
std::cerr << "[DEBUG IF] thenBlock: " << thenBlock->GetName() << std::endl; DEBUG_MSG("[DEBUG IF] thenBlock: " << thenBlock->GetName());
if (elseBlock) std::cerr << "[DEBUG IF] elseBlock: " << elseBlock->GetName() << std::endl; if (elseBlock) DEBUG_MSG("[DEBUG IF] elseBlock: " << elseBlock->GetName());
std::cerr << "[DEBUG IF] mergeBlock: " << mergeBlock->GetName() << std::endl; DEBUG_MSG("[DEBUG IF] mergeBlock: " << mergeBlock->GetName());
std::cerr << "[DEBUG IF] current insert block before cond: " DEBUG_MSG("[DEBUG IF] current insert block before cond: "
<< builder_.GetInsertBlock()->GetName() << std::endl; << builder_.GetInsertBlock()->GetName());
// 生成条件 // 生成条件
auto* condValue = EvalCond(*cond); auto* condValue = EvalCond(*cond);
@ -168,74 +168,74 @@ IRGenImpl::BlockFlow IRGenImpl::HandleIfStmt(SysYParser::StmtContext* ctx) {
// 创建条件跳转 // 创建条件跳转
if (elseBlock) { if (elseBlock) {
std::cerr << "[DEBUG IF] Creating condbr: " << condValue->GetName() DEBUG_MSG("[DEBUG IF] Creating condbr: " << condValue->GetName()
<< " -> " << thenBlock->GetName() << ", " << elseBlock->GetName() << std::endl; << " -> " << thenBlock->GetName() << ", " << elseBlock->GetName());
builder_.CreateCondBr(condValue, thenBlock, elseBlock); builder_.CreateCondBr(condValue, thenBlock, elseBlock);
} else { } else {
std::cerr << "[DEBUG IF] Creating condbr: " << condValue->GetName() DEBUG_MSG("[DEBUG IF] Creating condbr: " << condValue->GetName()
<< " -> " << thenBlock->GetName() << ", " << mergeBlock->GetName() << std::endl; << " -> " << thenBlock->GetName() << ", " << mergeBlock->GetName());
builder_.CreateCondBr(condValue, thenBlock, mergeBlock); builder_.CreateCondBr(condValue, thenBlock, mergeBlock);
} }
// 生成 then 分支 // 生成 then 分支
std::cerr << "[DEBUG IF] Generating then branch in block: " << thenBlock->GetName() << std::endl; DEBUG_MSG("[DEBUG IF] Generating then branch in block: " << thenBlock->GetName());
builder_.SetInsertPoint(thenBlock); builder_.SetInsertPoint(thenBlock);
auto thenResult = thenStmt->accept(this); auto thenResult = thenStmt->accept(this);
bool thenTerminated = (std::any_cast<BlockFlow>(thenResult) == BlockFlow::Terminated); bool thenTerminated = (std::any_cast<BlockFlow>(thenResult) == BlockFlow::Terminated);
std::cerr << "[DEBUG IF] then branch terminated: " << thenTerminated << std::endl; DEBUG_MSG("[DEBUG IF] then branch terminated: " << thenTerminated);
if (!thenTerminated) { if (!thenTerminated) {
std::cerr << "[DEBUG IF] Adding br to merge block from then" << std::endl; DEBUG_MSG("[DEBUG IF] Adding br to merge block from then");
builder_.CreateBr(mergeBlock); builder_.CreateBr(mergeBlock);
} }
std::cerr << "[DEBUG IF] then block has terminator: " << thenBlock->HasTerminator() << std::endl; DEBUG_MSG("[DEBUG IF] then block has terminator: " << thenBlock->HasTerminator());
// 生成 else 分支 // 生成 else 分支
bool elseTerminated = false; bool elseTerminated = false;
if (elseBlock) { if (elseBlock) {
std::cout << "[DEBUG IF] Generating else branch in block: " << elseBlock->GetName() << std::endl; DEBUG_MSG("[DEBUG IF] Generating else branch in block: " << elseBlock->GetName());
builder_.SetInsertPoint(elseBlock); builder_.SetInsertPoint(elseBlock);
auto elseResult = elseStmt->accept(this); auto elseResult = elseStmt->accept(this);
elseTerminated = (std::any_cast<BlockFlow>(elseResult) == BlockFlow::Terminated); elseTerminated = (std::any_cast<BlockFlow>(elseResult) == BlockFlow::Terminated);
std::cout << "[DEBUG IF] else branch terminated: " << elseTerminated << std::endl; DEBUG_MSG("[DEBUG IF] else branch terminated: " << elseTerminated);
if (!elseTerminated) { if (!elseTerminated) {
std::cout << "[DEBUG IF] Adding br to merge block from else" << std::endl; DEBUG_MSG("[DEBUG IF] Adding br to merge block from else");
builder_.CreateBr(mergeBlock); builder_.CreateBr(mergeBlock);
} }
std::cout << "[DEBUG IF] else block has terminator: " << elseBlock->HasTerminator() << std::endl; DEBUG_MSG("[DEBUG IF] else block has terminator: " << elseBlock->HasTerminator());
} }
// 决定后续插入点 // 决定后续插入点
std::cout << "[DEBUG IF] thenTerminated=" << thenTerminated DEBUG_MSG("[DEBUG IF] thenTerminated=" << thenTerminated
<< ", elseTerminated=" << elseTerminated << std::endl; << ", elseTerminated=" << elseTerminated);
if (elseBlock) { if (elseBlock) {
std::cout << "[DEBUG IF] Setting insert point to merge block: " DEBUG_MSG("[DEBUG IF] Setting insert point to merge block: "
<< mergeBlock->GetName() << std::endl; << mergeBlock->GetName());
builder_.SetInsertPoint(mergeBlock); builder_.SetInsertPoint(mergeBlock);
} else { } else {
std::cout << "[DEBUG IF] No else, setting insert point to merge block: " DEBUG_MSG("[DEBUG IF] No else, setting insert point to merge block: "
<< mergeBlock->GetName() << std::endl; << mergeBlock->GetName());
builder_.SetInsertPoint(mergeBlock); builder_.SetInsertPoint(mergeBlock);
} }
std::cout << "[DEBUG IF] Final insert block: " DEBUG_MSG("[DEBUG IF] Final insert block: "
<< builder_.GetInsertBlock()->GetName() << std::endl; << builder_.GetInsertBlock()->GetName());
return BlockFlow::Continue; return BlockFlow::Continue;
} }
// while语句待实现IRGenImpl::BlockFlow IRGenImpl::HandleWhileStmt(SysYParser::StmtContext* ctx) { // while语句待实现IRGenImpl::BlockFlow IRGenImpl::HandleWhileStmt(SysYParser::StmtContext* ctx) {
IRGenImpl::BlockFlow IRGenImpl::HandleWhileStmt(SysYParser::StmtContext* ctx) { IRGenImpl::BlockFlow IRGenImpl::HandleWhileStmt(SysYParser::StmtContext* ctx) {
std::cout << "[DEBUG IRGEN] HandleWhileStmt: " << (ctx ? ctx->getText() : "<null>") << std::endl; DEBUG_MSG("[DEBUG IRGEN] HandleWhileStmt: " << (ctx ? ctx->getText() : "<null>"));
if (!ctx || !ctx->cond() || !ctx->stmt(0)) { if (!ctx || !ctx->cond() || !ctx->stmt(0)) {
throw std::runtime_error(FormatError("irgen", "非法 while 语句")); throw std::runtime_error(FormatError("irgen", "非法 while 语句"));
} }
std::cout << "[DEBUG WHILE] Current insert block before while: " DEBUG_MSG("[DEBUG WHILE] Current insert block before while: "
<< builder_.GetInsertBlock()->GetName() << std::endl; << builder_.GetInsertBlock()->GetName());
auto uniq = [&](const std::string& prefix) { auto uniq = [&](const std::string& prefix) {
std::string t = module_.GetContext().NextTemp(); std::string t = module_.GetContext().NextTemp();
@ -246,18 +246,18 @@ IRGenImpl::BlockFlow IRGenImpl::HandleWhileStmt(SysYParser::StmtContext* ctx) {
auto* bodyBlock = func_->CreateBlock(uniq("while.body")); auto* bodyBlock = func_->CreateBlock(uniq("while.body"));
auto* exitBlock = func_->CreateBlock(uniq("while.exit")); auto* exitBlock = func_->CreateBlock(uniq("while.exit"));
std::cout << "[DEBUG WHILE] condBlock: " << condBlock->GetName() << std::endl; DEBUG_MSG("[DEBUG WHILE] condBlock: " << condBlock->GetName());
std::cout << "[DEBUG WHILE] bodyBlock: " << bodyBlock->GetName() << std::endl; DEBUG_MSG("[DEBUG WHILE] bodyBlock: " << bodyBlock->GetName());
std::cout << "[DEBUG WHILE] exitBlock: " << exitBlock->GetName() << std::endl; DEBUG_MSG("[DEBUG WHILE] exitBlock: " << exitBlock->GetName());
std::cout << "[DEBUG WHILE] Adding br to condBlock from current block" << std::endl; DEBUG_MSG("[DEBUG WHILE] Adding br to condBlock from current block");
builder_.CreateBr(condBlock); builder_.CreateBr(condBlock);
loopStack_.push_back({condBlock, bodyBlock, exitBlock}); loopStack_.push_back({condBlock, bodyBlock, exitBlock});
std::cout << "[DEBUG WHILE] loopStack size: " << loopStack_.size() << std::endl; DEBUG_MSG("[DEBUG WHILE] loopStack size: " << loopStack_.size());
// 条件块 // 条件块
std::cout << "[DEBUG WHILE] Generating condition in block: " << condBlock->GetName() << std::endl; DEBUG_MSG("[DEBUG WHILE] Generating condition in block: " << condBlock->GetName());
builder_.SetInsertPoint(condBlock); builder_.SetInsertPoint(condBlock);
auto* condValue = EvalCond(*ctx->cond()); auto* condValue = EvalCond(*ctx->cond());
if (!condValue->GetType()->IsInt1()) { if (!condValue->GetType()->IsInt1()) {
@ -270,45 +270,45 @@ IRGenImpl::BlockFlow IRGenImpl::HandleWhileStmt(SysYParser::StmtContext* ctx) {
} }
} }
builder_.CreateCondBr(condValue, bodyBlock, exitBlock); builder_.CreateCondBr(condValue, bodyBlock, exitBlock);
std::cout << "[DEBUG WHILE] condBlock has terminator: " << condBlock->HasTerminator() << std::endl; DEBUG_MSG("[DEBUG WHILE] condBlock has terminator: " << condBlock->HasTerminator());
// 循环体 // 循环体
std::cout << "[DEBUG WHILE] Generating body in block: " << bodyBlock->GetName() << std::endl; DEBUG_MSG("[DEBUG WHILE] Generating body in block: " << bodyBlock->GetName());
builder_.SetInsertPoint(bodyBlock); builder_.SetInsertPoint(bodyBlock);
auto bodyResult = ctx->stmt(0)->accept(this); auto bodyResult = ctx->stmt(0)->accept(this);
bool bodyTerminated = (std::any_cast<BlockFlow>(bodyResult) == BlockFlow::Terminated); bool bodyTerminated = (std::any_cast<BlockFlow>(bodyResult) == BlockFlow::Terminated);
std::cout << "[DEBUG WHILE] body terminated: " << bodyTerminated << std::endl; DEBUG_MSG("[DEBUG WHILE] body terminated: " << bodyTerminated);
if (!bodyTerminated) { if (!bodyTerminated) {
std::cout << "[DEBUG WHILE] Adding br to condBlock from body" << std::endl; DEBUG_MSG("[DEBUG WHILE] Adding br to condBlock from body");
builder_.CreateBr(condBlock); builder_.CreateBr(condBlock);
} }
std::cout << "[DEBUG WHILE] bodyBlock has terminator: " << bodyBlock->HasTerminator() << std::endl; DEBUG_MSG("[DEBUG WHILE] bodyBlock has terminator: " << bodyBlock->HasTerminator());
loopStack_.pop_back(); loopStack_.pop_back();
std::cout << "[DEBUG WHILE] loopStack size after pop: " << loopStack_.size() << std::endl; DEBUG_MSG("[DEBUG WHILE] loopStack size after pop: " << loopStack_.size());
// 设置插入点为 exitBlock // 设置插入点为 exitBlock
std::cout << "[DEBUG WHILE] Setting insert point to exitBlock: " << exitBlock->GetName() << std::endl; DEBUG_MSG("[DEBUG WHILE] Setting insert point to exitBlock: " << exitBlock->GetName());
builder_.SetInsertPoint(exitBlock); builder_.SetInsertPoint(exitBlock);
std::cout << "[DEBUG WHILE] exitBlock has terminator before return: " DEBUG_MSG("[DEBUG WHILE] exitBlock has terminator before return: "
<< exitBlock->HasTerminator() << std::endl; << exitBlock->HasTerminator());
return BlockFlow::Continue; return BlockFlow::Continue;
} }
// break语句待实现 // break语句待实现
IRGenImpl::BlockFlow IRGenImpl::HandleBreakStmt(SysYParser::StmtContext* ctx) { IRGenImpl::BlockFlow IRGenImpl::HandleBreakStmt(SysYParser::StmtContext* ctx) {
std::cout << "[DEBUG IRGEN] HandleBreakStmt: " << (ctx ? ctx->getText() : "<null>") << std::endl; DEBUG_MSG("[DEBUG IRGEN] HandleBreakStmt: " << (ctx ? ctx->getText() : "<null>"));
if (loopStack_.empty()) { if (loopStack_.empty()) {
throw std::runtime_error(FormatError("irgen", "break 语句不在循环中")); throw std::runtime_error(FormatError("irgen", "break 语句不在循环中"));
} }
std::cout << "[DEBUG BREAK] Current insert block before break: " DEBUG_MSG("[DEBUG BREAK] Current insert block before break: "
<< builder_.GetInsertBlock()->GetName() << std::endl; << builder_.GetInsertBlock()->GetName());
std::cout << "[DEBUG BREAK] Breaking to exitBlock: " DEBUG_MSG("[DEBUG BREAK] Breaking to exitBlock: "
<< loopStack_.back().exitBlock->GetName() << std::endl; << loopStack_.back().exitBlock->GetName());
// 跳转到循环退出块 // 跳转到循环退出块
builder_.CreateBr(loopStack_.back().exitBlock); builder_.CreateBr(loopStack_.back().exitBlock);
@ -318,16 +318,16 @@ IRGenImpl::BlockFlow IRGenImpl::HandleBreakStmt(SysYParser::StmtContext* ctx) {
} }
IRGenImpl::BlockFlow IRGenImpl::HandleContinueStmt(SysYParser::StmtContext* ctx) { IRGenImpl::BlockFlow IRGenImpl::HandleContinueStmt(SysYParser::StmtContext* ctx) {
std::cout << "[DEBUG IRGEN] HandleContinueStmt: " << (ctx ? ctx->getText() : "<null>") << std::endl; DEBUG_MSG("[DEBUG IRGEN] HandleContinueStmt: " << (ctx ? ctx->getText() : "<null>"));
if (loopStack_.empty()) { if (loopStack_.empty()) {
throw std::runtime_error(FormatError("irgen", "continue 语句不在循环中")); throw std::runtime_error(FormatError("irgen", "continue 语句不在循环中"));
} }
std::cout << "[DEBUG CONTINUE] Current insert block before continue: " DEBUG_MSG("[DEBUG CONTINUE] Current insert block before continue: "
<< builder_.GetInsertBlock()->GetName() << std::endl; << builder_.GetInsertBlock()->GetName());
std::cout << "[DEBUG CONTINUE] Continuing to condBlock: " DEBUG_MSG("[DEBUG CONTINUE] Continuing to condBlock: "
<< loopStack_.back().condBlock->GetName() << std::endl; << loopStack_.back().condBlock->GetName());
// 跳转到循环条件块 // 跳转到循环条件块
builder_.CreateBr(loopStack_.back().condBlock); builder_.CreateBr(loopStack_.back().condBlock);
@ -340,7 +340,7 @@ IRGenImpl::BlockFlow IRGenImpl::HandleContinueStmt(SysYParser::StmtContext* ctx)
// 赋值语句 // 赋值语句
// 赋值语句 // 赋值语句
IRGenImpl::BlockFlow IRGenImpl::HandleAssignStmt(SysYParser::StmtContext* ctx) { IRGenImpl::BlockFlow IRGenImpl::HandleAssignStmt(SysYParser::StmtContext* ctx) {
std::cout << "[DEBUG IRGEN] HandleAssignStmt: " << (ctx ? ctx->getText() : "<null>") << std::endl; DEBUG_MSG("[DEBUG IRGEN] HandleAssignStmt: " << (ctx ? ctx->getText() : "<null>"));
if (!ctx || !ctx->lVal() || !ctx->exp()) { if (!ctx || !ctx->lVal() || !ctx->exp()) {
throw std::runtime_error(FormatError("irgen", "非法赋值语句")); throw std::runtime_error(FormatError("irgen", "非法赋值语句"));
@ -354,7 +354,7 @@ IRGenImpl::BlockFlow IRGenImpl::HandleAssignStmt(SysYParser::StmtContext* ctx) {
auto* lval = ctx->lVal(); auto* lval = ctx->lVal();
std::string varName = lval->Ident()->getText(); std::string varName = lval->Ident()->getText();
std::cerr << "[DEBUG] HandleAssignStmt: assigning to " << varName << std::endl; DEBUG_MSG("[DEBUG] HandleAssignStmt: assigning to " << varName);
// 1. 检查是否为常量(不能给常量赋值) // 1. 检查是否为常量(不能给常量赋值)
auto* const_decl = sema_.ResolveConstUse(lval); auto* const_decl = sema_.ResolveConstUse(lval);
@ -372,8 +372,8 @@ IRGenImpl::BlockFlow IRGenImpl::HandleAssignStmt(SysYParser::StmtContext* ctx) {
auto it = storage_map_.find(var_decl); auto it = storage_map_.find(var_decl);
if (it != storage_map_.end()) { if (it != storage_map_.end()) {
base_ptr = it->second; base_ptr = it->second;
std::cerr << "[DEBUG] HandleAssignStmt: found in storage_map_ for " << varName DEBUG_MSG("[DEBUG] HandleAssignStmt: found in storage_map_ for " << varName
<< ", ptr = " << (void*)base_ptr << std::endl; << ", ptr = " << (void*)base_ptr);
} }
} }
@ -382,8 +382,8 @@ IRGenImpl::BlockFlow IRGenImpl::HandleAssignStmt(SysYParser::StmtContext* ctx) {
auto it2 = param_map_.find(varName); auto it2 = param_map_.find(varName);
if (it2 != param_map_.end()) { if (it2 != param_map_.end()) {
base_ptr = it2->second; base_ptr = it2->second;
std::cerr << "[DEBUG] HandleAssignStmt: found in param_map_ for " << varName DEBUG_MSG("[DEBUG] HandleAssignStmt: found in param_map_ for " << varName
<< ", ptr = " << (void*)base_ptr << std::endl; << ", ptr = " << (void*)base_ptr);
} }
} }
@ -392,8 +392,8 @@ IRGenImpl::BlockFlow IRGenImpl::HandleAssignStmt(SysYParser::StmtContext* ctx) {
auto it3 = global_map_.find(varName); auto it3 = global_map_.find(varName);
if (it3 != global_map_.end()) { if (it3 != global_map_.end()) {
base_ptr = it3->second; base_ptr = it3->second;
std::cerr << "[DEBUG] HandleAssignStmt: found in global_map_ for " << varName DEBUG_MSG("[DEBUG] HandleAssignStmt: found in global_map_ for " << varName
<< ", ptr = " << (void*)base_ptr << std::endl; << ", ptr = " << (void*)base_ptr);
} }
} }
@ -402,8 +402,8 @@ IRGenImpl::BlockFlow IRGenImpl::HandleAssignStmt(SysYParser::StmtContext* ctx) {
auto it4 = local_var_map_.find(varName); auto it4 = local_var_map_.find(varName);
if (it4 != local_var_map_.end()) { if (it4 != local_var_map_.end()) {
base_ptr = it4->second; base_ptr = it4->second;
std::cerr << "[DEBUG] HandleAssignStmt: found in local_var_map_ for " << varName DEBUG_MSG("[DEBUG] HandleAssignStmt: found in local_var_map_ for " << varName
<< ", ptr = " << (void*)base_ptr << std::endl; << ", ptr = " << (void*)base_ptr);
} }
} }
@ -497,21 +497,21 @@ IRGenImpl::BlockFlow IRGenImpl::HandleAssignStmt(SysYParser::StmtContext* ctx) {
builder_.CreateStore(rhs, elem_ptr); builder_.CreateStore(rhs, elem_ptr);
} else { } else {
// 普通标量赋值 // 普通标量赋值
std::cerr << "[DEBUG] HandleAssignStmt: scalar assignment to " << varName DEBUG_MSG("[DEBUG] HandleAssignStmt: scalar assignment to " << varName
<< ", ptr = " << (void*)base_ptr << ", ptr = " << (void*)base_ptr
<< ", rhs = " << (void*)rhs << std::endl; << ", rhs = " << (void*)rhs);
// 在 HandleAssignStmt 中,存储前添加类型调试 // 在 HandleAssignStmt 中,存储前添加类型调试
if (base_ptr && base_ptr->GetType()) { if (base_ptr && base_ptr->GetType()) {
std::cerr << "[DEBUG] Is int32: " << base_ptr->GetType()->IsInt32() << std::endl; DEBUG_MSG("[DEBUG] Is int32: " << base_ptr->GetType()->IsInt32());
std::cerr << "[DEBUG] Is float: " << base_ptr->GetType()->IsFloat() << std::endl; DEBUG_MSG("[DEBUG] Is float: " << base_ptr->GetType()->IsFloat());
std::cerr << "[DEBUG] Is ptr int32: " << base_ptr->GetType()->IsPtrInt32() << std::endl; DEBUG_MSG("[DEBUG] Is ptr int32: " << base_ptr->GetType()->IsPtrInt32());
std::cerr << "[DEBUG] Is ptr float: " << base_ptr->GetType()->IsPtrFloat() << std::endl; DEBUG_MSG("[DEBUG] Is ptr float: " << base_ptr->GetType()->IsPtrFloat());
std::cerr << "[DEBUG] Is array: " << base_ptr->GetType()->IsArray() << std::endl; DEBUG_MSG("[DEBUG] Is array: " << base_ptr->GetType()->IsArray());
} }
if (rhs && rhs->GetType()) { if (rhs && rhs->GetType()) {
std::cerr << "[DEBUG] Value is int32: " << rhs->GetType()->IsInt32() << std::endl; DEBUG_MSG("[DEBUG] Value is int32: " << rhs->GetType()->IsInt32());
} }
if (base_ptr->GetType()->IsPtrFloat() && rhs->GetType()->IsInt32()) { if (base_ptr->GetType()->IsPtrFloat() && rhs->GetType()->IsInt32()) {
rhs = builder_.CreateSIToFP(rhs, ir::Type::GetFloatType(), rhs = builder_.CreateSIToFP(rhs, ir::Type::GetFloatType(),

@ -46,13 +46,17 @@ int main(int argc, char** argv) {
} }
if (opts.emit_asm) { if (opts.emit_asm) {
auto machine_func = mir::LowerToMIR(*module); //auto machine_func = mir::LowerToMIR(*module);
mir::RunRegAlloc(*machine_func); auto machine_module = mir::LowerToMIR(*module);
mir::RunFrameLowering(*machine_func); //mir::RunRegAlloc(*machine_func);
mir::RunRegAlloc(*machine_module);
//mir::RunFrameLowering(*machine_func);
mir::RunFrameLowering(*machine_module);
if (need_blank_line) { if (need_blank_line) {
std::cout << "\n"; std::cout << "\n";
} }
mir::PrintAsm(*machine_func, std::cout); //mir::PrintAsm(*machine_func, std::cout);
mir::PrintAsm(*machine_module, std::cout);
} }
#else #else
if (opts.emit_ir || opts.emit_asm) { if (opts.emit_ir || opts.emit_asm) {

@ -2,12 +2,24 @@
#include <ostream> #include <ostream>
#include <stdexcept> #include <stdexcept>
#include <set>
#include "utils/Log.h" #include "utils/Log.h"
//#define DEBUG_Asm
#ifdef DEBUG_Asm
#include <iostream>
#define DEBUG_MSG(msg) std::cerr << "[Asm Debug] " << msg << std::endl
#else
#define DEBUG_MSG(msg)
#endif
namespace mir { namespace mir {
namespace { namespace {
static void PrintLoadImm64(std::ostream& os, PhysReg reg, uint64_t imm);
const FrameSlot& GetFrameSlot(const MachineFunction& function, const FrameSlot& GetFrameSlot(const MachineFunction& function,
const Operand& operand) { const Operand& operand) {
if (operand.GetKind() != Operand::Kind::FrameIndex) { if (operand.GetKind() != Operand::Kind::FrameIndex) {
@ -16,63 +28,458 @@ const FrameSlot& GetFrameSlot(const MachineFunction& function,
return function.GetFrameSlot(operand.GetFrameIndex()); return function.GetFrameSlot(operand.GetFrameIndex());
} }
void PrintStackAccess(std::ostream& os, const char* mnemonic, PhysReg reg, void PrintStackAccess(std::ostream& os, const char* insn, PhysReg reg, int64_t offset) {
int offset) { // offset 通常是负数,例如 -8, -24, -40 等
os << " " << mnemonic << " " << PhysRegName(reg) << ", [x29, #" << offset if (offset >= -256 && offset <= 255) {
<< "]\n"; os << " " << insn << " " << PhysRegName(reg) << ", [x29, #" << offset << "]\n";
return;
}
// 大偏移量:用 x16 计算 x29 + offset然后间接访问
os << " mov x16, x29\n";
int64_t abs_offset = (offset >= 0) ? offset : -offset;
if (abs_offset <= 4095) {
if (offset >= 0) {
os << " add x16, x16, #" << offset << "\n";
} else {
os << " sub x16, x16, #" << abs_offset << "\n";
}
} else {
// 分解大偏移量
PrintLoadImm64(os, PhysReg::X17, abs_offset);
if (offset >= 0) {
os << " add x16, x16, x17\n";
} else {
os << " sub x16, x16, x17\n";
}
}
os << " " << insn << " " << PhysRegName(reg) << ", [x16]\n";
}
// 打印单个操作数
void PrintOperand(std::ostream& os, const Operand& op) {
switch (op.GetKind()) {
case Operand::Kind::Reg:
os << PhysRegName(op.GetReg());
break;
case Operand::Kind::Imm:
os << "#" << op.GetImm();
break;
case Operand::Kind::FrameIndex:
os << "[sp, #" << op.GetFrameIndex() << "]";
break;
case Operand::Kind::Cond:
os << CondCodeName(op.GetCondCode());
break;
case Operand::Kind::Label:
DEBUG_MSG("label is" << op.GetLabel());
os << op.GetLabel();
break;
}
} }
} // namespace // 判断立即数是否可作为 AArch64 ADD/SUB 指令的 12 位立即数(可左移 0 或 12 位)
static bool IsLegalAddSubImm(int64_t imm) {
if (imm < 0) imm = -imm; // 取绝对值,因为移位规则对称
if (imm <= 4095) return true; // 0-4095 直接合法
if ((imm & 0xFFF) == 0 && imm <= 4095 * 4096) return true; // 4096 的倍数且 ≤ 16773120
return false;
}
void PrintAsm(const MachineFunction& function, std::ostream& os) { // 在匿名命名空间添加辅助函数
os << ".text\n"; static void PrintLoadImm64(std::ostream& os, PhysReg reg, uint64_t imm) {
os << ".global " << function.GetName() << "\n"; // 输出 movz + movk 序列
os << ".type " << function.GetName() << ", %function\n"; uint16_t part0 = imm & 0xFFFF;
os << function.GetName() << ":\n"; uint16_t part1 = (imm >> 16) & 0xFFFF;
uint16_t part2 = (imm >> 32) & 0xFFFF;
uint16_t part3 = (imm >> 48) & 0xFFFF;
for (const auto& inst : function.GetEntry().GetInstructions()) { os << " movz " << PhysRegName(reg) << ", #" << part0;
const auto& ops = inst.GetOperands(); if (part1 != 0 || part2 != 0 || part3 != 0) {
switch (inst.GetOpcode()) { os << ", lsl #0";
case Opcode::Prologue: }
os << " stp x29, x30, [sp, #-16]!\n"; os << "\n";
os << " mov x29, sp\n";
if (function.GetFrameSize() > 0) { if (part1 != 0) {
os << " sub sp, sp, #" << function.GetFrameSize() << "\n"; os << " movk " << PhysRegName(reg) << ", #" << part1 << ", lsl #16\n";
}
if (part2 != 0) {
os << " movk " << PhysRegName(reg) << ", #" << part2 << ", lsl #32\n";
}
if (part3 != 0) {
os << " movk " << PhysRegName(reg) << ", #" << part3 << ", lsl #48\n";
}
}
// 打印单条指令
void PrintInstruction(std::ostream& os, const MachineInstr& instr,
const MachineFunction& function) {
const auto& ops = instr.GetOperands();
switch (instr.GetOpcode()) {
case Opcode::Prologue:
os << " stp x29, x30, [sp, #-16]!\n";
os << " mov x29, sp\n";
if (function.GetFrameSize() > 0) {
int64_t size = function.GetFrameSize();
if (IsLegalAddSubImm(size)) {
os << " sub sp, sp, #" << size << "\n";
} else {
PrintLoadImm64(os, PhysReg::X16, size);
os << " sub sp, sp, x16\n";
} }
break; }
case Opcode::Epilogue: break;
if (function.GetFrameSize() > 0) { case Opcode::Epilogue:
os << " add sp, sp, #" << function.GetFrameSize() << "\n"; if (function.GetFrameSize() > 0) {
int64_t size = function.GetFrameSize();
if (IsLegalAddSubImm(size)) {
os << " add sp, sp, #" << size << "\n";
} else {
PrintLoadImm64(os, PhysReg::X16, size);
os << " add sp, sp, x16\n";
} }
os << " ldp x29, x30, [sp], #16\n";
break;
case Opcode::MovImm:
os << " mov " << PhysRegName(ops.at(0).GetReg()) << ", #"
<< ops.at(1).GetImm() << "\n";
break;
case Opcode::LoadStack: {
const auto& slot = GetFrameSlot(function, ops.at(1));
PrintStackAccess(os, "ldur", ops.at(0).GetReg(), slot.offset);
break;
} }
case Opcode::StoreStack: { os << " ldp x29, x30, [sp], #16\n";
break;
case Opcode::MovImm:
os << " mov " << PhysRegName(ops.at(0).GetReg()) << ", #"
<< ops.at(1).GetImm() << "\n";
break;
case Opcode::MovReg:
os << " mov " << PhysRegName(ops.at(0).GetReg()) << ", "
<< PhysRegName(ops.at(1).GetReg()) << "\n";
break;
case Opcode::StoreStack: {
// 检查第二个操作数的类型
if (ops.size() >= 2 && ops.at(1).GetKind() == Operand::Kind::FrameIndex) {
// 存储到栈槽
const auto& slot = GetFrameSlot(function, ops.at(1)); const auto& slot = GetFrameSlot(function, ops.at(1));
PrintStackAccess(os, "stur", ops.at(0).GetReg(), slot.offset); PrintStackAccess(os, "stur", ops.at(0).GetReg(), slot.offset);
break; } else if (ops.size() >= 2 && ops.at(1).GetKind() == Operand::Kind::Reg) {
// 间接存储:存储到寄存器指向的地址
// STR W9, [X8]
os << " str " << PhysRegName(ops.at(0).GetReg()) << ", ["
<< PhysRegName(ops.at(1).GetReg()) << "]\n";
} else {
throw std::runtime_error("StoreStack: 无效的操作数类型");
}
break;
}
case Opcode::LoadStack: {
// 检查第二个操作数的类型
if (ops.size() >= 2 && ops.at(1).GetKind() == Operand::Kind::FrameIndex) {
// 从栈槽加载
const auto& slot = GetFrameSlot(function, ops.at(1));
PrintStackAccess(os, "ldur", ops.at(0).GetReg(), slot.offset);
} else if (ops.size() >= 2 && ops.at(1).GetKind() == Operand::Kind::Reg) {
// 间接加载:从寄存器指向的地址加载
// LDR W9, [X8]
os << " ldr " << PhysRegName(ops.at(0).GetReg()) << ", ["
<< PhysRegName(ops.at(1).GetReg()) << "]\n";
} else {
throw std::runtime_error("LoadStack: 无效的操作数类型");
}
break;
}
case Opcode::StoreStackPair:
// stp x29, x30, [sp, #-16]!
os << " stp " << PhysRegName(ops.at(0).GetReg()) << ", "
<< PhysRegName(ops.at(1).GetReg()) << ", [sp";
if (ops.size() > 2 && ops.at(2).GetKind() == Operand::Kind::Imm) {
int offset = ops.at(2).GetImm();
os << ", #" << offset;
} }
case Opcode::AddRR: os << "]!\n"; // 注意添加 ! 表示 pre-index
break;
case Opcode::LoadStackPair:
// ldp x29, x30, [sp], #16
os << " ldp " << PhysRegName(ops.at(0).GetReg()) << ", "
<< PhysRegName(ops.at(1).GetReg()) << ", [sp]";
if (ops.size() > 2 && ops.at(2).GetKind() == Operand::Kind::Imm) {
int offset = ops.at(2).GetImm();
os << ", #" << offset;
}
os << "\n";
break;
case Opcode::AddRR:
os << " add " << PhysRegName(ops.at(0).GetReg()) << ", "
<< PhysRegName(ops.at(1).GetReg()) << ", "
<< PhysRegName(ops.at(2).GetReg()) << "\n";
break;
case Opcode::AddRI:
os << " add " << PhysRegName(ops.at(0).GetReg()) << ", "
<< PhysRegName(ops.at(1).GetReg()) << ", #"
<< ops.at(2).GetImm() << "\n";
break;
case Opcode::SubRR:
os << " sub " << PhysRegName(ops.at(0).GetReg()) << ", "
<< PhysRegName(ops.at(1).GetReg()) << ", "
<< PhysRegName(ops.at(2).GetReg()) << "\n";
break;
case Opcode::SubRI:
os << " sub " << PhysRegName(ops.at(0).GetReg()) << ", "
<< PhysRegName(ops.at(1).GetReg()) << ", #"
<< ops.at(2).GetImm() << "\n";
break;
case Opcode::MulRR:
os << " mul " << PhysRegName(ops.at(0).GetReg()) << ", "
<< PhysRegName(ops.at(1).GetReg()) << ", "
<< PhysRegName(ops.at(2).GetReg()) << "\n";
break;
case Opcode::SDivRR:
os << " sdiv " << PhysRegName(ops.at(0).GetReg()) << ", "
<< PhysRegName(ops.at(1).GetReg()) << ", "
<< PhysRegName(ops.at(2).GetReg()) << "\n";
break;
case Opcode::UDivRR:
os << " udiv " << PhysRegName(ops.at(0).GetReg()) << ", "
<< PhysRegName(ops.at(1).GetReg()) << ", "
<< PhysRegName(ops.at(2).GetReg()) << "\n";
break;
case Opcode::FAddRR:
os << " fadd " << PhysRegName(ops.at(0).GetReg()) << ", "
<< PhysRegName(ops.at(1).GetReg()) << ", "
<< PhysRegName(ops.at(2).GetReg()) << "\n";
break;
case Opcode::FSubRR:
os << " fsub " << PhysRegName(ops.at(0).GetReg()) << ", "
<< PhysRegName(ops.at(1).GetReg()) << ", "
<< PhysRegName(ops.at(2).GetReg()) << "\n";
break;
case Opcode::FMulRR:
os << " fmul " << PhysRegName(ops.at(0).GetReg()) << ", "
<< PhysRegName(ops.at(1).GetReg()) << ", "
<< PhysRegName(ops.at(2).GetReg()) << "\n";
break;
case Opcode::FDivRR:
os << " fdiv " << PhysRegName(ops.at(0).GetReg()) << ", "
<< PhysRegName(ops.at(1).GetReg()) << ", "
<< PhysRegName(ops.at(2).GetReg()) << "\n";
break;
case Opcode::CmpRR:
os << " cmp " << PhysRegName(ops.at(0).GetReg()) << ", "
<< PhysRegName(ops.at(1).GetReg()) << "\n";
break;
case Opcode::CmpRI:
os << " cmp " << PhysRegName(ops.at(0).GetReg()) << ", #"
<< ops.at(1).GetImm() << "\n";
break;
case Opcode::FCmpRR:
os << " fcmp " << PhysRegName(ops.at(0).GetReg()) << ", "
<< PhysRegName(ops.at(1).GetReg()) << "\n";
break;
case Opcode::SIToFP:
os << " scvtf " << PhysRegName(ops.at(0).GetReg()) << ", "
<< PhysRegName(ops.at(1).GetReg()) << "\n";
break;
case Opcode::FPToSI:
os << " fcvtzs " << PhysRegName(ops.at(0).GetReg()) << ", "
<< PhysRegName(ops.at(1).GetReg()) << "\n";
break;
case Opcode::ZExt:
os << " and " << PhysRegName(ops.at(0).GetReg()) << ", "
<< PhysRegName(ops.at(1).GetReg()) << ", #1\n";
break;
case Opcode::AndRR:
os << " and " << PhysRegName(ops.at(0).GetReg()) << ", "
<< PhysRegName(ops.at(1).GetReg()) << ", "
<< PhysRegName(ops.at(2).GetReg()) << "\n";
break;
case Opcode::OrRR:
os << " orr " << PhysRegName(ops.at(0).GetReg()) << ", "
<< PhysRegName(ops.at(1).GetReg()) << ", "
<< PhysRegName(ops.at(2).GetReg()) << "\n";
break;
case Opcode::EorRR:
os << " eor " << PhysRegName(ops.at(0).GetReg()) << ", "
<< PhysRegName(ops.at(1).GetReg()) << ", "
<< PhysRegName(ops.at(2).GetReg()) << "\n";
break;
case Opcode::LslRR:
os << " lsl " << PhysRegName(ops.at(0).GetReg()) << ", "
<< PhysRegName(ops.at(1).GetReg()) << ", "
<< PhysRegName(ops.at(2).GetReg()) << "\n";
break;
case Opcode::LsrRR:
os << " lsr " << PhysRegName(ops.at(0).GetReg()) << ", "
<< PhysRegName(ops.at(1).GetReg()) << ", "
<< PhysRegName(ops.at(2).GetReg()) << "\n";
break;
case Opcode::AsrRR:
os << " asr " << PhysRegName(ops.at(0).GetReg()) << ", "
<< PhysRegName(ops.at(1).GetReg()) << ", "
<< PhysRegName(ops.at(2).GetReg()) << "\n";
break;
case Opcode::B:
os << " b ";
PrintOperand(os, ops.at(0));
os << "\n";
break;
case Opcode::BCond:
os << " b.";
PrintOperand(os, ops.at(0));
os << " ";
PrintOperand(os, ops.at(1));
os << "\n";
break;
case Opcode::Call:
os << " bl ";
PrintOperand(os, ops.at(0));
os << "\n";
break;
case Opcode::Ret:
os << " ret\n";
break;
case Opcode::Nop:
os << " nop\n";
break;
case Opcode::Label:
os << ops.at(0).GetLabel() << ":\n";
break;
case Opcode::Movk:
os << " movk " << PhysRegName(ops.at(0).GetReg()) << ", #"
<< ops.at(1).GetImm() << ", lsl #" << ops.at(2).GetImm() << "\n";
break;
case Opcode::LoadStackAddr: {
const FrameSlot& slot = GetFrameSlot(function, ops.at(1));
int64_t offset = slot.offset; // 负值,如 -8
PhysReg dst = ops.at(0).GetReg();
auto tryEmitSimple = [&]() -> bool {
if (offset >= 0 && offset <= 4095) {
os << " add " << PhysRegName(dst) << ", x29, #" << offset << "\n";
return true;
} else if (offset < 0 && offset >= -4095) {
os << " sub " << PhysRegName(dst) << ", x29, #" << (-offset) << "\n";
return true;
}
return false;
};
if (tryEmitSimple()) break;
// 复杂偏移
uint64_t absOffset = (offset >= 0) ? offset : -offset;
PrintLoadImm64(os, PhysReg::X16, absOffset);
if (offset >= 0) {
os << " add " << PhysRegName(dst) << ", x29, x16\n";
} else {
os << " sub " << PhysRegName(dst) << ", x29, x16\n";
}
break;
}
case Opcode::Adrp: {
// adrp Xd, label
os << " adrp " << PhysRegName(ops.at(0).GetReg()) << ", "
<< ops.at(1).GetLabel() << "\n";
break;
}
case Opcode::AddLabel: {
// add Xd, Xn, :lo12:label
os << " add " << PhysRegName(ops.at(0).GetReg()) << ", " os << " add " << PhysRegName(ops.at(0).GetReg()) << ", "
<< PhysRegName(ops.at(1).GetReg()) << ", " << PhysRegName(ops.at(1).GetReg()) << ", :lo12:"
<< PhysRegName(ops.at(2).GetReg()) << "\n"; << ops.at(2).GetLabel() << "\n";
break; break;
case Opcode::Ret: }
os << " ret\n"; case Opcode::Sxtw:
os << " sxtw " << PhysRegName(ops.at(0).GetReg()) << ", "
<< PhysRegName(ops.at(1).GetReg()) << "\n";
break;
default:
os << " // unknown instruction\n";
break; break;
}
}
// 打印单个函数(单函数版本)
void PrintAsm(const MachineFunction& function, std::ostream& os) {
// 输出函数标签
os << ".text\n";
os << ".global " << function.GetName() << "\n";
os << ".type " << function.GetName() << ", %function\n";
os << function.GetName() << ":\n";
// 计算栈帧大小
int frameSize = function.GetFrameSize();
// 输出每个基本块
const auto& blocks = function.GetBasicBlocks();
bool firstBlock = true;
for (const auto& bb : blocks) {
DEBUG_MSG("block");
// 输出基本块标签(非第一个基本块)
if (!firstBlock) {
os << bb->GetName() << ":\n";
}
firstBlock = false;
// 输出基本块中的指令
for (const auto& inst : bb->GetInstructions()) {
DEBUG_MSG("inst");
PrintInstruction(os, inst, function);
} }
} }
os << ".size " << function.GetName() << ", .-" << function.GetName() os << ".size " << function.GetName() << ", .-" << function.GetName() << "\n";
<< "\n"; }
} // namespace
// 打印模块(模块版本)
void PrintAsm(const MachineModule& module, std::ostream& os) {
// 输出文件头
os << ".arch armv8-a\n";
// 输出数据段:全局变量
const auto& globals = module.GetGlobals();
if (!globals.empty()) {
os << "\n.data\n";
for (const auto& g : globals) {
os << ".global " << g.name << "\n";
os << ".type " << g.name << ", %object\n";
os << ".align " << g.alignment << "\n";
os << g.name << ":\n";
if (g.is_zero_init) {
os << " .zero " << g.size << "\n";
} else if (g.has_init_data) {
if (g.size == 4) {
os << " .word " << static_cast<uint32_t>(g.init_data) << "\n";
} else if (g.size == 8) {
os << " .quad " << g.init_data << "\n";
} else {
// 暂不支持的标量大小,回退为零初始化
os << " .zero " << g.size << " // unhandled init size\n";
}
} else {
// 有初始值但无法提取(例如数组、结构体)
os << " .zero " << g.size << " // unhandled initializer\n";
}
os << ".size " << g.name << ", " << g.size << "\n\n";
}
}
static const std::set<std::string> externalFuncs = {
"getint", "getch", "getarray", "putint", "putch", "putarray", "puts",
"_sysy_starttime", "_sysy_stoptime", "starttime", "stoptime",
"getfloat", "putfloat", "getfarray", "putfarray", "memset",
"sysy_alloc_i32", "sysy_alloc_f32", "sysy_free_i32", "sysy_free_f32",
"sysy_zero_i32", "sysy_zero_f32"
};
DEBUG_MSG("module");
// 遍历所有函数,输出汇编
for (const auto& func : module.GetFunctions()) {
if (externalFuncs.count(func->GetName())) {
continue; // 跳过库函数桩
}
DEBUG_MSG("func");
PrintAsm(*func, os);
os << "\n";
}
} }
} // namespace mir } // namespace mir

@ -5,6 +5,15 @@
#include "utils/Log.h" #include "utils/Log.h"
//#define DEBUG_Frame
#ifdef DEBUG_Frame
#include <iostream>
#define DEBUG_MSG(msg) std::cerr << "[Frame Debug] " << msg << std::endl
#else
#define DEBUG_MSG(msg)
#endif
namespace mir { namespace mir {
namespace { namespace {
@ -15,31 +24,49 @@ int AlignTo(int value, int align) {
} // namespace } // namespace
void RunFrameLowering(MachineFunction& function) { void RunFrameLowering(MachineFunction& function) {
DEBUG_MSG("function RunFrameLowering");
int cursor = 0; int cursor = 0;
for (const auto& slot : function.GetFrameSlots()) {
cursor += slot.size;
if (-cursor < -256) {
throw std::runtime_error(FormatError("mir", "暂不支持过大的栈帧"));
}
}
cursor = 0;
for (const auto& slot : function.GetFrameSlots()) { for (const auto& slot : function.GetFrameSlots()) {
cursor += slot.size; cursor += slot.size;
function.GetFrameSlot(slot.index).offset = -cursor; function.GetFrameSlot(slot.index).offset = -cursor;
} }
function.SetFrameSize(AlignTo(cursor, 16)); function.SetFrameSize(AlignTo(cursor, 16));
auto& insts = function.GetEntry().GetInstructions(); // 基本块
std::vector<MachineInstr> lowered; const auto& blocks = function.GetBasicBlocks();
lowered.emplace_back(Opcode::Prologue); bool firstBlock = true;
for (const auto& inst : insts) {
if (inst.GetOpcode() == Opcode::Ret) { for (const auto& bb : blocks) {
lowered.emplace_back(Opcode::Epilogue); DEBUG_MSG("block");
auto& insts = bb->GetInstructions();
std::vector<MachineInstr> lowered;
// 输出基本块标签(非第一个基本块)
if (firstBlock) {
DEBUG_MSG("empalace Prologue");
lowered.emplace_back(Opcode::Prologue);
}
firstBlock = false;
// 输出基本块中的指令
for (const auto& inst : insts) {
DEBUG_MSG("inst");
if (inst.GetOpcode() == Opcode::Ret) {
DEBUG_MSG("empalace Epilogue");
lowered.emplace_back(Opcode::Epilogue);
}
lowered.push_back(inst);
} }
lowered.push_back(inst); insts = std::move(lowered);
}
}
// 模块版本的栈帧布局
void RunFrameLowering(MachineModule& module) {
// 对模块中的每个函数执行栈帧布局
DEBUG_MSG("module RunFrameLowering");
for (auto& func : module.GetFunctions()) {
RunFrameLowering(*func);
} }
insts = std::move(lowered);
} }
} // namespace mir } // namespace mir

File diff suppressed because it is too large Load Diff

@ -9,7 +9,8 @@ MachineBasicBlock::MachineBasicBlock(std::string name)
MachineInstr& MachineBasicBlock::Append(Opcode opcode, MachineInstr& MachineBasicBlock::Append(Opcode opcode,
std::initializer_list<Operand> operands) { std::initializer_list<Operand> operands) {
instructions_.emplace_back(opcode, std::vector<Operand>(operands)); //instructions_.emplace_back(opcode, std::vector<Operand>(operands));
instructions_.emplace_back(opcode, std::move(operands));
return instructions_.back(); return instructions_.back();
} }

@ -4,17 +4,25 @@
namespace mir { namespace mir {
Operand::Operand(Kind kind, PhysReg reg, int imm) Operand::Operand(Kind kind, PhysReg reg, int imm, CondCode cc, const std::string& label)
: kind_(kind), reg_(reg), imm_(imm) {} : kind_(kind), reg_(reg), imm_(imm), cc_(cc), label_(label) {}
Operand Operand::Reg(PhysReg reg) { return Operand(Kind::Reg, reg, 0); } Operand Operand::Reg(PhysReg reg) { return Operand(Kind::Reg, reg, 0, CondCode::EQ, ""); }
Operand Operand::Imm(int value) { Operand Operand::Imm(int value) {
return Operand(Kind::Imm, PhysReg::W0, value); return Operand(Kind::Imm, PhysReg::W0, value, CondCode::EQ, "");
} }
Operand Operand::FrameIndex(int index) { Operand Operand::FrameIndex(int index) {
return Operand(Kind::FrameIndex, PhysReg::W0, index); return Operand(Kind::FrameIndex, PhysReg::W0, index, CondCode::EQ, "");
}
Operand Operand::Cond(CondCode cc) {
return Operand(Kind::Cond, PhysReg::W0, 0, cc, "");
}
Operand Operand::Label(const std::string& label) {
return Operand(Kind::Label, PhysReg::W0, 0, CondCode::EQ, label);
} }
MachineInstr::MachineInstr(Opcode opcode, std::vector<Operand> operands) MachineInstr::MachineInstr(Opcode opcode, std::vector<Operand> operands)

@ -12,8 +12,8 @@ bool IsAllowedReg(PhysReg reg) {
case PhysReg::W0: case PhysReg::W0:
case PhysReg::W8: case PhysReg::W8:
case PhysReg::W9: case PhysReg::W9:
case PhysReg::X29: case PhysReg::X29: //FP = X29 帧指针
case PhysReg::X30: case PhysReg::X30: //LR = X30 链接寄存器
case PhysReg::SP: case PhysReg::SP:
return true; return true;
} }
@ -22,15 +22,61 @@ bool IsAllowedReg(PhysReg reg) {
} // namespace } // namespace
//void RunRegAlloc(MachineFunction& function) {
// for (const auto& inst : function.GetEntry().GetInstructions()) {
// for (const auto& operand : inst.GetOperands()) {
// if (operand.GetKind() == Operand::Kind::Reg &&
// !IsAllowedReg(operand.GetReg())) {
// throw std::runtime_error(FormatError("mir", "寄存器分配失败"));
// }
// }
// }
//}
// 单函数版本的寄存器分配(原有逻辑)
void RunRegAlloc(MachineFunction& function) { void RunRegAlloc(MachineFunction& function) {
for (const auto& inst : function.GetEntry().GetInstructions()) { // 当前仅执行最小一致性检查,不实现真实寄存器分配
for (const auto& operand : inst.GetOperands()) { // Lab3 阶段保持栈槽模型,不需要真实寄存器分配
if (operand.GetKind() == Operand::Kind::Reg &&
!IsAllowedReg(operand.GetReg())) { // 检查每个基本块中的指令
throw std::runtime_error(FormatError("mir", "寄存器分配失败")); for (auto& bb : function.GetBasicBlocks()) {
for (auto& instr : bb->GetInstructions()) {
// 检查指令的操作数是否有效
for (const auto& operand : instr.GetOperands()) {
switch (operand.GetKind()) {
case Operand::Kind::Reg:
// 寄存器操作数:检查是否在允许的范围内
// 当前使用固定寄存器 w0, w8, w9, s0, s1 等
break;
case Operand::Kind::FrameIndex:
// 栈槽索引:检查是否有效
if (operand.GetFrameIndex() < 0 ||
operand.GetFrameIndex() >= static_cast<int>(function.GetFrameSlots().size())) {
throw std::runtime_error(
FormatError("regalloc", "无效的栈槽索引: " +
std::to_string(operand.GetFrameIndex())));
}
break;
case Operand::Kind::Imm:
case Operand::Kind::Cond:
case Operand::Kind::Label:
// 立即数、条件码、标签不需要检查
break;
}
} }
} }
} }
// 注意Lab3 阶段不实现真实寄存器分配
// 所有值仍然使用栈槽模型,寄存器仅作为临时计算使用
}
// 模块版本的寄存器分配
void RunRegAlloc(MachineModule& module) {
// 对模块中的每个函数执行寄存器分配
for (auto& func : module.GetFunctions()) {
RunRegAlloc(*func);
}
} }
} // namespace mir } // namespace mir

@ -8,20 +8,111 @@ namespace mir {
const char* PhysRegName(PhysReg reg) { const char* PhysRegName(PhysReg reg) {
switch (reg) { switch (reg) {
case PhysReg::W0: // 32位寄存器
return "w0"; case PhysReg::W0: return "w0";
case PhysReg::W8: case PhysReg::W1: return "w1";
return "w8"; case PhysReg::W2: return "w2";
case PhysReg::W9: case PhysReg::W3: return "w3";
return "w9"; case PhysReg::W4: return "w4";
case PhysReg::X29: case PhysReg::W5: return "w5";
return "x29"; case PhysReg::W6: return "w6";
case PhysReg::X30: case PhysReg::W7: return "w7";
return "x30"; case PhysReg::W8: return "w8";
case PhysReg::SP: case PhysReg::W9: return "w9";
return "sp"; case PhysReg::W10: return "w10";
case PhysReg::W11: return "w11";
case PhysReg::W12: return "w12";
case PhysReg::W13: return "w13";
case PhysReg::W14: return "w14";
case PhysReg::W15: return "w15";
case PhysReg::W16: return "w16"; // 添加
case PhysReg::W17: return "w17"; // 添加
case PhysReg::W18: return "w18"; // 添加
case PhysReg::W19: return "w19"; // 添加
case PhysReg::W20: return "w20"; // 添加
case PhysReg::W21: return "w21"; // 添加
case PhysReg::W22: return "w22"; // 添加
case PhysReg::W23: return "w23"; // 添加
case PhysReg::W24: return "w24"; // 添加
case PhysReg::W25: return "w25"; // 添加
case PhysReg::W26: return "w26"; // 添加
case PhysReg::W27: return "w27"; // 添加
case PhysReg::W28: return "w28"; // 添加
case PhysReg::W29: return "w29";
case PhysReg::W30: return "w30";
// 64位寄存器
case PhysReg::X0: return "x0";
case PhysReg::X1: return "x1";
case PhysReg::X2: return "x2";
case PhysReg::X3: return "x3";
case PhysReg::X4: return "x4";
case PhysReg::X5: return "x5";
case PhysReg::X6: return "x6";
case PhysReg::X7: return "x7";
case PhysReg::X8: return "x8";
case PhysReg::X9: return "x9";
case PhysReg::X10: return "x10"; // 添加
case PhysReg::X11: return "x11"; // 添加
case PhysReg::X12: return "x12"; // 添加
case PhysReg::X13: return "x13"; // 添加
case PhysReg::X14: return "x14"; // 添加
case PhysReg::X15: return "x15"; // 添加
case PhysReg::X16: return "x16"; // 添加
case PhysReg::X17: return "x17"; // 添加
case PhysReg::X18: return "x18"; // 添加
case PhysReg::X19: return "x19"; // 添加
case PhysReg::X20: return "x20"; // 添加
case PhysReg::X21: return "x21"; // 添加
case PhysReg::X22: return "x22"; // 添加
case PhysReg::X23: return "x23"; // 添加
case PhysReg::X24: return "x24"; // 添加
case PhysReg::X25: return "x25"; // 添加
case PhysReg::X26: return "x26"; // 添加
case PhysReg::X27: return "x27"; // 添加
case PhysReg::X28: return "x28"; // 添加
case PhysReg::X29: return "x29";
case PhysReg::X30: return "x30";
// 浮点寄存器
case PhysReg::S0: return "s0";
case PhysReg::S1: return "s1";
case PhysReg::S2: return "s2";
case PhysReg::S3: return "s3";
case PhysReg::S4: return "s4";
case PhysReg::S5: return "s5";
case PhysReg::S6: return "s6";
case PhysReg::S7: return "s7";
// 特殊寄存器
case PhysReg::SP: return "sp";
case PhysReg::ZR: return "xzr";
default: return "unknown";
} }
throw std::runtime_error(FormatError("mir", "未知物理寄存器")); throw std::runtime_error(FormatError("mir", "未知物理寄存器"));
} }
const char* CondCodeName(CondCode cc) {
switch (cc) {
case CondCode::EQ: return "eq";
case CondCode::NE: return "ne";
case CondCode::CS: return "cs";
case CondCode::CC: return "cc";
case CondCode::MI: return "mi";
case CondCode::PL: return "pl";
case CondCode::VS: return "vs";
case CondCode::VC: return "vc";
case CondCode::HI: return "hi";
case CondCode::LS: return "ls";
case CondCode::GE: return "ge";
case CondCode::LT: return "lt";
case CondCode::GT: return "gt";
case CondCode::LE: return "le";
case CondCode::AL: return "al";
default: return "unknown";
}
throw std::runtime_error(FormatError("mir", "未知条件码"));
}
} // namespace mir } // namespace mir

@ -4,11 +4,21 @@
#include <stdexcept> #include <stdexcept>
#include <string> #include <string>
#include <sstream> #include <sstream>
#include <iostream>
#include "SysYBaseVisitor.h" #include "SysYBaseVisitor.h"
#include "sem/SymbolTable.h" #include "sem/SymbolTable.h"
#include "utils/Log.h" #include "utils/Log.h"
//#define DEBUG_SEMA
#ifdef DEBUG_SEMA
#include <iostream>
#define DEBUG_MSG(msg) std::cerr << "[Sema Debug] " << msg << std::endl
#else
#define DEBUG_MSG(msg)
#endif
namespace { namespace {
// 获取左值名称的辅助函数 // 获取左值名称的辅助函数
@ -67,10 +77,9 @@ public:
} else { } else {
return_type = ir::Type::GetInt32Type(); return_type = ir::Type::GetInt32Type();
} }
std::cout << "[DEBUG] 进入函数: " << name DEBUG_MSG("[DEBUG] 进入函数: " << name
<< " 返回类型: " << (return_type->IsInt32() ? "int" : << " 返回类型: " << (return_type->IsInt32() ? "int" :
return_type->IsFloat() ? "float" : "void") return_type->IsFloat() ? "float" : "void"));
<< std::endl;
// 记录当前函数返回类型(用于 return 检查) // 记录当前函数返回类型(用于 return 检查)
current_func_return_type_ = return_type; current_func_return_type_ = return_type;
@ -83,10 +92,9 @@ public:
if (ctx->block()) { // 处理函数体 if (ctx->block()) { // 处理函数体
ctx->block()->accept(this); ctx->block()->accept(this);
} }
std::cout << "[DEBUG] 函数 " << name DEBUG_MSG("[DEBUG] 函数 " << name
<< " has_return: " << current_func_has_return_ << " has_return: " << current_func_has_return_
<< " return_type_is_void: " << return_type->IsVoid() << " return_type_is_void: " << return_type->IsVoid());
<< std::endl;
if (!return_type->IsVoid() && !current_func_has_return_) { // 检查非 void 函数是否有 return if (!return_type->IsVoid() && !current_func_has_return_) { // 检查非 void 函数是否有 return
throw std::runtime_error(FormatError("sema", "非 void 函数 " + name + " 缺少 return 语句")); throw std::runtime_error(FormatError("sema", "非 void 函数 " + name + " 缺少 return 语句"));
} }
@ -170,10 +178,10 @@ public:
std::vector<int> dims; std::vector<int> dims;
bool is_array = !ctx->constExp().empty(); bool is_array = !ctx->constExp().empty();
// 调试输出 // 调试输出
std::cout << "[DEBUG] CheckVarDef: " << name DEBUG_MSG("[DEBUG] CheckVarDef: " << name
<< " base_type: " << (base_type->IsInt32() ? "int" : base_type->IsFloat() ? "float" : "unknown") << " base_type: " << (base_type->IsInt32() ? "int" : base_type->IsFloat() ? "float" : "unknown")
<< " is_array: " << is_array << " is_array: " << is_array
<< " dim_count: " << ctx->constExp().size() << std::endl; << " dim_count: " << ctx->constExp().size());
if (is_array) { if (is_array) {
// 处理数组维度 // 处理数组维度
for (auto* dim_exp : ctx->constExp()) { for (auto* dim_exp : ctx->constExp()) {
@ -185,26 +193,24 @@ public:
throw std::runtime_error(FormatError("sema", "数组维度必须为正整数")); throw std::runtime_error(FormatError("sema", "数组维度必须为正整数"));
} }
dims.push_back(dim); dims.push_back(dim);
std::cout << "[DEBUG] dim[" << dims.size() - 1 << "] = " << dim << std::endl; DEBUG_MSG("[DEBUG] dim[" << dims.size() - 1 << "] = " << dim);
} }
// 创建数组类型 // 创建数组类型
type = ir::Type::GetArrayType(base_type, dims); type = ir::Type::GetArrayType(base_type, dims);
std::cout << "[DEBUG] 创建数组类型完成" << std::endl; DEBUG_MSG("[DEBUG] 创建数组类型完成");
std::cout << "[DEBUG] type->IsArray(): " << type->IsArray() << std::endl; DEBUG_MSG("[DEBUG] type->IsArray(): " << type->IsArray());
std::cout << "[DEBUG] type->GetKind(): " << (int)type->GetKind() << std::endl; DEBUG_MSG("[DEBUG] type->GetKind(): " << (int)type->GetKind());
// 验证数组类型 // 验证数组类型
if (type->IsArray()) { if (type->IsArray()) {
auto* arr_type = dynamic_cast<ir::ArrayType*>(type.get()); auto* arr_type = dynamic_cast<ir::ArrayType*>(type.get());
if (arr_type) { if (arr_type) {
std::cout << "[DEBUG] ArrayType dimensions: "; DEBUG_MSG("[DEBUG] ArrayType dimensions: ");
for (int d : arr_type->GetDimensions()) { for (int d : arr_type->GetDimensions()) {
std::cout << d << " "; DEBUG_MSG(d << " ");
} }
std::cout << std::endl; DEBUG_MSG("[DEBUG] Element type: "
std::cout << "[DEBUG] Element type: "
<< (arr_type->GetElementType()->IsInt32() ? "int" : << (arr_type->GetElementType()->IsInt32() ? "int" :
arr_type->GetElementType()->IsFloat() ? "float" : "unknown") arr_type->GetElementType()->IsFloat() ? "float" : "unknown"));
<< std::endl;
} }
} }
} }
@ -230,10 +236,10 @@ public:
sym.param_types.clear(); // 确保不混淆 sym.param_types.clear(); // 确保不混淆
} }
table_.addSymbol(sym); // 添加到符号表 table_.addSymbol(sym); // 添加到符号表
std::cout << "[DEBUG] 符号添加完成: " << name DEBUG_MSG("[DEBUG] 符号添加完成: " << name
<< " type_kind: " << (int)sym.type->GetKind() << " type_kind: " << (int)sym.type->GetKind()
<< " is_array: " << sym.type->IsArray() << " is_array: " << sym.type->IsArray()
<< std::endl; );
} }
void CheckConstDef(SysYParser::ConstDefContext* ctx, void CheckConstDef(SysYParser::ConstDefContext* ctx,
@ -250,10 +256,10 @@ public:
std::shared_ptr<ir::Type> type = base_type; std::shared_ptr<ir::Type> type = base_type;
std::vector<int> dims; std::vector<int> dims;
bool is_array = !ctx->constExp().empty(); bool is_array = !ctx->constExp().empty();
std::cout << "[DEBUG] CheckConstDef: " << name DEBUG_MSG("[DEBUG] CheckConstDef: " << name
<< " base_type: " << (base_type->IsInt32() ? "int" : base_type->IsFloat() ? "float" : "unknown") << " base_type: " << (base_type->IsInt32() ? "int" : base_type->IsFloat() ? "float" : "unknown")
<< " is_array: " << is_array << " is_array: " << is_array
<< " dim_count: " << ctx->constExp().size() << std::endl; << " dim_count: " << ctx->constExp().size());
if (is_array) { if (is_array) {
for (auto* dim_exp : ctx->constExp()) { for (auto* dim_exp : ctx->constExp()) {
@ -262,10 +268,10 @@ public:
throw std::runtime_error(FormatError("sema", "数组维度必须为正整数")); throw std::runtime_error(FormatError("sema", "数组维度必须为正整数"));
} }
dims.push_back(dim); dims.push_back(dim);
std::cout << "[DEBUG] dim[" << dims.size() - 1 << "] = " << dim << std::endl; DEBUG_MSG("[DEBUG] dim[" << dims.size() - 1 << "] = " << dim);
} }
type = ir::Type::GetArrayType(base_type, dims); type = ir::Type::GetArrayType(base_type, dims);
std::cout << "[DEBUG] 创建数组类型完成IsArray: " << type->IsArray() << std::endl; DEBUG_MSG("[DEBUG] 创建数组类型完成IsArray: " << type->IsArray());
} }
// ========== 绑定维度表达式 ========== // ========== 绑定维度表达式 ==========
@ -280,7 +286,7 @@ public:
BindConstInitVal(ctx->constInitVal()); BindConstInitVal(ctx->constInitVal());
init_values = table_.EvaluateConstInitVal(ctx->constInitVal(), dims, base_type); init_values = table_.EvaluateConstInitVal(ctx->constInitVal(), dims, base_type);
std::cout << "[DEBUG] 初始化值数量: " << init_values.size() << std::endl; DEBUG_MSG("[DEBUG] 初始化值数量: " << init_values.size());
} }
// 计算期望的元素数量 // 计算期望的元素数量
@ -288,12 +294,12 @@ public:
if (is_array) { if (is_array) {
expected_count = 1; expected_count = 1;
for (int d : dims) expected_count *= d; for (int d : dims) expected_count *= d;
std::cout << "[DEBUG] 期望元素数量: " << expected_count << std::endl; DEBUG_MSG("[DEBUG] 期望元素数量: " << expected_count);
} }
// 如果初始化值不足,补零 // 如果初始化值不足,补零
if (is_array && init_values.size() < expected_count) { if (is_array && init_values.size() < expected_count) {
std::cout << "[DEBUG] 初始化值不足,补零" << std::endl; DEBUG_MSG("[DEBUG] 初始化值不足,补零");
SymbolTable::ConstValue zero; SymbolTable::ConstValue zero;
if (base_type->IsInt32()) { if (base_type->IsInt32()) {
zero.kind = SymbolTable::ConstValue::INT; zero.kind = SymbolTable::ConstValue::INT;
@ -314,13 +320,13 @@ public:
Symbol sym; Symbol sym;
sym.name = name; sym.name = name;
sym.kind = SymbolKind::Constant; sym.kind = SymbolKind::Constant;
std::cout << "CheckConstDef: before addSymbol, sym.kind = " << (int)sym.kind << std::endl; DEBUG_MSG("CheckConstDef: before addSymbol, sym.kind = " << (int)sym.kind);
sym.type = type; sym.type = type;
sym.scope_level = table_.currentScopeLevel(); sym.scope_level = table_.currentScopeLevel();
sym.is_initialized = true; sym.is_initialized = true;
sym.var_def_ctx = nullptr; sym.var_def_ctx = nullptr;
sym.const_def_ctx = ctx; sym.const_def_ctx = ctx;
std::cout << "保存常量定义上下文: " << name << ", ctx: " << ctx << std::endl; DEBUG_MSG("保存常量定义上下文: " << name << ", ctx: " << ctx);
// ========== 存储常量值 ========== // ========== 存储常量值 ==========
if (is_array) { if (is_array) {
@ -338,19 +344,19 @@ public:
sym.array_const_values.push_back(cv); sym.array_const_values.push_back(cv);
} }
std::cout << "[DEBUG] 存储数组常量,共 " << sym.array_const_values.size() DEBUG_MSG("[DEBUG] 存储数组常量,共 " << sym.array_const_values.size()
<< " 个元素" << std::endl; << " 个元素");
} else if (!init_values.empty()) { } else if (!init_values.empty()) {
// 存储标量常量 // 存储标量常量
if (base_type->IsInt32() && init_values[0].kind == SymbolTable::ConstValue::INT) { if (base_type->IsInt32() && init_values[0].kind == SymbolTable::ConstValue::INT) {
sym.is_int_const = true; sym.is_int_const = true;
sym.const_value.i32 = init_values[0].int_val; sym.const_value.i32 = init_values[0].int_val;
std::cout << "[DEBUG] 存储整型常量: " << init_values[0].int_val << std::endl; DEBUG_MSG("[DEBUG] 存储整型常量: " << init_values[0].int_val);
} else if (base_type->IsFloat() && init_values[0].kind == SymbolTable::ConstValue::FLOAT) { } else if (base_type->IsFloat() && init_values[0].kind == SymbolTable::ConstValue::FLOAT) {
sym.is_int_const = false; sym.is_int_const = false;
sym.const_value.f32 = init_values[0].float_val; sym.const_value.f32 = init_values[0].float_val;
std::cout << "[DEBUG] 存储浮点常量: " << init_values[0].float_val << std::endl; DEBUG_MSG("[DEBUG] 存储浮点常量: " << init_values[0].float_val);
} else if (base_type->IsInt32() && init_values[0].kind == SymbolTable::ConstValue::FLOAT) { } else if (base_type->IsInt32() && init_values[0].kind == SymbolTable::ConstValue::FLOAT) {
// 整型常量用浮点数初始化(需要检查是否为整数) // 整型常量用浮点数初始化(需要检查是否为整数)
float f = init_values[0].float_val; float f = init_values[0].float_val;
@ -361,30 +367,30 @@ public:
} }
sym.is_int_const = true; sym.is_int_const = true;
sym.const_value.i32 = i; sym.const_value.i32 = i;
std::cout << "[DEBUG] 浮点转整型常量: " << f << " -> " << i << std::endl; DEBUG_MSG("[DEBUG] 浮点转整型常量: " << f << " -> " << i);
} else if (base_type->IsFloat() && init_values[0].kind == SymbolTable::ConstValue::INT) { } else if (base_type->IsFloat() && init_values[0].kind == SymbolTable::ConstValue::INT) {
// 浮点常量用整型初始化,隐式转换 // 浮点常量用整型初始化,隐式转换
sym.is_int_const = false; sym.is_int_const = false;
sym.const_value.f32 = static_cast<float>(init_values[0].int_val); sym.const_value.f32 = static_cast<float>(init_values[0].int_val);
std::cout << "[DEBUG] 整型转浮点常量: " << init_values[0].int_val DEBUG_MSG("[DEBUG] 整型转浮点常量: " << init_values[0].int_val
<< " -> " << static_cast<float>(init_values[0].int_val) << std::endl; << " -> " << static_cast<float>(init_values[0].int_val));
} }
} else { } else {
// 没有初始化值,对于标量常量这是错误的 // 没有初始化值,对于标量常量这是错误的
if (!is_array) { if (!is_array) {
throw std::runtime_error(FormatError("sema", "常量必须有初始化值: " + name)); throw std::runtime_error(FormatError("sema", "常量必须有初始化值: " + name));
} }
std::cout << "[DEBUG] 数组常量无初始化器,将全部补零" << std::endl; DEBUG_MSG("[DEBUG] 数组常量无初始化器,将全部补零");
} }
table_.addSymbol(sym); table_.addSymbol(sym);
std::cout << "CheckConstDef: after addSymbol, sym.kind = " << (int)sym.kind << std::endl; DEBUG_MSG("CheckConstDef: after addSymbol, sym.kind = " << (int)sym.kind);
auto* stored = table_.lookup(name); auto* stored = table_.lookup(name);
std::cout << "CheckConstDef: after addSymbol, stored const_def_ctx = " << stored->const_def_ctx << std::endl; DEBUG_MSG("CheckConstDef: after addSymbol, stored const_def_ctx = " << stored->const_def_ctx);
std::cout << "[DEBUG] 常量符号添加完成: " << name DEBUG_MSG("[DEBUG] 常量符号添加完成: " << name
<< " is_array_const: " << sym.is_array_const << " is_array_const: " << sym.is_array_const
<< " element_count: " << sym.array_const_values.size() << std::endl; << " element_count: " << sym.array_const_values.size());
} }
// ==================== 常量声明 ==================== // ==================== 常量声明 ====================
@ -407,20 +413,19 @@ public:
std::any visitStmt(SysYParser::StmtContext* ctx) override { std::any visitStmt(SysYParser::StmtContext* ctx) override {
if (!ctx) return {}; if (!ctx) return {};
// 调试输出 // 调试输出
std::cout << "[DEBUG] visitStmt: "; DEBUG_MSG("[DEBUG] visitStmt: ");
if (ctx->Return()) std::cout << "Return "; if (ctx->Return()) DEBUG_MSG("Return ");
if (ctx->If()) std::cout << "If "; if (ctx->If()) DEBUG_MSG("If ");
if (ctx->While()) std::cout << "While "; if (ctx->While()) DEBUG_MSG("While ");
if (ctx->Break()) std::cout << "Break "; if (ctx->Break()) DEBUG_MSG("Break ");
if (ctx->Continue()) std::cout << "Continue "; if (ctx->Continue()) DEBUG_MSG("Continue ");
if (ctx->lVal() && ctx->Assign()) std::cout << "Assign "; if (ctx->lVal() && ctx->Assign()) DEBUG_MSG("Assign ");
if (ctx->exp() && ctx->Semi()) std::cout << "ExpStmt "; if (ctx->exp() && ctx->Semi()) DEBUG_MSG("ExpStmt ");
if (ctx->block()) std::cout << "Block "; if (ctx->block()) DEBUG_MSG("Block ");
std::cout << std::endl;
// 判断语句类型 - 注意Return() 返回的是 TerminalNode* // 判断语句类型 - 注意Return() 返回的是 TerminalNode*
if (ctx->Return() != nullptr) { if (ctx->Return() != nullptr) {
// return 语句 // return 语句
std::cout << "[DEBUG] 检测到 return 语句" << std::endl; DEBUG_MSG("[DEBUG] 检测到 return 语句");
return visitReturnStmtInternal(ctx); return visitReturnStmtInternal(ctx);
} else if (ctx->lVal() != nullptr && ctx->Assign() != nullptr) { } else if (ctx->lVal() != nullptr && ctx->Assign() != nullptr) {
// 赋值语句 // 赋值语句
@ -449,14 +454,14 @@ public:
// return 语句内部实现 // return 语句内部实现
std::any visitReturnStmtInternal(SysYParser::StmtContext* ctx) { std::any visitReturnStmtInternal(SysYParser::StmtContext* ctx) {
std::cout << "[DEBUG] visitReturnStmtInternal 被调用" << std::endl; DEBUG_MSG("[DEBUG] visitReturnStmtInternal 被调用");
std::shared_ptr<ir::Type> expected = current_func_return_type_; std::shared_ptr<ir::Type> expected = current_func_return_type_;
if (!expected) { if (!expected) {
throw std::runtime_error(FormatError("sema", "return 语句不在函数体内")); throw std::runtime_error(FormatError("sema", "return 语句不在函数体内"));
} }
if (ctx->exp() != nullptr) { if (ctx->exp() != nullptr) {
// 有返回值的 return // 有返回值的 return
std::cout << "[DEBUG] 有返回值的 return" << std::endl; DEBUG_MSG("[DEBUG] 有返回值的 return");
ExprInfo ret_val = CheckExp(ctx->exp()); ExprInfo ret_val = CheckExp(ctx->exp());
if (expected->IsVoid()) { if (expected->IsVoid()) {
throw std::runtime_error(FormatError("sema", "void 函数不能返回值")); throw std::runtime_error(FormatError("sema", "void 函数不能返回值"));
@ -469,23 +474,23 @@ public:
} }
// 设置 has_return 标志 // 设置 has_return 标志
current_func_has_return_ = true; current_func_has_return_ = true;
std::cout << "[DEBUG] 设置 current_func_has_return_ = true" << std::endl; DEBUG_MSG("[DEBUG] 设置 current_func_has_return_ = true");
} else { } else {
// 无返回值的 return // 无返回值的 return
std::cout << "[DEBUG] 无返回值的 return" << std::endl; DEBUG_MSG("[DEBUG] 无返回值的 return");
if (!expected->IsVoid()) { if (!expected->IsVoid()) {
throw std::runtime_error(FormatError("sema", "非 void 函数必须返回值")); throw std::runtime_error(FormatError("sema", "非 void 函数必须返回值"));
} }
// 设置 has_return 标志 // 设置 has_return 标志
current_func_has_return_ = true; current_func_has_return_ = true;
std::cout << "[DEBUG] 设置 current_func_has_return_ = true" << std::endl; DEBUG_MSG("[DEBUG] 设置 current_func_has_return_ = true");
} }
return {}; return {};
} }
// 左值表达式(变量引用) // 左值表达式(变量引用)
std::any visitLVal(SysYParser::LValContext* ctx) override { std::any visitLVal(SysYParser::LValContext* ctx) override {
std::cout << "[DEBUG] visitLVal: " << ctx->getText() << std::endl; DEBUG_MSG("[DEBUG] visitLVal: " << ctx->getText());
if (!ctx || !ctx->Ident()) { if (!ctx || !ctx->Ident()) {
throw std::runtime_error(FormatError("sema", "非法变量引用")); throw std::runtime_error(FormatError("sema", "非法变量引用"));
} }
@ -496,17 +501,17 @@ public:
} }
// 检查数组访问 // 检查数组访问
bool is_array_access = !ctx->exp().empty(); bool is_array_access = !ctx->exp().empty();
std::cout << "[DEBUG] name: " << name DEBUG_MSG("[DEBUG] name: " << name
<< ", is_array_access: " << is_array_access << ", is_array_access: " << is_array_access
<< ", subscript_count: " << ctx->exp().size() << std::endl; << ", subscript_count: " << ctx->exp().size());
ExprInfo result; ExprInfo result;
// 判断是否为数组类型或指针类型(数组参数) // 判断是否为数组类型或指针类型(数组参数)
bool is_array_or_ptr = false; bool is_array_or_ptr = false;
if (sym->type) { if (sym->type) {
is_array_or_ptr = sym->type->IsArray() || sym->type->IsPtrInt32() || sym->type->IsPtrFloat(); is_array_or_ptr = sym->type->IsArray() || sym->type->IsPtrInt32() || sym->type->IsPtrFloat();
std::cout << "[DEBUG] type_kind: " << (int)sym->type->GetKind() DEBUG_MSG("[DEBUG] type_kind: " << (int)sym->type->GetKind()
<< ", is_array: " << sym->type->IsArray() << ", is_array: " << sym->type->IsArray()
<< ", is_ptr: " << (sym->type->IsPtrInt32() || sym->type->IsPtrFloat()) << std::endl; << ", is_ptr: " << (sym->type->IsPtrInt32() || sym->type->IsPtrFloat()));
} }
if (is_array_or_ptr) { if (is_array_or_ptr) {
@ -517,7 +522,7 @@ public:
if (auto* arr_type = dynamic_cast<ir::ArrayType*>(sym->type.get())) { if (auto* arr_type = dynamic_cast<ir::ArrayType*>(sym->type.get())) {
dim_count = arr_type->GetDimensions().size(); dim_count = arr_type->GetDimensions().size();
elem_type = arr_type->GetElementType(); elem_type = arr_type->GetElementType();
std::cout << "[DEBUG] 数组维度: " << dim_count << std::endl; DEBUG_MSG("[DEBUG] 数组维度: " << dim_count);
} }
} else if (sym->type->IsPtrInt32() || sym->type->IsPtrFloat()) { } else if (sym->type->IsPtrInt32() || sym->type->IsPtrFloat()) {
dim_count = 1; dim_count = 1;
@ -526,12 +531,12 @@ public:
} else if (sym->type->IsPtrFloat()) { } else if (sym->type->IsPtrFloat()) {
elem_type = ir::Type::GetFloatType(); elem_type = ir::Type::GetFloatType();
} }
std::cout << "[DEBUG] 指针类型, dim_count: 1" << std::endl; DEBUG_MSG("[DEBUG] 指针类型, dim_count: 1");
} }
if (is_array_access) { if (is_array_access) {
std::cout << "[DEBUG] 有下标访问,期望维度: " << dim_count DEBUG_MSG("[DEBUG] 有下标访问,期望维度: " << dim_count
<< ", 实际下标数: " << ctx->exp().size() << std::endl; << ", 实际下标数: " << ctx->exp().size());
if (ctx->exp().size() != dim_count) { if (ctx->exp().size() != dim_count) {
throw std::runtime_error(FormatError("sema", "数组下标个数不匹配")); throw std::runtime_error(FormatError("sema", "数组下标个数不匹配"));
} }
@ -545,9 +550,9 @@ public:
result.is_lvalue = true; result.is_lvalue = true;
result.is_const = false; result.is_const = false;
} else { } else {
std::cout << "[DEBUG] 无下标访问" << std::endl; DEBUG_MSG("[DEBUG] 无下标访问");
if (sym->type->IsArray()) { if (sym->type->IsArray()) {
std::cout << "[DEBUG] 数组名作为地址,转换为指针" << std::endl; DEBUG_MSG("[DEBUG] 数组名作为地址,转换为指针");
if (auto* arr_type = dynamic_cast<ir::ArrayType*>(sym->type.get())) { if (auto* arr_type = dynamic_cast<ir::ArrayType*>(sym->type.get())) {
if (arr_type->GetElementType()->IsInt32()) { if (arr_type->GetElementType()->IsInt32()) {
result.type = ir::Type::GetPtrInt32Type(); result.type = ir::Type::GetPtrInt32Type();
@ -669,7 +674,7 @@ public:
// 主表达式 // 主表达式
std::any visitPrimaryExp(SysYParser::PrimaryExpContext* ctx) override { std::any visitPrimaryExp(SysYParser::PrimaryExpContext* ctx) override {
std::cout << "[DEBUG] visitPrimaryExp: " << ctx->getText() << std::endl; DEBUG_MSG("[DEBUG] visitPrimaryExp: " << ctx->getText());
ExprInfo result; ExprInfo result;
if (ctx->lVal()) { // 左值表达式 if (ctx->lVal()) { // 左值表达式
result = CheckLValue(ctx->lVal()); result = CheckLValue(ctx->lVal());
@ -701,14 +706,14 @@ public:
// 一元表达式 // 一元表达式
std::any visitUnaryExp(SysYParser::UnaryExpContext* ctx) override { std::any visitUnaryExp(SysYParser::UnaryExpContext* ctx) override {
std::cout << "[DEBUG] visitUnaryExp: " << ctx->getText() << std::endl; DEBUG_MSG("[DEBUG] visitUnaryExp: " << ctx->getText());
ExprInfo result; ExprInfo result;
if (ctx->primaryExp()) { if (ctx->primaryExp()) {
ctx->primaryExp()->accept(this); ctx->primaryExp()->accept(this);
auto* info = sema_.GetExprType(ctx->primaryExp()); auto* info = sema_.GetExprType(ctx->primaryExp());
if (info) result = *info; if (info) result = *info;
} else if (ctx->Ident() && ctx->L_PAREN()) { // 函数调用 } else if (ctx->Ident() && ctx->L_PAREN()) { // 函数调用
std::cout << "[DEBUG] 函数调用: " << ctx->Ident()->getText() << std::endl; DEBUG_MSG("[DEBUG] 函数调用: " << ctx->Ident()->getText());
result = CheckFuncCall(ctx); result = CheckFuncCall(ctx);
} else if (ctx->unaryOp()) { // 一元运算 } else if (ctx->unaryOp()) { // 一元运算
ctx->unaryExp()->accept(this); ctx->unaryExp()->accept(this);
@ -1074,8 +1079,8 @@ public:
// 新增:同时返回两者 // 新增:同时返回两者
SemaResult TakeResult() { SemaResult TakeResult() {
std::cerr << "[DEBUG] TakeResult 前: 符号表作用域数量 = " DEBUG_MSG("[DEBUG] TakeResult 前: 符号表作用域数量 = "
<< table_.getScopeCount() << std::endl; << table_.getScopeCount());
// 可选:打印符号表内容 // 可选:打印符号表内容
// table_.dump(); // table_.dump();
@ -1084,8 +1089,8 @@ public:
result.context = std::move(sema_); result.context = std::move(sema_);
result.symbol_table = std::move(table_); result.symbol_table = std::move(table_);
std::cerr << "[DEBUG] TakeResult 后: 符号表作用域数量 = " DEBUG_MSG("[DEBUG] TakeResult 后: 符号表作用域数量 = "
<< result.symbol_table.getScopeCount() << std::endl; << result.symbol_table.getScopeCount());
return result; return result;
} }
@ -1106,7 +1111,7 @@ private:
if (!ctx || !ctx->addExp()) { if (!ctx || !ctx->addExp()) {
throw std::runtime_error(FormatError("sema", "无效表达式")); throw std::runtime_error(FormatError("sema", "无效表达式"));
} }
std::cout << "[DEBUG] CheckExp: " << ctx->getText() << std::endl; DEBUG_MSG("[DEBUG] CheckExp: " << ctx->getText());
ctx->addExp()->accept(this); ctx->addExp()->accept(this);
auto* info = sema_.GetExprType(ctx->addExp()); auto* info = sema_.GetExprType(ctx->addExp());
if (!info) { if (!info) {
@ -1157,21 +1162,21 @@ private:
if (!sym) { if (!sym) {
throw std::runtime_error(FormatError("sema", "未定义的变量: " + name)); throw std::runtime_error(FormatError("sema", "未定义的变量: " + name));
} }
std::cout << "CheckLValue: found sym->name = " << sym->name DEBUG_MSG("CheckLValue: found sym->name = " << sym->name
<< ", sym->kind = " << (int)sym->kind << std::endl; << ", sym->kind = " << (int)sym->kind);
if (sym->kind == SymbolKind::Variable && sym->var_def_ctx) { if (sym->kind == SymbolKind::Variable && sym->var_def_ctx) {
sema_.BindVarUse(ctx, sym->var_def_ctx); sema_.BindVarUse(ctx, sym->var_def_ctx);
std::cout << "绑定变量: " << name << " -> VarDefContext" << std::endl; DEBUG_MSG("绑定变量: " << name << " -> VarDefContext");
} }
else if (sym->kind == SymbolKind::Constant && sym->const_def_ctx) { else if (sym->kind == SymbolKind::Constant && sym->const_def_ctx) {
sema_.BindConstUse(ctx, sym->const_def_ctx); sema_.BindConstUse(ctx, sym->const_def_ctx);
std::cout << "绑定常量: " << name << " -> ConstDefContext" << std::endl; DEBUG_MSG("绑定常量: " << name << " -> ConstDefContext");
} }
std::cout << "CheckLValue 绑定变量: " << name DEBUG_MSG("CheckLValue 绑定变量: " << name
<< ", sym->kind: " << (int)sym->kind << ", sym->kind: " << (int)sym->kind
<< ", sym->var_def_ctx: " << sym->var_def_ctx << ", sym->var_def_ctx: " << sym->var_def_ctx
<< ", sym->const_def_ctx: " << sym->const_def_ctx << std::endl; << ", sym->const_def_ctx: " << sym->const_def_ctx);
bool is_array_access = !ctx->exp().empty(); bool is_array_access = !ctx->exp().empty();
bool is_const = (sym->kind == SymbolKind::Constant); bool is_const = (sym->kind == SymbolKind::Constant);
@ -1203,9 +1208,8 @@ private:
} else if (sym->type->IsPtrFloat()) { } else if (sym->type->IsPtrFloat()) {
elem_type = ir::Type::GetFloatType(); elem_type = ir::Type::GetFloatType();
} }
std::cout << "数组参数维度: " << dim_count << " 维, dims: "; DEBUG_MSG("数组参数维度: " << dim_count << " 维, dims: ");
for (int d : dims) std::cout << d << " "; for (int d : dims) DEBUG_MSG(d << " ");
std::cout << std::endl;
} else if (sym->type && (sym->type->IsPtrInt32() || sym->type->IsPtrFloat())) { } else if (sym->type && (sym->type->IsPtrInt32() || sym->type->IsPtrFloat())) {
// 普通指针,只能有一个下标 // 普通指针,只能有一个下标
dim_count = 1; dim_count = 1;
@ -1218,7 +1222,7 @@ private:
size_t subscript_count = ctx->exp().size(); size_t subscript_count = ctx->exp().size();
std::cout << "dim_count: " << dim_count << ", subscript_count: " << subscript_count << std::endl; DEBUG_MSG("dim_count: " << dim_count << ", subscript_count: " << subscript_count);
if (dim_count > 0 || sym->is_array_param || sym->type->IsArray() || if (dim_count > 0 || sym->is_array_param || sym->type->IsArray() ||
sym->type->IsPtrInt32() || sym->type->IsPtrFloat()) { sym->type->IsPtrInt32() || sym->type->IsPtrFloat()) {
@ -1239,11 +1243,11 @@ private:
if (subscript_count == dim_count) { if (subscript_count == dim_count) {
// 完全索引,返回元素类型 // 完全索引,返回元素类型
std::cout << "完全索引,返回元素类型" << std::endl; DEBUG_MSG("完全索引,返回元素类型");
return {elem_type, true, false}; return {elem_type, true, false};
} else { } else {
// 部分索引,返回子数组的指针类型 // 部分索引,返回子数组的指针类型
std::cout << "部分索引,返回指针类型" << std::endl; DEBUG_MSG("部分索引,返回指针类型");
// 计算剩余维度的指针类型 // 计算剩余维度的指针类型
if (elem_type->IsInt32()) { if (elem_type->IsInt32()) {
return {ir::Type::GetPtrInt32Type(), false, false}; return {ir::Type::GetPtrInt32Type(), false, false};
@ -1257,7 +1261,7 @@ private:
// 没有下标访问 // 没有下标访问
if (sym->type && sym->type->IsArray()) { if (sym->type && sym->type->IsArray()) {
// 数组名作为地址 // 数组名作为地址
std::cout << "数组名作为地址" << std::endl; DEBUG_MSG("数组名作为地址");
if (auto* arr_type = dynamic_cast<ir::ArrayType*>(sym->type.get())) { if (auto* arr_type = dynamic_cast<ir::ArrayType*>(sym->type.get())) {
if (arr_type->GetElementType()->IsInt32()) { if (arr_type->GetElementType()->IsInt32()) {
return {ir::Type::GetPtrInt32Type(), false, true}; return {ir::Type::GetPtrInt32Type(), false, true};
@ -1268,7 +1272,7 @@ private:
return {ir::Type::GetPtrInt32Type(), false, true}; return {ir::Type::GetPtrInt32Type(), false, true};
} else if (sym->is_array_param) { } else if (sym->is_array_param) {
// 数组参数名作为地址 // 数组参数名作为地址
std::cout << "数组参数名作为地址" << std::endl; DEBUG_MSG("数组参数名作为地址");
if (sym->type->IsPtrInt32()) { if (sym->type->IsPtrInt32()) {
return {ir::Type::GetPtrInt32Type(), false, true}; return {ir::Type::GetPtrInt32Type(), false, true};
} else { } else {
@ -1292,14 +1296,14 @@ private:
throw std::runtime_error(FormatError("sema", "非法函数调用")); throw std::runtime_error(FormatError("sema", "非法函数调用"));
} }
std::string func_name = ctx->Ident()->getText(); std::string func_name = ctx->Ident()->getText();
std::cout << "[DEBUG] CheckFuncCall: " << func_name << std::endl; DEBUG_MSG("[DEBUG] CheckFuncCall: " << func_name);
auto* func_sym = table_.lookup(func_name); auto* func_sym = table_.lookup(func_name);
if (!func_sym || func_sym->kind != SymbolKind::Function) { if (!func_sym || func_sym->kind != SymbolKind::Function) {
throw std::runtime_error(FormatError("sema", "未定义的函数: " + func_name)); throw std::runtime_error(FormatError("sema", "未定义的函数: " + func_name));
} }
std::vector<ExprInfo> args; std::vector<ExprInfo> args;
if (ctx->funcRParams()) { if (ctx->funcRParams()) {
std::cout << "[DEBUG] 处理函数调用参数:" << std::endl; DEBUG_MSG("[DEBUG] 处理函数调用参数:");
for (auto* exp : ctx->funcRParams()->exp()) { for (auto* exp : ctx->funcRParams()->exp()) {
if (exp) { if (exp) {
args.push_back(CheckExp(exp)); args.push_back(CheckExp(exp));
@ -1310,8 +1314,8 @@ private:
throw std::runtime_error(FormatError("sema", "参数个数不匹配")); throw std::runtime_error(FormatError("sema", "参数个数不匹配"));
} }
for (size_t i = 0; i < std::min(args.size(), func_sym->param_types.size()); ++i) { for (size_t i = 0; i < std::min(args.size(), func_sym->param_types.size()); ++i) {
std::cout << "[DEBUG] 检查参数 " << i << ": 实参类型 " << (int)args[i].type->GetKind() DEBUG_MSG("[DEBUG] 检查参数 " << i << ": 实参类型 " << (int)args[i].type->GetKind()
<< " 形参类型 " << (int)func_sym->param_types[i]->GetKind() << std::endl; << " 形参类型 " << (int)func_sym->param_types[i]->GetKind());
if (!IsTypeCompatible(args[i].type, func_sym->param_types[i])) { if (!IsTypeCompatible(args[i].type, func_sym->param_types[i])) {
throw std::runtime_error(FormatError("sema", "参数类型不匹配")); throw std::runtime_error(FormatError("sema", "参数类型不匹配"));
} }
@ -1511,10 +1515,8 @@ private:
sym.array_dims = dims; sym.array_dims = dims;
table_.addSymbol(sym); table_.addSymbol(sym);
std::cout << "[DEBUG] 添加参数: " << name << " type_kind: " << (int)param_type->GetKind() DEBUG_MSG("[DEBUG] 添加参数: " << name << " type_kind: " << (int)param_type->GetKind());
<< " is_array: " << is_array << " dims: "; for (int d : dims) DEBUG_MSG(d << " ");
for (int d : dims) std::cout << d << " ";
std::cout << std::endl;
} }
} }

@ -6,7 +6,7 @@
#include <cmath> #include <cmath>
#include <functional> #include <functional>
#define DEBUG_SYMBOL_TABLE //#define DEBUG_SYMBOL_TABLE
#ifdef DEBUG_SYMBOL_TABLE #ifdef DEBUG_SYMBOL_TABLE
#include <iostream> #include <iostream>
@ -48,10 +48,9 @@ bool SymbolTable::addSymbol(const Symbol& sym) {
// 立即验证存储的符号 // 立即验证存储的符号
const auto& stored = current_scope[sym.name]; const auto& stored = current_scope[sym.name];
std::cout << "SymbolTable::addSymbol: stored " << sym.name DEBUG_MSG("SymbolTable::addSymbol: stored " << sym.name
<< " with kind=" << (int)stored.kind << " with kind=" << (int)stored.kind
<< ", const_def_ctx=" << stored.const_def_ctx << ", const_def_ctx=" << stored.const_def_ctx);
<< std::endl;
return true; return true;
} }
@ -69,11 +68,10 @@ const Symbol* SymbolTable::lookup(const std::string& name) const {
const auto& scope = scopes_[*it]; const auto& scope = scopes_[*it];
auto found = scope.find(name); auto found = scope.find(name);
if (found != scope.end()) { if (found != scope.end()) {
std::cout << "SymbolTable::lookup: found " << name DEBUG_MSG("SymbolTable::lookup: found " << name
<< " in active scope index " << *it << " in active scope index " << *it
<< ", kind=" << (int)found->second.kind << ", kind=" << (int)found->second.kind
<< ", const_def_ctx=" << found->second.const_def_ctx << ", const_def_ctx=" << found->second.const_def_ctx);
<< std::endl;
return &found->second; return &found->second;
} }
} }

@ -0,0 +1,5 @@
编译libsysy.a
```
aarch64-linux-gnu-gcc -c sylib.c -o sylib.o
aarch64-linux-gnu-ar rcs libsysy.a sylib.o
```
Loading…
Cancel
Save