add_library(ib_sh4_state STATIC src/state.cpp)
target_include_directories(ib_sh4_state PUBLIC include)
target_compile_features(ib_sh4_state PUBLIC cxx_std_20)
# FPSCR.RM uses fesetround (sh4/fpu_ops.hpp); GCC ignores FENV_ACCESS without this.
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
    target_compile_options(ib_sh4_state PUBLIC -frounding-math)
endif()

add_library(ib_sh4_decoder STATIC src/decoder.cpp)
target_link_libraries(ib_sh4_decoder PUBLIC ib_sh4_state)

add_library(ib_sh4_aot_host STATIC src/aot_standalone.cpp)
target_link_libraries(ib_sh4_aot_host PUBLIC ib_sh4_state)

if(BUILD_TESTS)
    add_executable(ib_sh4_decoder_tests "${PROJECT_SOURCE_DIR}/tests/unit/sh4_decoder.cpp")
    target_link_libraries(ib_sh4_decoder_tests PRIVATE ib_sh4_decoder)
    add_test(NAME sh4_decoder COMMAND ib_sh4_decoder_tests)
endif()

if(BUILD_TESTS)
    # Single-step executor for synthetic tests only.
    add_executable(ib_sh4_semantics_tests
        "${PROJECT_SOURCE_DIR}/tests/unit/sh4_semantics.cpp"
        src/cpu.cpp)
    target_link_libraries(ib_sh4_semantics_tests PRIVATE ib_sh4_decoder)
    add_test(NAME sh4_semantics COMMAND ib_sh4_semantics_tests)
endif()

add_library(ib_sh4_codegen STATIC src/aot_emit.cpp)
target_link_libraries(ib_sh4_codegen PUBLIC ib_sh4_decoder)
add_executable(ib-recomp src/recomp.cpp)
target_link_libraries(ib-recomp PRIVATE ib_sh4_codegen)

add_executable(ib-sh4-aot src/aot_main.cpp)
target_link_libraries(ib-sh4-aot PRIVATE ib_sh4_codegen)

if(BUILD_TESTS)
    # Translates a synthetic program and checks it against the step executor.
    # Reads a program file, translates it and returns the generated source and
    # the words as a C++ initializer list.
    function(ib_sh4_aot_translate program_file function_name base_hex out_source out_define)
        file(READ "${program_file}" _text)
        string(STRIP "${_text}" _text)
        separate_arguments(_words UNIX_COMMAND "${_text}")
        list(TRANSFORM _words PREPEND "0x" OUTPUT_VARIABLE _literals)
        list(JOIN _literals "," _define)
        get_filename_component(_stem "${program_file}" NAME_WE)
        if("--standalone" IN_LIST ARGN)
            string(APPEND _stem "_${function_name}")
        endif()
        set(_generated "${CMAKE_CURRENT_BINARY_DIR}/${_stem}_generated.cpp")
        add_custom_command(
            OUTPUT "${_generated}"
            COMMAND ib-sh4-aot --output "${_generated}" --base ${base_hex} --name ${function_name} ${ARGN} ${_words}
            DEPENDS ib-sh4-aot "${program_file}"
            VERBATIM)
        set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${program_file}")
        set(${out_source} "${_generated}" PARENT_SCOPE)
        set(${out_define} "${_define}" PARENT_SCOPE)
    endfunction()

    function(ib_sh4_aot_diff_test name case_id)
        set(_dir "${PROJECT_SOURCE_DIR}/tests/unit")
        set(_defines "IB_CASE=${case_id}")
        set(_entry_args "")
        if(ARGN)
            list(POP_FRONT ARGN _entry)
            set(_entry_args --entry ${_entry} ${ARGN})
            list(APPEND _defines "IB_ENTRY=0x${_entry}")
        endif()
        ib_sh4_aot_translate("${_dir}/sh4_aot_${name}_program.txt" run 1000 _sources _program_define ${_entry_args})
        list(APPEND _defines "IB_PROGRAM=${_program_define}")
        # Optional second function at 0x1800, reached only through aot::dispatch.
        if(EXISTS "${_dir}/sh4_aot_${name}_callee.txt")
            ib_sh4_aot_translate("${_dir}/sh4_aot_${name}_callee.txt" callee 1800 _callee _callee_define)
            list(APPEND _sources "${_callee}")
            list(APPEND _defines "IB_CALLEE=${_callee_define}")
        endif()
        add_executable(ib_sh4_aot_${name}_tests
            "${PROJECT_SOURCE_DIR}/tests/unit/sh4_aot_diff.cpp"
            ${_sources}
            src/cpu.cpp)
        target_compile_definitions(ib_sh4_aot_${name}_tests PRIVATE ${_defines})
        target_link_libraries(ib_sh4_aot_${name}_tests PRIVATE ib_sh4_decoder)
        add_test(NAME sh4_aot_${name} COMMAND ib_sh4_aot_${name}_tests)
    endfunction()
    ib_sh4_aot_diff_test(memory 1)
    ib_sh4_aot_diff_test(fpu 2)
    ib_sh4_aot_diff_test(calls 3)
    ib_sh4_aot_diff_test(alu 4)
    ib_sh4_aot_diff_test(flow 5 1004)
    ib_sh4_aot_diff_test(indirect 6 1000 --readonly-literals)
    ib_sh4_aot_diff_test(frame 7 1000)
    find_package(Python3 COMPONENTS Interpreter REQUIRED)
    set(_image_dir "${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG>/image-fixture")
    set(_fixture "${PROJECT_SOURCE_DIR}/tests/unit/sh4_image_fixture.py")
    set(_fixture_sources "${_image_dir}/dispatch.cpp" "${_image_dir}/part_0.cpp" "${_image_dir}/part_1.cpp")
    add_custom_command(OUTPUT ${_fixture_sources}
        COMMAND "${Python3_EXECUTABLE}" "${_fixture}" "$<TARGET_FILE:ib-recomp>" "${_image_dir}"
        DEPENDS ib-recomp "${_fixture}" VERBATIM)
    add_executable(ib_sh4_image_tests "${PROJECT_SOURCE_DIR}/tests/unit/sh4_image.cpp" ${_fixture_sources})
    target_link_libraries(ib_sh4_image_tests PRIVATE ib_sh4_state)
    add_test(NAME sh4_image COMMAND ib_sh4_image_tests)
    add_test(NAME sh4_aot_flow_cli COMMAND ${Python3_EXECUTABLE}
        "${PROJECT_SOURCE_DIR}/tests/unit/sh4_aot_flow_cli.py"
        "$<TARGET_FILE:ib-sh4-aot>"
        "${PROJECT_SOURCE_DIR}/tests/unit/sh4_aot_flow_program.txt"
        "${PROJECT_SOURCE_DIR}/tests/unit/sh4_aot_indirect_program.txt")

    function(ib_sh4_aot_standalone_test name entry symbol)
        ib_sh4_aot_translate("${PROJECT_SOURCE_DIR}/tests/unit/sh4_aot_standalone_program.txt"
            ${symbol} 1000 _source _unused --entry ${entry} --standalone ${ARGN})
        add_executable(ib_sh4_aot_${name} "${_source}")
        target_link_libraries(ib_sh4_aot_${name} PRIVATE ib_sh4_aot_host)
    endfunction()
    # Also verify that the generated main can call a function named "image".
    ib_sh4_aot_standalone_test(standalone 1000 image)
    ib_sh4_aot_standalone_test(standalone_unmapped 1018 unmapped)
    ib_sh4_aot_standalone_test(standalone_readonly 101E readonly)
    ib_sh4_aot_standalone_test(standalone_trap 1026 trap)
    ib_sh4_aot_standalone_test(standalone_table 102C table --indirect-table 103C:2)
    ib_sh4_aot_standalone_test(standalone_relative_table 1052 relative_table --indirect-table-rel16 1064:2:1064)
    ib_sh4_aot_standalone_test(standalone_register_load 1076 register_load --readonly-literals)
    ib_sh4_aot_standalone_test(standalone_bounded_table 108C bounded_table --readonly-literals)
    ib_sh4_aot_translate("${PROJECT_SOURCE_DIR}/tests/unit/sh4_aot_indirect_program.txt"
        seeded 1000 _seeded_source _unused --entry 1000 --standalone
        --indirect-target 1018 --indirect-target 1028)
    add_executable(ib_sh4_aot_standalone_seeded "${_seeded_source}")
    target_link_libraries(ib_sh4_aot_standalone_seeded PRIVATE ib_sh4_aot_host)
    add_test(NAME sh4_aot_standalone COMMAND ${Python3_EXECUTABLE}
        "${PROJECT_SOURCE_DIR}/tests/unit/sh4_aot_standalone.py"
        "$<TARGET_FILE:ib_sh4_aot_standalone>"
        "$<TARGET_FILE:ib_sh4_aot_standalone_unmapped>"
        "$<TARGET_FILE:ib_sh4_aot_standalone_readonly>"
        "$<TARGET_FILE:ib_sh4_aot_standalone_trap>"
        "$<TARGET_FILE:ib_sh4_aot_standalone_seeded>"
        "$<TARGET_FILE:ib_sh4_aot_standalone_table>"
        "$<TARGET_FILE:ib_sh4_aot_standalone_relative_table>"
        "$<TARGET_FILE:ib_sh4_aot_standalone_register_load>"
        "$<TARGET_FILE:ib_sh4_aot_standalone_bounded_table>")
endif()
