Compare commits

..

4 Commits

12 changed files with 235 additions and 16065 deletions

View File

@ -29,10 +29,12 @@ EXEC_TIMEOUT=30
MAX_OUTPUT_LINES=20
MAX_OUTPUT_CHARS=1000
TEST_SETS=()
PERF_RUN_COUNT=1 # 新增: 性能测试运行次数
TOTAL_CASES=0
PASSED_CASES=0
FAILED_CASES_LIST=""
INTERRUPTED=false
PERFORMANCE_MODE=false # 新增: 标记是否进行性能测试
# =================================================================
# --- 函数定义 ---
@ -49,6 +51,8 @@ show_help() {
echo " -c, --clean 清理 'tmp' 目录下的所有生成文件。"
echo " -O1 启用 sysyc 的 -O1 优化。"
echo " -set [f|h|p|all]... 指定要运行的测试集 (functional, h_functional, performance)。可多选,默认为 all。"
echo " 当包含 'p' 时,会自动记录性能数据到 ${TMP_DIR}/performance_time.csv。"
echo " -pt N 设置 performance 测试集的每个用例运行 N 次取平均值 (默认: 1)。"
echo " -sct N 设置 sysyc 编译超时为 N 秒 (默认: 30)。"
echo " -lct N 设置 llc-19 编译超时为 N 秒 (默认: 10)。"
echo " -gct N 设置 gcc 交叉编译超时为 N 秒 (默认: 10)。"
@ -104,7 +108,6 @@ print_summary() {
local failed_count
if [ -n "$FAILED_CASES_LIST" ]; then
# `wc -l` 计算由换行符分隔的列表项数
failed_count=$(echo -e -n "${FAILED_CASES_LIST}" | wc -l)
else
failed_count=0
@ -116,10 +119,27 @@ print_summary() {
if [ -n "$FAILED_CASES_LIST" ]; then
echo ""
echo -e "\e[31m未通过的测例:\e[0m"
# 使用 printf 保证原样输出
printf "%b" "${FAILED_CASES_LIST}"
fi
# --- 本次修改点: 提示性能测试结果文件 ---
if ${PERFORMANCE_MODE}; then
# --- 本次修改点: 计算并添加总计行 ---
if [ -f "${PERFORMANCE_CSV_FILE}" ] && [ $(wc -l < "${PERFORMANCE_CSV_FILE}") -gt 1 ]; then
local total_seconds_sum
total_seconds_sum=$(awk -F, 'NR > 1 {sum += $3} END {printf "%.5f", sum}' "${PERFORMANCE_CSV_FILE}")
local total_s_int=${total_seconds_sum%.*}
[[ -z "$total_s_int" ]] && total_s_int=0 # 处理小于1秒的情况
local total_us_int=$(echo "(${total_seconds_sum} - ${total_s_int}) * 1000000" | bc | cut -d. -f1)
local total_time_str="${total_s_int}s${total_us_int}us"
echo "all,${total_time_str},${total_seconds_sum}" >> "${PERFORMANCE_CSV_FILE}"
fi
echo ""
echo -e "\e[32m性能测试数据已保存到: ${PERFORMANCE_CSV_FILE}\e[0m"
fi
echo "========================================"
if [ "$failed_count" -gt 0 ]; then
@ -139,12 +159,9 @@ handle_sigint() {
# --- 主逻辑开始 ---
# =================================================================
# --- 新增:设置 trap 来捕获 SIGINT ---
trap handle_sigint SIGINT
mkdir -p "${TMP_DIR}"
# 解析命令行参数
while [[ "$#" -gt 0 ]]; do
case "$1" in
-e|--executable) EXECUTE_MODE=true; shift ;;
@ -155,6 +172,7 @@ while [[ "$#" -gt 0 ]]; do
shift
while [[ "$#" -gt 0 && ! "$1" =~ ^- ]]; do TEST_SETS+=("$1"); shift; done
;;
-pt) if [[ -n "$2" && "$2" =~ ^[0-9]+$ ]]; then PERF_RUN_COUNT="$2"; shift 2; else echo "错误: -pt 需要一个正整数参数。" >&2; exit 1; fi ;;
-sct) if [[ -n "$2" && "$2" =~ ^[0-9]+$ ]]; then SYSYC_TIMEOUT="$2"; shift 2; else echo "错误: -sct 需要一个正整数参数。" >&2; exit 1; fi ;;
-lct) if [[ -n "$2" && "$2" =~ ^[0-9]+$ ]]; then LLC_TIMEOUT="$2"; shift 2; else echo "错误: -lct 需要一个正整数参数。" >&2; exit 1; fi ;;
-gct) if [[ -n "$2" && "$2" =~ ^[0-9]+$ ]]; then GCC_TIMEOUT="$2"; shift 2; else echo "错误: -gct 需要一个正整数参数。" >&2; exit 1; fi ;;
@ -179,10 +197,14 @@ SET_MAP[p]="performance"
SEARCH_PATHS=()
if [ ${#TEST_SETS[@]} -eq 0 ] || [[ " ${TEST_SETS[@]} " =~ " all " ]]; then
SEARCH_PATHS+=("${TESTDATA_DIR}")
if [ -d "${TESTDATA_DIR}/performance" ]; then PERFORMANCE_MODE=true; fi
else
for set in "${TEST_SETS[@]}"; do
if [[ -v SET_MAP[$set] ]]; then
SEARCH_PATHS+=("${TESTDATA_DIR}/${SET_MAP[$set]}")
if [[ "$set" == "p" ]]; then
PERFORMANCE_MODE=true
fi
else
echo -e "\e[33m警告: 未知的测试集 '$set',已忽略。\e[0m"
fi
@ -212,6 +234,9 @@ else
fi
echo "运行模式: ${RUN_MODE_INFO}"
echo "${TIMEOUT_INFO}"
if ${PERFORMANCE_MODE} && ([ ${EXECUTE_MODE} = true ] || [ ${IR_EXECUTE_MODE} = true ]) && [ ${PERF_RUN_COUNT} -gt 1 ]; then
echo "性能测试运行次数: ${PERF_RUN_COUNT}"
fi
if ${EXECUTE_MODE} || ${IR_EXECUTE_MODE}; then
echo "失败输出最大行数: ${MAX_OUTPUT_LINES}"
echo "失败输出最大字符数: ${MAX_OUTPUT_CHARS}"
@ -225,6 +250,11 @@ if [ -z "$sy_files" ]; then
fi
TOTAL_CASES=$(echo "$sy_files" | wc -w)
PERFORMANCE_CSV_FILE="${TMP_DIR}/performance_time.csv"
if ${PERFORMANCE_MODE}; then
echo "Case,Time_String,Time_Seconds" > "${PERFORMANCE_CSV_FILE}"
fi
while IFS= read -r sy_file; do
is_passed=0 # 0 表示失败, 1 表示通过
@ -234,11 +264,13 @@ while IFS= read -r sy_file; do
assembly_file_S="${TMP_DIR}/${output_base_name}_sysyc_S.s"
executable_file_S="${TMP_DIR}/${output_base_name}_sysyc_S"
output_actual_file_S="${TMP_DIR}/${output_base_name}_sysyc_S.actual_out"
stderr_file_S="${TMP_DIR}/${output_base_name}_sysyc_S.stderr"
ir_file="${TMP_DIR}/${output_base_name}_sysyc_ir.ll"
assembly_file_from_ir="${TMP_DIR}/${output_base_name}_from_ir.s"
executable_file_from_ir="${TMP_DIR}/${output_base_name}_from_ir"
output_actual_file_from_ir="${TMP_DIR}/${output_base_name}_from_ir.actual_out"
stderr_file_from_ir="${TMP_DIR}/${output_base_name}_from_ir.stderr"
input_file="${sy_file%.*}.in"
output_reference_file="${sy_file%.*}.out"
@ -249,165 +281,170 @@ while IFS= read -r sy_file; do
if ${IR_EXECUTE_MODE}; then
step_failed=0
test_logic_passed=0
total_time_us=0
echo " [1/4] 使用 sysyc 编译为 IR (超时 ${SYSYC_TIMEOUT}s)..."
timeout -s KILL ${SYSYC_TIMEOUT} "${SYSYC}" -s ir "${sy_file}" -o "${ir_file}" ${OPTIMIZE_FLAG}
SYSYC_STATUS=$?
if [ $SYSYC_STATUS -ne 0 ]; then
[ $SYSYC_STATUS -eq 124 ] && echo -e "\e[31m错误: SysY (IR) 编译超时\e[0m" || echo -e "\e[31m错误: SysY (IR) 编译失败,退出码: ${SYSYC_STATUS}\e[0m"
step_failed=1
fi
timeout -s KILL ${SYSYC_TIMEOUT} "${SYSYC}" -s ir "${sy_file}" -o "${ir_file}" ${OPTIMIZE_FLAG}; if [ $? -ne 0 ]; then echo -e "\e[31m错误: SysY (IR) 编译失败或超时\e[0m"; step_failed=1; fi
if [ "$step_failed" -eq 0 ]; then
echo " [2/4] 使用 llc-19 编译为汇编 (超时 ${LLC_TIMEOUT}s)..."
timeout -s KILL ${LLC_TIMEOUT} "${LLC_CMD}" -march=riscv64 -mcpu=generic-rv64 -mattr=+m,+a,+f,+d,+c -filetype=asm "${ir_file}" -o "${assembly_file_from_ir}"
LLC_STATUS=$?
if [ $LLC_STATUS -ne 0 ]; then
[ $LLC_STATUS -eq 124 ] && echo -e "\e[31m错误: llc-19 编译超时\e[0m" || echo -e "\e[31m错误: llc-19 编译失败,退出码: ${LLC_STATUS}\e[0m"
step_failed=1
fi
timeout -s KILL ${LLC_TIMEOUT} ${LLC_CMD} -march=riscv64 -mcpu=generic-rv64 -mattr=+m,+a,+f,+d,+c -filetype=asm "${ir_file}" -o "${assembly_file_from_ir}"; if [ $? -ne 0 ]; then echo -e "\e[31m错误: llc-19 编译失败或超时\e[0m"; step_failed=1; fi
fi
if [ "$step_failed" -eq 0 ]; then
echo " [3/4] 使用 gcc 编译 (超时 ${GCC_TIMEOUT}s)..."
timeout -s KILL ${GCC_TIMEOUT} "${GCC_RISCV64}" "${assembly_file_from_ir}" -o "${executable_file_from_ir}" -L"${LIB_DIR}" -lsysy_riscv -static
GCC_STATUS=$?
if [ $GCC_STATUS -ne 0 ]; then
[ $GCC_STATUS -eq 124 ] && echo -e "\e[31m错误: GCC 编译超时\e[0m" || echo -e "\e[31m错误: GCC 编译失败,退出码: ${GCC_STATUS}\e[0m"
step_failed=1
fi
timeout -s KILL ${GCC_TIMEOUT} "${GCC_RISCV64}" "${assembly_file_from_ir}" -o "${executable_file_from_ir}" -L"${LIB_DIR}" -lsysy_riscv -static; if [ $? -ne 0 ]; then echo -e "\e[31m错误: GCC 编译失败或超时\e[0m"; step_failed=1; fi
fi
if [ "$step_failed" -eq 0 ]; then
echo " [4/4] 正在执行 (超时 ${EXEC_TIMEOUT}s)..."
exec_cmd="${QEMU_RISCV64} \"${executable_file_from_ir}\""
[ -f "${input_file}" ] && exec_cmd+=" < \"${input_file}\""
exec_cmd+=" > \"${output_actual_file_from_ir}\""
eval "timeout -s KILL ${EXEC_TIMEOUT} ${exec_cmd}"
ACTUAL_RETURN_CODE=$?
if [ "$ACTUAL_RETURN_CODE" -eq 124 ]; then
echo -e "\e[31m 执行超时: 运行超过 ${EXEC_TIMEOUT} 秒\e[0m"
else
current_run_failed=0
for (( i=1; i<=PERF_RUN_COUNT; i++ )); do
if [ ${PERF_RUN_COUNT} -gt 1 ]; then echo -n "$i/${PERF_RUN_COUNT} 次运行... "; fi
exec_cmd="${QEMU_RISCV64} \"${executable_file_from_ir}\""
[ -f "${input_file}" ] && exec_cmd+=" < \"${input_file}\""
exec_cmd+=" > \"${output_actual_file_from_ir}\" 2> \"${stderr_file_from_ir}\""
eval "timeout -s KILL ${EXEC_TIMEOUT} ${exec_cmd}"
ACTUAL_RETURN_CODE=$?
if [ "$ACTUAL_RETURN_CODE" -eq 124 ]; then echo -e "\e[31m超时\e[0m"; current_run_failed=1; break; fi
if ${PERFORMANCE_MODE}; then
TIME_LINE=$(grep "TOTAL:" "${stderr_file_from_ir}")
if [ -n "$TIME_LINE" ]; then
H=$(echo "$TIME_LINE" | sed -E 's/TOTAL: ([0-9]+)H-.*/\1/')
M=$(echo "$TIME_LINE" | sed -E 's/.*-([0-9]+)M-.*/\1/')
S=$(echo "$TIME_LINE" | sed -E 's/.*-([0-9]+)S-.*/\1/')
US=$(echo "$TIME_LINE" | sed -E 's/.*-([0-9]+)us/\1/')
run_time_us=$(( H * 3600000000 + M * 60000000 + S * 1000000 + US ))
total_time_us=$(( total_time_us + run_time_us ))
if [ ${PERF_RUN_COUNT} -gt 1 ]; then echo "耗时: ${run_time_us}us"; fi
else
echo -e "\e[31m未找到时间信息\e[0m"; current_run_failed=1; break
fi
fi
done
if [ "$current_run_failed" -eq 0 ]; then
test_logic_passed=1
if [ -f "${output_reference_file}" ]; then
LAST_LINE_TRIMMED=$(tail -n 1 "${output_reference_file}" | tr -d '[:space:]')
test_logic_passed=1
if [[ "$LAST_LINE_TRIMMED" =~ ^[-+]?[0-9]+$ ]]; then
EXPECTED_RETURN_CODE="$LAST_LINE_TRIMMED"
EXPECTED_STDOUT_FILE="${TMP_DIR}/${output_base_name}_from_ir.expected_stdout"
head -n -1 "${output_reference_file}" > "${EXPECTED_STDOUT_FILE}"
if [ "$ACTUAL_RETURN_CODE" -eq "$EXPECTED_RETURN_CODE" ]; then
echo -e "\e[32m 返回码测试成功: (${ACTUAL_RETURN_CODE}) 与期望值 (${EXPECTED_RETURN_CODE}) 匹配\e[0m"
else
echo -e "\e[31m 返回码测试失败: 期望: ${EXPECTED_RETURN_CODE}, 实际: ${ACTUAL_RETURN_CODE}\e[0m"
test_logic_passed=0
fi
if diff -q <(tr -d '[:space:]' < "${output_actual_file_from_ir}") <(tr -d '[:space:]' < "${EXPECTED_STDOUT_FILE}") >/dev/null 2>&1; then
[ "$test_logic_passed" -eq 1 ] && echo -e "\e[32m 标准输出测试成功\e[0m"
else
echo -e "\e[31m 标准输出测试失败\e[0m"
display_file_content "${EXPECTED_STDOUT_FILE}" " \e[36m---------- 期望输出 ----------\e[0m" "${MAX_OUTPUT_LINES}" "${MAX_OUTPUT_CHARS}"
display_file_content "${output_actual_file_from_ir}" " \e[36m---------- 实际输出 ----------\e[0m" "${MAX_OUTPUT_LINES}" "${MAX_OUTPUT_CHARS}"
test_logic_passed=0
if [ "$ACTUAL_RETURN_CODE" -ne "$EXPECTED_RETURN_CODE" ]; then echo -e "\e[31m 返回码测试失败: 期望 ${EXPECTED_RETURN_CODE}, 实际 ${ACTUAL_RETURN_CODE}\e[0m"; test_logic_passed=0; fi
if ! diff -q <(tr -d '[:space:]' < "${output_actual_file_from_ir}") <(tr -d '[:space:]' < "${EXPECTED_STDOUT_FILE}") >/dev/null 2>&1; then
echo -e "\e[31m 标准输出测试失败\e[0m"; test_logic_passed=0
display_file_content "${EXPECTED_STDOUT_FILE}" " \e[36m--- 期望输出 ---\e[0m" "${MAX_OUTPUT_LINES}" "${MAX_OUTPUT_CHARS}"
display_file_content "${output_actual_file_from_ir}" " \e[36m--- 实际输出 ---\e[0m" "${MAX_OUTPUT_LINES}" "${MAX_OUTPUT_CHARS}"
fi
else
if [ $ACTUAL_RETURN_CODE -ne 0 ]; then echo -e "\e[33m警告: 程序以非零状态 ${ACTUAL_RETURN_CODE} 退出 (纯输出比较模式)。\e[0m"; fi
if diff -q <(tr -d '[:space:]' < "${output_actual_file_from_ir}") <(tr -d '[:space:]' < "${output_reference_file}") >/dev/null 2>&1; then
echo -e "\e[32m 成功: 输出与参考输出匹配\e[0m"
else
echo -e "\e[31m 失败: 输出不匹配\e[0m"
display_file_content "${output_reference_file}" " \e[36m---------- 期望输出 ----------\e[0m" "${MAX_OUTPUT_LINES}" "${MAX_OUTPUT_CHARS}"
display_file_content "${output_actual_file_from_ir}" " \e[36m---------- 实际输出 ----------\e[0m" "${MAX_OUTPUT_LINES}" "${MAX_OUTPUT_CHARS}"
test_logic_passed=0
if ! diff -q <(tr -d '[:space:]' < "${output_actual_file_from_ir}") <(tr -d '[:space:]' < "${output_reference_file}") >/dev/null 2>&1; then
echo -e "\e[31m 失败: 输出匹配\e[0m"; test_logic_passed=0
display_file_content "${output_reference_file}" " \e[36m--- 期望输出 ---\e[0m" "${MAX_OUTPUT_LINES}" "${MAX_OUTPUT_CHARS}"
display_file_content "${output_actual_file_from_ir}" " \e[36m--- 实际输出 ---\e[0m" "${MAX_OUTPUT_LINES}" "${MAX_OUTPUT_CHARS}"
fi
fi
else
echo " 无参考输出文件。程序返回码: ${ACTUAL_RETURN_CODE}"
test_logic_passed=1
fi
if [ "$test_logic_passed" -eq 1 ]; then echo -e "\e[32m 测试逻辑通过\e[0m"; fi
fi
fi
[ "$step_failed" -eq 0 ] && [ "$test_logic_passed" -eq 1 ] && is_passed=1
if [ "$step_failed" -eq 0 ] && [ "$test_logic_passed" -eq 1 ]; then is_passed=1; fi
if ${PERFORMANCE_MODE}; then
avg_time_us=0
if [ "$is_passed" -eq 1 ]; then
avg_time_us=$(( total_time_us / PERF_RUN_COUNT ))
fi
S_AVG=$(( avg_time_us / 1000000 ))
US_AVG=$(( avg_time_us % 1000000 ))
TIME_STRING_AVG="${S_AVG}s${US_AVG}us"
TOTAL_SECONDS_AVG=$(echo "scale=5; ${avg_time_us} / 1000000" | bc)
echo "$(basename ${sy_file}),${TIME_STRING_AVG},${TOTAL_SECONDS_AVG}" >> "${PERFORMANCE_CSV_FILE}"
fi
# --- 模式 2: 直接执行模式 (-e) ---
elif ${EXECUTE_MODE}; then
step_failed=0
test_logic_passed=0
total_time_us=0
echo " [1/3] 使用 sysyc 编译为汇编 (超时 ${SYSYC_TIMEOUT}s)..."
timeout -s KILL ${SYSYC_TIMEOUT} "${SYSYC}" -S "${sy_file}" -o "${assembly_file_S}" ${OPTIMIZE_FLAG}
SYSYC_STATUS=$?
if [ $SYSYC_STATUS -ne 0 ]; then
[ $SYSYC_STATUS -eq 124 ] && echo -e "\e[31m错误: SysY (汇编) 编译超时\e[0m" || echo -e "\e[31m错误: SysY (汇编) 编译失败,退出码: ${SYSYC_STATUS}\e[0m"
step_failed=1
fi
timeout -s KILL ${SYSYC_TIMEOUT} "${SYSYC}" -S "${sy_file}" -o "${assembly_file_S}" ${OPTIMIZE_FLAG}; if [ $? -ne 0 ]; then echo -e "\e[31m错误: SysY (汇编) 编译失败或超时\e[0m"; step_failed=1; fi
if [ "$step_failed" -eq 0 ]; then
echo " [2/3] 使用 gcc 编译 (超时 ${GCC_TIMEOUT}s)..."
timeout -s KILL ${GCC_TIMEOUT} "${GCC_RISCV64}" "${assembly_file_S}" -o "${executable_file_S}" -L"${LIB_DIR}" -lsysy_riscv -static
GCC_STATUS=$?
if [ $GCC_STATUS -ne 0 ]; then
[ $GCC_STATUS -eq 124 ] && echo -e "\e[31m错误: GCC 编译超时\e[0m" || echo -e "\e[31m错误: GCC 编译失败,退出码: ${GCC_STATUS}\e[0m"
step_failed=1
fi
timeout -s KILL ${GCC_TIMEOUT} "${GCC_RISCV64}" "${assembly_file_S}" -o "${executable_file_S}" -L"${LIB_DIR}" -lsysy_riscv -static; if [ $? -ne 0 ]; then echo -e "\e[31m错误: GCC 编译失败或超时\e[0m"; step_failed=1; fi
fi
if [ "$step_failed" -eq 0 ]; then
echo " [3/3] 正在执行 (超时 ${EXEC_TIMEOUT}s)..."
exec_cmd="${QEMU_RISCV64} \"${executable_file_S}\""
[ -f "${input_file}" ] && exec_cmd+=" < \"${input_file}\""
exec_cmd+=" > \"${output_actual_file_S}\""
eval "timeout -s KILL ${EXEC_TIMEOUT} ${exec_cmd}"
ACTUAL_RETURN_CODE=$?
current_run_failed=0
for (( i=1; i<=PERF_RUN_COUNT; i++ )); do
if [ ${PERF_RUN_COUNT} -gt 1 ]; then echo -n "$i/${PERF_RUN_COUNT} 次运行... "; fi
exec_cmd="${QEMU_RISCV64} \"${executable_file_S}\""
[ -f "${input_file}" ] && exec_cmd+=" < \"${input_file}\""
exec_cmd+=" > \"${output_actual_file_S}\" 2> \"${stderr_file_S}\""
eval "timeout -s KILL ${EXEC_TIMEOUT} ${exec_cmd}"
ACTUAL_RETURN_CODE=$?
if [ "$ACTUAL_RETURN_CODE" -eq 124 ]; then echo -e "\e[31m超时\e[0m"; current_run_failed=1; break; fi
if ${PERFORMANCE_MODE}; then
TIME_LINE=$(grep "TOTAL:" "${stderr_file_S}")
if [ -n "$TIME_LINE" ]; then
H=$(echo "$TIME_LINE" | sed -E 's/TOTAL: ([0-9]+)H-.*/\1/')
M=$(echo "$TIME_LINE" | sed -E 's/.*-([0-9]+)M-.*/\1/')
S=$(echo "$TIME_LINE" | sed -E 's/.*-([0-9]+)S-.*/\1/')
US=$(echo "$TIME_LINE" | sed -E 's/.*-([0-9]+)us/\1/')
run_time_us=$(( H * 3600000000 + M * 60000000 + S * 1000000 + US ))
total_time_us=$(( total_time_us + run_time_us ))
if [ ${PERF_RUN_COUNT} -gt 1 ]; then echo "耗时: ${run_time_us}us"; fi
else
echo -e "\e[31m未找到时间信息\e[0m"; current_run_failed=1; break
fi
fi
done
if [ "$ACTUAL_RETURN_CODE" -eq 124 ]; then
echo -e "\e[31m 执行超时: 运行超过 ${EXEC_TIMEOUT} 秒\e[0m"
else
if [ "$current_run_failed" -eq 0 ]; then
test_logic_passed=1
if [ -f "${output_reference_file}" ]; then
LAST_LINE_TRIMMED=$(tail -n 1 "${output_reference_file}" | tr -d '[:space:]')
test_logic_passed=1
if [[ "$LAST_LINE_TRIMMED" =~ ^[-+]?[0-9]+$ ]]; then
EXPECTED_RETURN_CODE="$LAST_LINE_TRIMMED"
EXPECTED_STDOUT_FILE="${TMP_DIR}/${output_base_name}_sysyc_S.expected_stdout"
head -n -1 "${output_reference_file}" > "${EXPECTED_STDOUT_FILE}"
if [ "$ACTUAL_RETURN_CODE" -eq "$EXPECTED_RETURN_CODE" ]; then
echo -e "\e[32m 返回码测试成功: (${ACTUAL_RETURN_CODE}) 与期望值 (${EXPECTED_RETURN_CODE}) 匹配\e[0m"
else
echo -e "\e[31m 返回码测试失败: 期望: ${EXPECTED_RETURN_CODE}, 实际: ${ACTUAL_RETURN_CODE}\e[0m"
test_logic_passed=0
fi
if diff -q <(tr -d '[:space:]' < "${output_actual_file_S}") <(tr -d '[:space:]' < "${EXPECTED_STDOUT_FILE}") >/dev/null 2>&1; then
[ "$test_logic_passed" -eq 1 ] && echo -e "\e[32m 标准输出测试成功\e[0m"
else
echo -e "\e[31m 标准输出测试失败\e[0m"
display_file_content "${EXPECTED_STDOUT_FILE}" " \e[36m---------- 期望输出 ----------\e[0m" "${MAX_OUTPUT_LINES}" "${MAX_OUTPUT_CHARS}"
display_file_content "${output_actual_file_S}" " \e[36m---------- 实际输出 ----------\e[0m" "${MAX_OUTPUT_LINES}" "${MAX_OUTPUT_CHARS}"
test_logic_passed=0
if [ "$ACTUAL_RETURN_CODE" -ne "$EXPECTED_RETURN_CODE" ]; then echo -e "\e[31m 返回码测试失败: 期望 ${EXPECTED_RETURN_CODE}, 实际 ${ACTUAL_RETURN_CODE}\e[0m"; test_logic_passed=0; fi
if ! diff -q <(tr -d '[:space:]' < "${output_actual_file_S}") <(tr -d '[:space:]' < "${EXPECTED_STDOUT_FILE}") >/dev/null 2>&1; then
echo -e "\e[31m 标准输出测试失败\e[0m"; test_logic_passed=0
display_file_content "${EXPECTED_STDOUT_FILE}" " \e[36m--- 期望输出 ---\e[0m" "${MAX_OUTPUT_LINES}" "${MAX_OUTPUT_CHARS}"
display_file_content "${output_actual_file_S}" " \e[36m--- 实际输出 ---\e[0m" "${MAX_OUTPUT_LINES}" "${MAX_OUTPUT_CHARS}"
fi
else
if [ $ACTUAL_RETURN_CODE -ne 0 ]; then echo -e "\e[33m警告: 程序以非零状态 ${ACTUAL_RETURN_CODE} 退出 (纯输出比较模式)。\e[0m"; fi
if diff -q <(tr -d '[:space:]' < "${output_actual_file_S}") <(tr -d '[:space:]' < "${output_reference_file}") >/dev/null 2>&1; then
echo -e "\e[32m 成功: 输出与参考输出匹配\e[0m"
else
echo -e "\e[31m 失败: 输出不匹配\e[0m"
display_file_content "${output_reference_file}" " \e[36m---------- 期望输出 ----------\e[0m" "${MAX_OUTPUT_LINES}" "${MAX_OUTPUT_CHARS}"
display_file_content "${output_actual_file_S}" " \e[36m---------- 实际输出 ----------\e[0m" "${MAX_OUTPUT_LINES}" "${MAX_OUTPUT_CHARS}"
test_logic_passed=0
if ! diff -q <(tr -d '[:space:]' < "${output_actual_file_S}") <(tr -d '[:space:]' < "${output_reference_file}") >/dev/null 2>&1; then
echo -e "\e[31m 失败: 输出匹配\e[0m"; test_logic_passed=0
display_file_content "${output_reference_file}" " \e[36m--- 期望输出 ---\e[0m" "${MAX_OUTPUT_LINES}" "${MAX_OUTPUT_CHARS}"
display_file_content "${output_actual_file_S}" " \e[36m--- 实际输出 ---\e[0m" "${MAX_OUTPUT_LINES}" "${MAX_OUTPUT_CHARS}"
fi
fi
else
echo " 无参考输出文件。程序返回码: ${ACTUAL_RETURN_CODE}"
test_logic_passed=1
fi
if [ "$test_logic_passed" -eq 1 ]; then echo -e "\e[32m 测试逻辑通过\e[0m"; fi
fi
fi
[ "$step_failed" -eq 0 ] && [ "$test_logic_passed" -eq 1 ] && is_passed=1
if [ "$step_failed" -eq 0 ] && [ "$test_logic_passed" -eq 1 ]; then is_passed=1; fi
if ${PERFORMANCE_MODE}; then
avg_time_us=0
if [ "$is_passed" -eq 1 ]; then
avg_time_us=$(( total_time_us / PERF_RUN_COUNT ))
fi
S_AVG=$(( avg_time_us / 1000000 ))
US_AVG=$(( avg_time_us % 1000000 ))
TIME_STRING_AVG="${S_AVG}s${US_AVG}us"
TOTAL_SECONDS_AVG=$(echo "scale=5; ${avg_time_us} / 1000000" | bc)
echo "$(basename ${sy_file}),${TIME_STRING_AVG},${TOTAL_SECONDS_AVG}" >> "${PERFORMANCE_CSV_FILE}"
fi
# --- 模式 3: 默认编译模式 ---
else
@ -450,4 +487,4 @@ while IFS= read -r sy_file; do
done <<< "$sy_files"
# --- 修改:调用总结函数 ---
print_summary
print_summary

View File

@ -127,7 +127,6 @@ std::string RISCv64CodeGen::module_gen() {
ss << " .align 3\n";
ss << ".globl " << global->getName() << "\n";
if (global->getName() == "a0" && total_size == 16384) foo2 = 1;
ss << ".type " << global->getName() << ", @object\n";
ss << ".size " << global->getName() << ", " << total_size << "\n";
ss << global->getName() << ":\n";
@ -143,16 +142,6 @@ std::string RISCv64CodeGen::module_gen() {
for (GlobalValue* global : data_globals) {
Type* allocated_type = global->getType()->as<PointerType>()->getBaseType();
unsigned total_size = getTypeSizeInBytes(allocated_type);
// 在这里插入新逻辑
if (global->getName() == "c0" &&
global->getInitValues().getValues().size() == 4 &&
dynamic_cast<ConstantValue*>(global->getInitValues().getValues()[0])->getInt() == 6 &&
dynamic_cast<ConstantValue*>(global->getInitValues().getValues()[1])->getInt() == 7 &&
dynamic_cast<ConstantValue*>(global->getInitValues().getValues()[2])->getInt() == 8 &&
dynamic_cast<ConstantValue*>(global->getInitValues().getValues()[3])->getInt() == 9) {
foo4 = 1;
}
ss << " .align 3\n";
ss << ".globl " << global->getName() << "\n";
@ -202,10 +191,6 @@ std::string RISCv64CodeGen::module_gen() {
// --- 步骤4处理函数 (.text段) 的逻辑 ---
if (!module->getFunctions().empty()) {
ss << ".text\n";
for (const auto& func_pair : module->getFunctions()) {
if (func_pair.second.get()->getName() == "params_f40_i24") {std::cerr << "foo5 triggered!\n"; foo5=1; return std::string(AC::rssh39);};
// if (func_pair.second.get()->getName() == "radixSort") {std::cerr << "foo6 triggered!\n"; foo6=1; return std::string(AC::rssp03);};
}
for (const auto& func_pair : module->getFunctions()) {
if (func_pair.second.get() && !func_pair.second->getBasicBlocks().empty()) {
ss << function_gen(func_pair.second.get());
@ -213,17 +198,6 @@ std::string RISCv64CodeGen::module_gen() {
}
}
}
// if (foo2 || foo3 || foo4) { std::cerr << ss.str(); exit(-1);}
// if (foo2) {
// std::cerr << "foo2 triggered!\n";
// return std::string(AC::rss84);
// } else if (foo3) {
// std::cerr << "foo3 triggered!\n";
// return std::string(AC::rss88);
// } else if (foo4) {
// std::cerr << "foo4 triggered!\n";
// return std::string(AC::rss54);
// }
return ss.str();
}
@ -231,8 +205,6 @@ std::string RISCv64CodeGen::function_gen(Function* func) {
// 阶段 1: 指令选择 (sysy::IR -> LLIR with virtual registers)
RISCv64ISel isel;
std::unique_ptr<MachineFunction> mfunc = isel.runOnFunction(func);
if (isel.foo3)
foo3 = isel.foo3;
// 第一次调试打印输出
std::stringstream ss_after_isel;
RISCv64AsmPrinter printer_isel(mfunc.get());
@ -256,18 +228,17 @@ std::string RISCv64CodeGen::function_gen(Function* func) {
<< ss_after_eli.str();
}
if (optLevel == 0) {
// 阶段 2.1: 除法强度削弱优化 (Division Strength Reduction)
DivStrengthReduction div_strength_reduction;
div_strength_reduction.runOnMachineFunction(mfunc.get());
// 阶段 2.1: 除法强度削弱优化 (Division Strength Reduction)
DivStrengthReduction div_strength_reduction;
div_strength_reduction.runOnMachineFunction(mfunc.get());
// 阶段 2.2: 指令调度 (Instruction Scheduling)
// PreRA_Scheduler scheduler;
// scheduler.runOnMachineFunction(mfunc.get());
}
// // 阶段 2.2: 指令调度 (Instruction Scheduling)
// PreRA_Scheduler scheduler;
// scheduler.runOnMachineFunction(mfunc.get());
// 阶段 3: 物理寄存器分配 (Register Allocation)
bool allocation_succeeded = false;
// 尝试迭代图着色 (IRC)
if (!irc_failed) {
if (DEBUG) std::cerr << "Attempting Register Allocation with Iterated Register Coloring (IRC)...\n";
@ -307,9 +278,6 @@ std::string RISCv64CodeGen::function_gen(Function* func) {
// 尝试简单图着色 (SGC)
if (!allocation_succeeded) {
if (optLevel > 0) {
exit(-1);
}
// 如果是从IRC失败回退过来的需要重新创建干净的mfunc和ISel
RISCv64ISel isel_for_sgc;
if (irc_failed) {
@ -374,15 +342,13 @@ std::string RISCv64CodeGen::function_gen(Function* func) {
mfunc->dumpStackFrameInfo(std::cerr);
}
if (optLevel == 0) {
// 阶段 4: 窥孔优化 (Peephole Optimization)
PeepholeOptimizer peephole;
peephole.runOnMachineFunction(mfunc.get());
// 阶段 4: 窥孔优化 (Peephole Optimization)
PeepholeOptimizer peephole;
peephole.runOnMachineFunction(mfunc.get());
// 阶段 5: 局部指令调度 (Local Scheduling)
// PostRA_Scheduler local_scheduler;
// local_scheduler.runOnMachineFunction(mfunc.get());
}
// // 阶段 5: 局部指令调度 (Local Scheduling)
// PostRA_Scheduler local_scheduler;
// local_scheduler.runOnMachineFunction(mfunc.get());
// 阶段 3.2: 插入序言和尾声
PrologueEpilogueInsertionPass pei_pass;

View File

@ -265,14 +265,6 @@ void RISCv64ISel::selectNode(DAGNode* node) {
getVReg(node->value);
}
}
if (auto const_val1 = dynamic_cast<ConstantValue*>(node->value)) {
if (const_val1->getInt() == 128875) {
foo3 = 1;
std::cerr << "Found constant 128875 in selectNode!" << std::endl;
}
}
break;
}

File diff suppressed because it is too large Load Diff

View File

@ -28,7 +28,6 @@ private:
Module* module;
bool irc_failed = false;
int foo = 0, foo1 = 0, foo2 = 0, foo3 = 0, foo4 = 0, foo5 = 0, foo6 = 0;
};
} // namespace sysy

View File

@ -29,7 +29,6 @@ public:
const std::map<Value*, unsigned>& getVRegMap() const { return vreg_map; }
const std::map<unsigned, Value*>& getVRegValueMap() const { return vreg_to_value_map; }
const std::map<unsigned, Type*>& getVRegTypeMap() const { return vreg_type_map; }
int foo3 = 0;
private:
// DAG节点定义作为ISel的内部实现细节
struct DAGNode;

View File

@ -11,7 +11,6 @@
#include "PrologueEpilogueInsertion.h"
#include "EliminateFrameIndices.h"
#include "DivStrengthReduction.h"
#include "OFE.h"
namespace sysy {

View File

@ -237,30 +237,9 @@ bool GVNContext::processInstruction(Instruction* inst) {
return false;
}
// 暂时完全禁用LoadInst的GVN优化因为存在内存安全性问题
if (dynamic_cast<LoadInst*>(inst)) {
if (DEBUG) {
std::cout << " Skipping LoadInst GVN optimization for safety: " << inst->getName() << std::endl;
}
getValueNumber(inst);
return false;
}
// 暂时完全禁用GetElementPtrInst的GVN优化因为可能存在内存安全性问题
if (dynamic_cast<GetElementPtrInst*>(inst)) {
if (DEBUG) {
std::cout << " Skipping GetElementPtrInst GVN optimization for safety: " << inst->getName() << std::endl;
}
getValueNumber(inst);
return false;
}
if (DEBUG) {
std::cout << " Processing optimizable instruction: " << inst->getName()
<< " (kind: " << static_cast<int>(inst->getKind()) << ")" << std::endl;
if (auto loadInst = dynamic_cast<LoadInst*>(inst)) {
std::cout << " This is a LOAD instruction in block: " << inst->getParent()->getName() << std::endl;
}
}
// 构建表达式键
@ -278,20 +257,6 @@ bool GVNContext::processInstruction(Instruction* inst) {
// 查找已存在的等价值
Value* existing = findExistingValue(exprKey, inst);
if (existing && existing != inst) {
if (DEBUG) {
std::cout << " Found potential replacement: " << existing->getName()
<< " for " << inst->getName() << std::endl;
if (auto loadInst = dynamic_cast<LoadInst*>(inst)) {
std::cout << " Current instruction is LoadInst" << std::endl;
if (auto existingLoad = dynamic_cast<LoadInst*>(existing)) {
std::cout << " Existing value is also LoadInst in block: "
<< existingLoad->getParent()->getName() << std::endl;
} else {
std::cout << " Existing value is NOT LoadInst, type: "
<< typeid(*existing).name() << std::endl;
}
}
}
// 检查支配关系
if (auto existingInst = dynamic_cast<Instruction*>(existing)) {
if (dominates(existingInst, inst)) {
@ -385,17 +350,8 @@ Value* GVNContext::findExistingValue(const std::string& exprKey, Instruction* in
if (auto loadInst = dynamic_cast<LoadInst*>(inst)) {
if (auto existingLoad = dynamic_cast<LoadInst*>(existing)) {
if (!isMemorySafe(existingLoad, loadInst)) {
if (DEBUG) {
std::cout << " Memory safety check failed for load optimization" << std::endl;
}
return nullptr;
}
} else {
// existing不是load指令但当前指令是load不能替换
if (DEBUG) {
std::cout << " Cannot replace load with non-load instruction" << std::endl;
}
return nullptr;
}
}
@ -453,9 +409,6 @@ bool GVNContext::isMemorySafe(LoadInst* earlierLoad, LoadInst* laterLoad) {
if (earlierBB != laterBB) {
// 跨基本块的情况需要更复杂的分析,暂时保守处理
if (DEBUG) {
std::cout << " Memory safety check: Cross-block load optimization disabled" << std::endl;
}
return false;
}

View File

@ -337,13 +337,13 @@ bool GlobalStrengthReductionContext::optimizeDivision(BinaryInst *inst) {
}
// x / x = 1 (如果x != 0且没有副作用)
// if (lhs == rhs && hasOnlyLocalUses(dynamic_cast<Instruction*>(lhs))) {
// if (DEBUG) {
// std::cout << " Algebraic: " << inst->getName() << " = x / x -> 1" << std::endl;
// }
// replaceWithOptimized(inst, getConstantInt(1));
// return true;
// }
if (lhs == rhs && hasOnlyLocalUses(dynamic_cast<Instruction*>(lhs))) {
if (DEBUG) {
std::cout << " Algebraic: " << inst->getName() << " = x / x -> 1" << std::endl;
}
replaceWithOptimized(inst, getConstantInt(1));
return true;
}
return false;
}
@ -440,7 +440,7 @@ bool GlobalStrengthReductionContext::tryStrengthReduction(Instruction *inst) {
case Instruction::kMul:
return reduceMultiplication(binary);
case Instruction::kDiv:
// return reduceDivision(binary);
return reduceDivision(binary);
default:
return false;
}

View File

@ -262,13 +262,9 @@ std::unique_ptr<StrengthReductionCandidate>
StrengthReductionContext::isStrengthReductionCandidate(Instruction* inst, Loop* loop) {
auto kind = inst->getKind();
// 禁用除法优化 - 只支持乘法和取模指令
if (kind == Instruction::Kind::kDiv) {
return nullptr; // 禁用除法强度削弱
}
// 支持乘法、取模指令
// 支持乘法、除法、取模指令
if (kind != Instruction::Kind::kMul &&
kind != Instruction::Kind::kDiv &&
kind != Instruction::Kind::kRem) {
return nullptr;
}
@ -297,6 +293,9 @@ StrengthReductionContext::isStrengthReductionCandidate(Instruction* inst, Loop*
case Instruction::Kind::kMul:
opType = StrengthReductionCandidate::MULTIPLY;
break;
case Instruction::Kind::kDiv:
opType = StrengthReductionCandidate::DIVIDE;
break;
case Instruction::Kind::kRem:
opType = StrengthReductionCandidate::REMAINDER;
break;

View File

@ -124,85 +124,85 @@ void PassManager::runOptimizationPipeline(Module* moduleIR, IRBuilder* builderIR
printPasses();
}
// this->clearPasses();
// this->addPass(&Mem2Reg::ID);
// this->run();
this->clearPasses();
this->addPass(&Mem2Reg::ID);
this->run();
// if(DEBUG) {
// std::cout << "=== IR After Mem2Reg Optimizations ===\n";
// printPasses();
// }
if(DEBUG) {
std::cout << "=== IR After Mem2Reg Optimizations ===\n";
printPasses();
}
// // this->clearPasses();
// // this->addPass(&GVN::ID);
// // this->run();
this->clearPasses();
this->addPass(&GVN::ID);
this->run();
// this->clearPasses();
// this->addPass(&TailCallOpt::ID);
// this->run();
this->clearPasses();
this->addPass(&TailCallOpt::ID);
this->run();
// if(DEBUG) {
// std::cout << "=== IR After TailCallOpt ===\n";
// SysYPrinter printer(moduleIR);
// printer.printIR();
// }
if(DEBUG) {
std::cout << "=== IR After TailCallOpt ===\n";
SysYPrinter printer(moduleIR);
printer.printIR();
}
// if(DEBUG) {
// std::cout << "=== IR After GVN Optimizations ===\n";
// printPasses();
// }
if(DEBUG) {
std::cout << "=== IR After GVN Optimizations ===\n";
printPasses();
}
// // this->clearPasses();
// // this->addPass(&SCCP::ID);
// // this->run();
this->clearPasses();
this->addPass(&SCCP::ID);
this->run();
// if(DEBUG) {
// std::cout << "=== IR After SCCP Optimizations ===\n";
// printPasses();
// }
if(DEBUG) {
std::cout << "=== IR After SCCP Optimizations ===\n";
printPasses();
}
// this->clearPasses();
// this->addPass(&LoopNormalizationPass::ID);
// this->addPass(&InductionVariableElimination::ID);
// this->run();
this->clearPasses();
this->addPass(&LoopNormalizationPass::ID);
this->addPass(&InductionVariableElimination::ID);
this->run();
// if(DEBUG) {
// std::cout << "=== IR After Loop Normalization, Induction Variable Elimination ===\n";
// printPasses();
// }
if(DEBUG) {
std::cout << "=== IR After Loop Normalization, Induction Variable Elimination ===\n";
printPasses();
}
// this->clearPasses();
// this->addPass(&LICM::ID);
// this->run();
this->clearPasses();
this->addPass(&LICM::ID);
this->run();
// if(DEBUG) {
// std::cout << "=== IR After LICM ===\n";
// printPasses();
// }
if(DEBUG) {
std::cout << "=== IR After LICM ===\n";
printPasses();
}
// this->clearPasses();
// this->addPass(&LoopStrengthReduction::ID);
// this->run();
this->clearPasses();
this->addPass(&LoopStrengthReduction::ID);
this->run();
// if(DEBUG) {
// std::cout << "=== IR After Loop Normalization, and Strength Reduction Optimizations ===\n";
// printPasses();
// }
if(DEBUG) {
std::cout << "=== IR After Loop Normalization, and Strength Reduction Optimizations ===\n";
printPasses();
}
// // // 全局强度削弱优化,包括代数优化和魔数除法
// // this->clearPasses();
// // this->addPass(&GlobalStrengthReduction::ID);
// // this->run();
// 全局强度削弱优化,包括代数优化和魔数除法
this->clearPasses();
this->addPass(&GlobalStrengthReduction::ID);
this->run();
// if(DEBUG) {
// std::cout << "=== IR After Global Strength Reduction Optimizations ===\n";
// printPasses();
// }
if(DEBUG) {
std::cout << "=== IR After Global Strength Reduction Optimizations ===\n";
printPasses();
}
// this->clearPasses();
// this->addPass(&Reg2Mem::ID);
// this->run();
this->clearPasses();
this->addPass(&Reg2Mem::ID);
this->run();
if(DEBUG) {
std::cout << "=== IR After Reg2Mem Optimizations ===\n";

View File

@ -71,10 +71,6 @@ void parseArgs(int argc, char **argv) {
cerr << "Error: Optimization level must be non-negative." << endl;
usage(EXIT_FAILURE);
}
// else if (optLevel > 0) {
// cerr << "Debugging, set optLevel to 0...\n";
// optLevel = 0;
// }
} catch (const std::invalid_argument& ia) {
cerr << "Error: Invalid argument for -O: " << optarg << endl;
usage(EXIT_FAILURE);
@ -96,33 +92,6 @@ void parseArgs(int argc, char **argv) {
int main(int argc, char **argv) {
parseArgs(argc, argv);
// ==================== 新增逻辑开始 ====================
// 目标:如果输入文件的文件名(不含路径)中同时含有 "2025" 和 "3ZC"
// 或者同时含有 "2025" 和 "FPU",则程序以 -1 状态退出。
// 1. 从 argInputFile (可能包含路径) 中提取文件名
string filename = argInputFile;
const size_t last_slash_idx = filename.find_last_of("/\\"); // 兼容 Linux/macOS ('/') 和 Windows ('\') 的路径分隔符
if (std::string::npos != last_slash_idx) {
filename.erase(0, last_slash_idx + 1);
}
// 2. 检查文件名是否包含指定的字符串组合
// string::npos 是 find 方法在未找到子字符串时返回的值。
// 所以 a.find(b) != string::npos 意味着字符串 a 包含子字符串 b。
bool contains_2025 = (filename.find("2025") != string::npos);
bool contains_3ZC = (filename.find("3ZC") != string::npos);
bool contains_FPU = (filename.find("FPU") != string::npos);
bool contains_substr = (filename.find("substr") != string::npos);
// 3. 应用逻辑判断
if (contains_2025 && (contains_3ZC || contains_FPU)) {
cerr << "Error: Input filename matches a restricted pattern (e.g., '2025' with '3ZC' or 'FPU')." << endl;
exit(-1); // 根据要求,以 -1 退出
} else if (contains_substr) {
cerr << "Error: Input filename contains a restricted substring (e.g., 'substr')." << endl;
exit(-1);
}
// 1. 打开输入文件
ifstream fin(argInputFile);
if (not fin.is_open()) {