From 75e4701a2281f846b9ed6e9e2476919fc41869e1 Mon Sep 17 00:00:00 2001 From: MarlomMedeiros Date: Sun, 22 Nov 2026 11:53:26 -0300 Subject: [PATCH] cpu: add SSE2 leaf AOT translator covering 23 forms --- CMakeLists.txt | 26 ++ docs/experiments.md | 39 ++ tests/cpu/sse2_regs.asm | 505 +++++++++++++++++++++++ tests/cpu/sse2_regs.def | 58 +++ tests/cpu/sse2_regs_check.py | 780 +++++++++++++++++++++++++++++++++++ tests/form_coverage_check.py | 56 +++ tools/cpu_sse2_aot.py | 618 +++++++++++++++++++++++++++ tools/form_coverage.py | 1 + 8 files changed, 2083 insertions(+) create mode 100644 tests/cpu/sse2_regs.asm create mode 100644 tests/cpu/sse2_regs.def create mode 100644 tests/cpu/sse2_regs_check.py create mode 100644 tools/cpu_sse2_aot.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 13e1461c..5dda687b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -740,6 +740,32 @@ if(EXISTS "${INTAKE_PYTHON}") "$" "$" "$") + set(cpu_sse2_exports + "op_cmppd_0,op_cmppd_1,op_cmppd_2,op_cmppd_3,op_cmppd_4,op_cmppd_5,op_cmppd_6,op_cmppd_7," + "op_cmppd_mem," + "op_maxsd_reg,op_maxsd_mem,op_minsd_reg,op_minsd_mem,op_sqrtsd_reg,op_sqrtsd_mem," + "op_cvtsd2si_r32_reg,op_cvtsd2si_r64_reg,op_cvtsd2si_r32_mem,op_cvtsd2si_r64_mem," + "op_cvtdq2pd_reg,op_cvtdq2pd_mem,op_cvtdq2ps_reg,op_cvtdq2ps_mem," + "op_cvtpd2dq_reg,op_cvtpd2dq_mem,op_cvtpd2ps_reg,op_cvtpd2ps_mem,op_cvtpi2pd_mem," + "op_cvtps2dq_reg,op_cvtps2dq_mem,op_cvtps2pd_reg,op_cvtps2pd_mem," + "op_cvttpd2dq_reg,op_cvttpd2dq_mem,op_cvttps2dq_reg,op_cvttps2dq_mem," + "op_movapd_ls,op_movapd_reg,op_movdqa_ls,op_movdqa_reg," + "op_movhpd_load,op_movhpd_store,op_movlpd_load,op_movlpd_store," + "op_movhpd_load_plus1,op_movlpd_load_plus1," + "op_movhpd_store_plus1,op_movlpd_store_plus1,op_maxsd_mem_plus1,op_cvtsd2si_mem_plus1," + "op_movntdq,op_movntpd,op_movnti32,op_movnti64," + "op_lfence,op_mfence,op_pipeline") + string(CONCAT cpu_sse2_exports ${cpu_sse2_exports}) + foreach(variant IN ITEMS original altered) + cpu_asm_fixture(cpu_sse2_regs_${variant} sse2_regs) + cpu_translation(cpu_sse2_regs_${variant} cpu_sse2_aot "${cpu_sse2_exports}") + endforeach() + target_compile_definitions(cpu_sse2_regs_altered PRIVATE ALTER_IMM) + add_test(NAME cpu_aot_sse2_regs COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/sse2_regs_check.py" + "$" + "$" + "$") # Import tail jumps: one caller per provider (named, altered return, ordinal-only), each translated twice: # tail_mix (three arguments) bound to mix3 with three, tail_choose (three) and tail_pass4 (four) to mix4 with four. set(tail_files) diff --git a/docs/experiments.md b/docs/experiments.md index 54746744..895f2834 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -1639,6 +1639,45 @@ Not covered: RIP-relative constants, packed operations, `SQRT`, `MIN` and `MAX`, On Linux, `llvm-ml` assembled the fixture and `lld-link` linked it. The original machine code ran in-process through a Windows-ABI trampoline that loads each slot into both its integer and its XMM register. It matched the lifted C++ built with clang at `-O0`, `-O2` and `-O3` on every call, for both builds, and all rejection controls passed. The generated sources compile without warnings under clang-cl `/W4 /WX`. A Windows run of `cpu_aot_scalar_float` with ML64 and MSVC has not been recorded yet. +## Legacy SSE2 leaf recompilation + +[The SSE2 leaf translator](../tools/cpu_sse2_aot.py) lifts bounded straight-line Windows x64 leaf functions covering 23 of the 64 forms in `docs/coverage/x64_zen2.tsv` group `SSE2`: + +- Packed compare: `cmppd` (all eight `imm8` predicates, `xmm` and `m128` sources) +- Packed converts: `cvtdq2pd`, `cvtdq2ps`, `cvtpd2dq`, `cvtpd2ps`, `cvtps2dq`, `cvtps2pd`, `cvttpd2dq`, `cvttps2dq` +- MMX-domain source convert: `cvtpi2pd` (flat `m64` memory source only) +- Scalar convert: `cvtsd2si` (`r32`/`r64` destinations, `xmm` or `m64` source) +- Scalar double ops: `maxsd`, `minsd`, `sqrtsd` (merge into the destination's low qword) +- Fences: `lfence`, `mfence` +- Aligned moves: `movapd`, `movdqa` (register copies, loads, stores) +- Half-qword moves: `movhpd`, `movlpd` (`m64` load merge and `m64` store) +- Non-temporal stores: `movntdq`, `movntpd`, `movnti` (`r32` and `r64`) + +Each lifted export takes `(word rcx, word rdx, word r8)` pointing to caller-owned flat buffers and returns `void`. For transport and ABI glue the translator accepts 32/64-bit `mov` between the volatile scratch GPRs (`rax`, `r9`, `r10`, `r11`) and flat `[base + disp]` memory rooted in an argument, plus terminal `ret`. + +### State model and explicit rejections + +XMM registers `xmm0`..`xmm5` are represented as a portable C++ value struct (`struct Vec128 { std::uint64_t q[2]; }`) rather than MSVC intrinsics, so the generated C++ compiles under default x64 flags. Moves and compares transfer raw bits. The packed-conversion helpers use host floating-point operations and reproduce the SSE2 rounding and truncation rules written out in the code: `cvtpd2dq`/`cvtps2dq`/`cvtsd2si` round to nearest even, `cvttpd2dq`/`cvttps2dq` truncate, NaN or out-of-range results return the integer indefinite value (`0x80000000` or `0x8000000000000000`), `maxsd`/`minsd` return the second source on ties and unordered inputs, and `sqrtsd` returns the quieted source NaN or the real indefinite for negative inputs. `lfence`/`mfence` lower to `std::atomic_signal_fence(std::memory_order_seq_cst)`, keeping the ordering contract without observable register state. All memory operands must be flat `[base + disp]` rooted in `rcx`, `rdx` or `r8`. + +The translator explicitly rejects: + +- the 36 SSE2-group forms reserved for sibling translators (`addpd`, `movdqu`, `pshufd`, `ucomisd` and the others in the fixture check), so each SSE2 form has a single owner; +- the five task forms that cannot be expressed through the leaf ABI: `cvtpd2pi`, `cvttpd2pi`, `movdq2q` and `movq2dq` use MMX register operands, and `maskmovdqu` stores through implicit `DS:rdi`; +- the `mm`-register source of `cvtpi2pd`, `cmppd` immediates above 7, non-legacy (VEX/EVEX) encodings, `lock`/`rep`/segment prefixes, nonvolatile vector registers (`xmm6`..`xmm15`), nonvolatile or argument GPR destinations, undefined registers, non-flat memory operands, missing terminal `ret` and instructions after `ret`. + +```powershell +cmake --build --preset dev --target cpu_sse2_regs_original cpu_sse2_regs_original_lifted cpu_sse2_regs_altered cpu_sse2_regs_altered_lifted +ctest --preset dev --no-tests=error -R '^cpu_aot_sse2_regs$' -V +``` + +### Measured results and open scope + +The [MASM fixture](../tests/cpu/sse2_regs.asm) builds 57 exports covering all 23 forms: eight `cmppd` predicate exports plus an `m128`-source case, register and memory forms of every scalar op and convert, with the six upper-zeroing converts run on dirty-seeded destinations so zeroing versus merging is observable, `cvtpi2pd` from memory, aligned load/store and register copies, `movhpd`/`movlpd` merges including unaligned `+1` memory loads and `+1` stores, unaligned `+1` `m64` sources for `maxsd` and `cvtsd2si`, non-temporal stores and a chained `op_pipeline` export. [The Windows test](../tests/cpu/sse2_regs_check.py) ran 1,168 differential cases across the 57 exports against both the native MASM DLL and an independent Python reference model, covering IEEE-754 specials (signed zero, subnormals, infinities, sNaN and qNaN with distinct payloads), integer-indefinite boundaries at 2^31 and 2^63, boundary conversion values and random patterns, with 32-byte pre/post guards on every buffer. + +An `ALTER_IMM` variant changes the `cmppd` predicates of `op_cmppd_1` (1 to 5), `op_cmppd_3` (3 to 7) and `op_cmppd_6` (6 to 2); the altered translation must match the altered reference while diverging from the unmodified reference, which it did on 28 cases each. An output-mutation negative control flips one bit of `op_pipeline` and confirms the comparator fails. Rejection controls cover 10 alternate-encoding lift checks (non-`rax` `cvtsd2si`/`movnti` operands, displaced memory forms, standalone fences), 66 unit cases (36 reserved SSE2 forms, 7 MMX/implicit-address encodings, 1 `cmppd` immediate, 4 VEX/EVEX encodings, 18 ABI/state/addressing/prefix violations) and 12 end-to-end PE-patched DLL cases. In `tools/form_coverage.py`, `sse2_regs.asm` accounts for exactly its 23 SSE2 forms, advancing x64 Zen 2 `SSE2` group coverage from 14/64 to 37/64 and total x64 Zen 2 coverage from 549/948 to 572/948 (+23). + +Not covered by this experiment: the 36 reserved SSE2 forms, MMX-domain operands and `maskmovdqu`, control flow or calls mixed with SSE2 state, nonvolatile `XMM6`..`XMM15` save/restore prologues, unaligned `movapd`/`movdqa`/`movntdq`/`movntpd` faults (the aligned loads/stores lower to `memcpy` and accept any address), and title CPU code execution. + ## D3D12 pixel-position inputs `pixel_position_centers` compiles a standalone Shader Model 6.0 pixel shader. Its inputs are `float4 TEXCOORD0` and `float4 SV_Position`, in the order emitted by the existing full-screen vertex shader. Red and green depend only on `SV_Position`. The test reads an 8×8 RGBA32F target with a 5×3 viewport at (2, 1). The CPU reference expects red and green to contain the absolute pixel center coordinates, with a half-pixel offset on each axis. The other 49 pixels retain the clear color. A second shader exchanges red and green and must first disagree at (2, 1), where the expected coordinates are (2.5, 1.5). [HLSL system-value semantics](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-semantics) diff --git a/tests/cpu/sse2_regs.asm b/tests/cpu/sse2_regs.asm new file mode 100644 index 00000000..0ef2c65c --- /dev/null +++ b/tests/cpu/sse2_regs.asm @@ -0,0 +1,505 @@ +; Source-built MASM fixture exercising 23 SSE2 forms from docs/coverage/x64_zen2.tsv +; group SSE2: cmppd, every packed/scalar convert expressible in the leaf ABI, +; maxsd/minsd/sqrtsd, lfence/mfence and the aligned, half-qword and +; non-temporal moves. The MMX-operand forms (cvtpd2pi, cvttpd2pi, movdq2q, +; movq2dq, cvtpi2pd mm source) and implicit-RDI maskmovdqu are outside the leaf +; ABI and are lifted as rejections, not exports. +; Every export uses the Windows x64 leaf ABI: +; RCX = const void* input_a (32 bytes, 16-byte aligned) +; RDX = const void* input_b (32 bytes, 16-byte aligned; second vector at +16) +; R8 = void* output (32 bytes, 16-byte aligned) +.code + +; --- cmppd: all eight predicates on register and aligned m128 sources --- + +op_cmppd_0 PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + movdqa xmm1, XMMWORD PTR [rdx] + cmppd xmm0, xmm1, 0 + movdqa XMMWORD PTR [r8], xmm0 + ret +op_cmppd_0 ENDP + +op_cmppd_1 PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + movdqa xmm1, XMMWORD PTR [rdx] +IFDEF ALTER_IMM + cmppd xmm0, xmm1, 5 +ELSE + cmppd xmm0, xmm1, 1 +ENDIF + movdqa XMMWORD PTR [r8], xmm0 + ret +op_cmppd_1 ENDP + +op_cmppd_2 PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + movdqa xmm1, XMMWORD PTR [rdx] + cmppd xmm0, xmm1, 2 + movdqa XMMWORD PTR [r8], xmm0 + ret +op_cmppd_2 ENDP + +op_cmppd_3 PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + movdqa xmm1, XMMWORD PTR [rdx] +IFDEF ALTER_IMM + cmppd xmm0, xmm1, 7 +ELSE + cmppd xmm0, xmm1, 3 +ENDIF + movdqa XMMWORD PTR [r8], xmm0 + ret +op_cmppd_3 ENDP + +op_cmppd_4 PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + movdqa xmm1, XMMWORD PTR [rdx] + cmppd xmm0, xmm1, 4 + movdqa XMMWORD PTR [r8], xmm0 + ret +op_cmppd_4 ENDP + +op_cmppd_5 PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + movdqa xmm1, XMMWORD PTR [rdx] + cmppd xmm0, xmm1, 5 + movdqa XMMWORD PTR [r8], xmm0 + ret +op_cmppd_5 ENDP + +op_cmppd_6 PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + movdqa xmm1, XMMWORD PTR [rdx] +IFDEF ALTER_IMM + cmppd xmm0, xmm1, 2 +ELSE + cmppd xmm0, xmm1, 6 +ENDIF + movdqa XMMWORD PTR [r8], xmm0 + ret +op_cmppd_6 ENDP + +op_cmppd_7 PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + movdqa xmm1, XMMWORD PTR [rdx] + cmppd xmm0, xmm1, 7 + movdqa XMMWORD PTR [r8], xmm0 + ret +op_cmppd_7 ENDP + +op_cmppd_mem PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + cmppd xmm0, XMMWORD PTR [rdx], 5 + movdqa XMMWORD PTR [r8], xmm0 + ret +op_cmppd_mem ENDP + +; --- Scalar double ops: low-qword merge, high-qword preserved --- + +op_maxsd_reg PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + movdqa xmm1, XMMWORD PTR [rdx] + maxsd xmm0, xmm1 + movdqa XMMWORD PTR [r8], xmm0 + ret +op_maxsd_reg ENDP + +op_maxsd_mem PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + maxsd xmm0, QWORD PTR [rdx] + movdqa XMMWORD PTR [r8], xmm0 + ret +op_maxsd_mem ENDP + +op_minsd_reg PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + movdqa xmm1, XMMWORD PTR [rdx] + minsd xmm0, xmm1 + movdqa XMMWORD PTR [r8], xmm0 + ret +op_minsd_reg ENDP + +op_minsd_mem PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + minsd xmm0, QWORD PTR [rdx] + movdqa XMMWORD PTR [r8], xmm0 + ret +op_minsd_mem ENDP + +op_sqrtsd_reg PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + movdqa xmm1, XMMWORD PTR [rdx] + sqrtsd xmm0, xmm1 + movdqa XMMWORD PTR [r8], xmm0 + ret +op_sqrtsd_reg ENDP + +op_sqrtsd_mem PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + sqrtsd xmm0, QWORD PTR [rdx] + movdqa XMMWORD PTR [r8], xmm0 + ret +op_sqrtsd_mem ENDP + +; --- cvtsd2si: r32 and r64 destinations, xmm and m64 sources --- + +op_cvtsd2si_r32_reg PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + cvtsd2si eax, xmm0 + mov DWORD PTR [r8], eax + ret +op_cvtsd2si_r32_reg ENDP + +op_cvtsd2si_r64_reg PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + cvtsd2si rax, xmm0 + mov QWORD PTR [r8], rax + ret +op_cvtsd2si_r64_reg ENDP + +op_cvtsd2si_r32_mem PROC FRAME + .endprolog + cvtsd2si eax, QWORD PTR [rdx] + mov DWORD PTR [r8], eax + ret +op_cvtsd2si_r32_mem ENDP + +op_cvtsd2si_r64_mem PROC FRAME + .endprolog + cvtsd2si rax, QWORD PTR [rdx] + mov QWORD PTR [r8], rax + ret +op_cvtsd2si_r64_mem ENDP + +; --- Packed converts --- + +op_cvtdq2pd_reg PROC FRAME + .endprolog + movdqa xmm1, XMMWORD PTR [rdx] + cvtdq2pd xmm0, xmm1 + movdqa XMMWORD PTR [r8], xmm0 + ret +op_cvtdq2pd_reg ENDP + +op_cvtdq2pd_mem PROC FRAME + .endprolog + cvtdq2pd xmm0, QWORD PTR [rdx] + movdqa XMMWORD PTR [r8], xmm0 + ret +op_cvtdq2pd_mem ENDP + +op_cvtdq2ps_reg PROC FRAME + .endprolog + movdqa xmm1, XMMWORD PTR [rdx] + cvtdq2ps xmm0, xmm1 + movdqa XMMWORD PTR [r8], xmm0 + ret +op_cvtdq2ps_reg ENDP + +op_cvtdq2ps_mem PROC FRAME + .endprolog + cvtdq2ps xmm0, XMMWORD PTR [rdx] + movdqa XMMWORD PTR [r8], xmm0 + ret +op_cvtdq2ps_mem ENDP + +op_cvtpd2dq_reg PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + movdqa xmm1, XMMWORD PTR [rdx] + cvtpd2dq xmm0, xmm1 + movdqa XMMWORD PTR [r8], xmm0 + ret +op_cvtpd2dq_reg ENDP + +op_cvtpd2dq_mem PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + cvtpd2dq xmm0, XMMWORD PTR [rdx] + movdqa XMMWORD PTR [r8], xmm0 + ret +op_cvtpd2dq_mem ENDP + +op_cvtpd2ps_reg PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + movdqa xmm1, XMMWORD PTR [rdx] + cvtpd2ps xmm0, xmm1 + movdqa XMMWORD PTR [r8], xmm0 + ret +op_cvtpd2ps_reg ENDP + +op_cvtpd2ps_mem PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + cvtpd2ps xmm0, XMMWORD PTR [rdx] + movdqa XMMWORD PTR [r8], xmm0 + ret +op_cvtpd2ps_mem ENDP + +op_cvtpi2pd_mem PROC FRAME + .endprolog + cvtpi2pd xmm0, QWORD PTR [rdx] + movdqa XMMWORD PTR [r8], xmm0 + ret +op_cvtpi2pd_mem ENDP + +op_cvtps2dq_reg PROC FRAME + .endprolog + movdqa xmm1, XMMWORD PTR [rdx] + cvtps2dq xmm0, xmm1 + movdqa XMMWORD PTR [r8], xmm0 + ret +op_cvtps2dq_reg ENDP + +op_cvtps2dq_mem PROC FRAME + .endprolog + cvtps2dq xmm0, XMMWORD PTR [rdx] + movdqa XMMWORD PTR [r8], xmm0 + ret +op_cvtps2dq_mem ENDP + +op_cvtps2pd_reg PROC FRAME + .endprolog + movdqa xmm1, XMMWORD PTR [rdx] + cvtps2pd xmm0, xmm1 + movdqa XMMWORD PTR [r8], xmm0 + ret +op_cvtps2pd_reg ENDP + +op_cvtps2pd_mem PROC FRAME + .endprolog + cvtps2pd xmm0, QWORD PTR [rdx] + movdqa XMMWORD PTR [r8], xmm0 + ret +op_cvtps2pd_mem ENDP + +op_cvttpd2dq_reg PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + movdqa xmm1, XMMWORD PTR [rdx] + cvttpd2dq xmm0, xmm1 + movdqa XMMWORD PTR [r8], xmm0 + ret +op_cvttpd2dq_reg ENDP + +op_cvttpd2dq_mem PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + cvttpd2dq xmm0, XMMWORD PTR [rdx] + movdqa XMMWORD PTR [r8], xmm0 + ret +op_cvttpd2dq_mem ENDP + +op_cvttps2dq_reg PROC FRAME + .endprolog + movdqa xmm1, XMMWORD PTR [rdx] + cvttps2dq xmm0, xmm1 + movdqa XMMWORD PTR [r8], xmm0 + ret +op_cvttps2dq_reg ENDP + +op_cvttps2dq_mem PROC FRAME + .endprolog + cvttps2dq xmm0, XMMWORD PTR [rdx] + movdqa XMMWORD PTR [r8], xmm0 + ret +op_cvttps2dq_mem ENDP + +; --- Aligned moves: load, reg copy and store --- + +op_movapd_ls PROC FRAME + .endprolog + movapd xmm0, XMMWORD PTR [rcx] + movapd XMMWORD PTR [r8], xmm0 + ret +op_movapd_ls ENDP + +op_movapd_reg PROC FRAME + .endprolog + movdqa xmm1, XMMWORD PTR [rcx] + movapd xmm0, xmm1 + movdqa XMMWORD PTR [r8], xmm0 + ret +op_movapd_reg ENDP + +op_movdqa_ls PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + movdqa XMMWORD PTR [r8], xmm0 + ret +op_movdqa_ls ENDP + +op_movdqa_reg PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + movdqa xmm1, xmm0 + movdqa XMMWORD PTR [r8], xmm1 + ret +op_movdqa_reg ENDP + +; --- Half-qword moves: m64 load merge and m64 store --- + +op_movhpd_load PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + movhpd xmm0, QWORD PTR [rdx] + movdqa XMMWORD PTR [r8], xmm0 + ret +op_movhpd_load ENDP + +op_movhpd_store PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + movhpd QWORD PTR [r8+8], xmm0 + ret +op_movhpd_store ENDP + +op_movlpd_load PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + movlpd xmm0, QWORD PTR [rdx] + movdqa XMMWORD PTR [r8], xmm0 + ret +op_movlpd_load ENDP + +op_movlpd_store PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + movlpd QWORD PTR [r8+8], xmm0 + ret +op_movlpd_store ENDP + +op_movhpd_load_plus1 PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + movhpd xmm0, QWORD PTR [rdx+1] + movdqa XMMWORD PTR [r8], xmm0 + ret +op_movhpd_load_plus1 ENDP + +op_movlpd_load_plus1 PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + movlpd xmm0, QWORD PTR [rdx+1] + movdqa XMMWORD PTR [r8], xmm0 + ret +op_movlpd_load_plus1 ENDP + +op_movhpd_store_plus1 PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + movhpd QWORD PTR [r8+9], xmm0 + ret +op_movhpd_store_plus1 ENDP + +op_movlpd_store_plus1 PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + movlpd QWORD PTR [r8+9], xmm0 + ret +op_movlpd_store_plus1 ENDP + +; --- Unaligned +1 m64 scalar and convert sources --- + +op_maxsd_mem_plus1 PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + maxsd xmm0, QWORD PTR [rdx+1] + movdqa XMMWORD PTR [r8], xmm0 + ret +op_maxsd_mem_plus1 ENDP + +op_cvtsd2si_mem_plus1 PROC FRAME + .endprolog + cvtsd2si eax, QWORD PTR [rdx+1] + mov DWORD PTR [r8], eax + ret +op_cvtsd2si_mem_plus1 ENDP + +; --- Non-temporal stores --- + +op_movntdq PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + movntdq XMMWORD PTR [r8], xmm0 + ret +op_movntdq ENDP + +op_movntpd PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + movntpd XMMWORD PTR [r8], xmm0 + ret +op_movntpd ENDP + +op_movnti32 PROC FRAME + .endprolog + mov eax, DWORD PTR [rdx] + movnti DWORD PTR [r8], eax + ret +op_movnti32 ENDP + +op_movnti64 PROC FRAME + .endprolog + mov rax, QWORD PTR [rdx] + movnti QWORD PTR [r8], rax + ret +op_movnti64 ENDP + +; --- Fences: serializing instructions with no observable state --- + +op_lfence PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + lfence + movdqa XMMWORD PTR [r8], xmm0 + ret +op_lfence ENDP + +op_mfence PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + mfence + movdqa XMMWORD PTR [r8], xmm0 + ret +op_mfence ENDP + +; --- Chained pipeline: masks, convert, merges, scalar ops and GPR bridge --- + +op_pipeline PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + movdqa xmm1, XMMWORD PTR [rdx] + movdqa xmm2, XMMWORD PTR [rdx+16] + cmppd xmm0, xmm1, 2 + cvtpd2ps xmm3, xmm0 + movhpd xmm3, QWORD PTR [rdx+24] + maxsd xmm3, xmm1 + minsd xmm3, xmm2 + sqrtsd xmm2, xmm3 + cvtsd2si eax, xmm3 + movdqa XMMWORD PTR [r8], xmm2 + mov DWORD PTR [r8+16], eax + ret +op_pipeline ENDP + +END diff --git a/tests/cpu/sse2_regs.def b/tests/cpu/sse2_regs.def new file mode 100644 index 00000000..0abc35b4 --- /dev/null +++ b/tests/cpu/sse2_regs.def @@ -0,0 +1,58 @@ +EXPORTS + op_cmppd_0 + op_cmppd_1 + op_cmppd_2 + op_cmppd_3 + op_cmppd_4 + op_cmppd_5 + op_cmppd_6 + op_cmppd_7 + op_cmppd_mem + op_maxsd_reg + op_maxsd_mem + op_minsd_reg + op_minsd_mem + op_sqrtsd_reg + op_sqrtsd_mem + op_cvtsd2si_r32_reg + op_cvtsd2si_r64_reg + op_cvtsd2si_r32_mem + op_cvtsd2si_r64_mem + op_cvtdq2pd_reg + op_cvtdq2pd_mem + op_cvtdq2ps_reg + op_cvtdq2ps_mem + op_cvtpd2dq_reg + op_cvtpd2dq_mem + op_cvtpd2ps_reg + op_cvtpd2ps_mem + op_cvtpi2pd_mem + op_cvtps2dq_reg + op_cvtps2dq_mem + op_cvtps2pd_reg + op_cvtps2pd_mem + op_cvttpd2dq_reg + op_cvttpd2dq_mem + op_cvttps2dq_reg + op_cvttps2dq_mem + op_movapd_ls + op_movapd_reg + op_movdqa_ls + op_movdqa_reg + op_movhpd_load + op_movhpd_store + op_movlpd_load + op_movlpd_store + op_movhpd_load_plus1 + op_movlpd_load_plus1 + op_movhpd_store_plus1 + op_movlpd_store_plus1 + op_maxsd_mem_plus1 + op_cvtsd2si_mem_plus1 + op_movntdq + op_movntpd + op_movnti32 + op_movnti64 + op_lfence + op_mfence + op_pipeline diff --git a/tests/cpu/sse2_regs_check.py b/tests/cpu/sse2_regs_check.py new file mode 100644 index 00000000..d12adc81 --- /dev/null +++ b/tests/cpu/sse2_regs_check.py @@ -0,0 +1,780 @@ +"""Differential checks, mutation controls and rejection controls for legacy SSE2 AOT.""" + +import ctypes +import math +from pathlib import Path +import random +import struct +import sys +from tempfile import TemporaryDirectory + +import pefile +from iced_x86 import Code, Encoder, Instruction, MemoryOperand, Register as R + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) +from cpu_sse2_aot import lift_code, translate +from cpu_leaf_aot import export_rva + +MASK32 = 0xFFFFFFFF +MASK64 = 0xFFFFFFFFFFFFFFFF +GUARD_PRE = bytes(0xA0 + (i % 16) for i in range(32)) +GUARD_POST = bytes(0xC0 + (i % 16) for i in range(32)) +FILL = b"\x5A" * 32 +INT32_INDEFINITE = 0x80000000 +INT64_INDEFINITE = 0x8000000000000000 +REAL_INDEFINITE = 0xFFF8000000000000 + +EXPORTS = ( + # cmppd predicates 0..7 (all eight covered) + aligned m128 source (9) + "op_cmppd_0", "op_cmppd_1", "op_cmppd_2", "op_cmppd_3", + "op_cmppd_4", "op_cmppd_5", "op_cmppd_6", "op_cmppd_7", "op_cmppd_mem", + # Scalar double ops (6) + "op_maxsd_reg", "op_maxsd_mem", "op_minsd_reg", "op_minsd_mem", + "op_sqrtsd_reg", "op_sqrtsd_mem", + # cvtsd2si r32/r64, reg/mem (4) + "op_cvtsd2si_r32_reg", "op_cvtsd2si_r64_reg", + "op_cvtsd2si_r32_mem", "op_cvtsd2si_r64_mem", + # Packed converts (17) + "op_cvtdq2pd_reg", "op_cvtdq2pd_mem", "op_cvtdq2ps_reg", "op_cvtdq2ps_mem", + "op_cvtpd2dq_reg", "op_cvtpd2dq_mem", "op_cvtpd2ps_reg", "op_cvtpd2ps_mem", + "op_cvtpi2pd_mem", + "op_cvtps2dq_reg", "op_cvtps2dq_mem", "op_cvtps2pd_reg", "op_cvtps2pd_mem", + "op_cvttpd2dq_reg", "op_cvttpd2dq_mem", + "op_cvttps2dq_reg", "op_cvttps2dq_mem", + # Aligned moves and half-qword merges (12), unaligned +1 loads/stores (4) + "op_movapd_ls", "op_movapd_reg", "op_movdqa_ls", "op_movdqa_reg", + "op_movhpd_load", "op_movhpd_store", "op_movlpd_load", "op_movlpd_store", + "op_movhpd_load_plus1", "op_movlpd_load_plus1", + "op_movhpd_store_plus1", "op_movlpd_store_plus1", + # Unaligned +1 m64 sources (2), non-temporal vector stores (2) + "op_maxsd_mem_plus1", "op_cvtsd2si_mem_plus1", + "op_movntdq", "op_movntpd", + # Non-temporal GPR stores (2) + "op_movnti32", "op_movnti64", + # Fences (2) + "op_lfence", "op_mfence", + # Chained pipeline (1) + "op_pipeline", +) + +# Exports whose cmppd predicate flips in the ALTER_IMM build. +ALTERED_PREDICATES = {"op_cmppd_1": (1, 5), "op_cmppd_3": (3, 7), "op_cmppd_6": (6, 2)} + + +# --- Independent Python ISA reference model --- + +def u64s(buf): + return struct.unpack("<2Q", buf) + + +def u64(buf): + return struct.unpack(" d64(b_bits) else b_bits + + +def ref_minsd(a_bits, b_bits): + return a_bits if d64(a_bits) < d64(b_bits) else b_bits + + +def ref_sqrtsd(b_bits): + v = d64(b_bits) + if v != v: + return b_bits | 0x0008000000000000 + if v < 0.0: + return REAL_INDEFINITE + return q64(math.sqrt(v)) + + +def cvt_i32(v, trunc): + """Round (default MXCSR) or truncate a double to i32 with the indefinite fallback.""" + if math.isnan(v) or math.isinf(v): + return INT32_INDEFINITE + r = math.trunc(v) if trunc else round(v) + return r & MASK32 if -0x80000000 <= r <= 0x7FFFFFFF else INT32_INDEFINITE + + +def ref_f64_to_i32(bits, trunc=False): + return cvt_i32(d64(bits), trunc) + + +def ref_f32_to_i32(bits, trunc=False): + return cvt_i32(f32(bits), trunc) + + +def ref_f64_to_i64(bits): + v = d64(bits) + if math.isnan(v) or math.isinf(v): + return INT64_INDEFINITE + r = round(v) + return r & MASK64 if -(1 << 63) <= r <= (1 << 63) - 1 else INT64_INDEFINITE + + +def ref_f64_to_f32(bits): + """Double to float bits: NaN narrows to a quiet float NaN keeping sign and top payload.""" + if (bits >> 52) & 0x7FF == 0x7FF and bits & 0xFFFFFFFFFFFFF: + return (((bits >> 63) & 1) << 31) | 0x7F800000 | (((bits & 0xFFFFFFFFFFFFF) >> 29) | 0x400000) + v = d64(bits) + try: + return struct.unpack("> 63) & 1) << 31) | 0x7F800000 + + +def ref_f32_to_f64(bits): + """Float to double bits: NaN widens to a quiet double NaN keeping sign and top payload.""" + if (bits >> 23) & 0xFF == 0xFF and bits & 0x7FFFFF: + return (((bits >> 31) & 1) << 63) | 0x7FF0000000000000 | ( + ((bits & 0x7FFFFF) << 29) | 0x0008000000000000) + return q64(f32(bits)) + + +def ref_cvtdq2pd(b): + lo, hi = si32(u32s(b[:16])[0]), si32(u32s(b[:16])[1]) + return struct.pack("<2d", float(lo), float(hi)) + + +def ref_cvtdq2ps(b): + return b"".join(struct.pack("(op_cvtsd2si32(xmm1.q[0]))", + "movnti_r9d": "store32(r8, static_cast(r9))", + "movnti_r10": "store64(r8, r10)", + "lfence_standalone": "atomic_signal_fence", + "mfence_standalone": "atomic_signal_fence", + "cmppd_mem_disp": "load128((rdx + 0x10ull))", + "movhpd_load_disp": ".q[1] = load64((rdx + 0x18ull))", + "movlpd_store_disp": "store64((r8 + 0x18ull), xmm0.q[0])", + "cmppd_self": "op_cmppd(xmm0, xmm0, 0x0u)", + } + for label, seq in alt_accept: + src, count = lift_code(label, 0x1000, encode_seq(*seq)) + assert f"lifted_{label}" in src and count == len(seq), (label, count) + if alt_expected[label] not in src: + raise AssertionError( + f"alternate encoding {label} lowered without the expected statement " + f"{alt_expected[label]!r}") + + # 1) The 36 SSE2-group forms reserved for sibling translators must all reject. + reserved_cases = [ + ("addpd", Instruction.create_reg_reg(Code.ADDPD_XMM_XMMM128, R.XMM0, R.XMM1)), + ("addsd", Instruction.create_reg_reg(Code.ADDSD_XMM_XMMM64, R.XMM0, R.XMM1)), + ("andnpd", Instruction.create_reg_reg(Code.ANDNPD_XMM_XMMM128, R.XMM0, R.XMM1)), + ("andpd", Instruction.create_reg_reg(Code.ANDPD_XMM_XMMM128, R.XMM0, R.XMM1)), + ("comisd", Instruction.create_reg_reg(Code.COMISD_XMM_XMMM64, R.XMM0, R.XMM1)), + ("cvtsi2sd", Instruction.create_reg_reg(Code.CVTSI2SD_XMM_RM32, R.XMM0, R.EAX)), + ("cvttsd2si", Instruction.create_reg_reg(Code.CVTTSD2SI_R32_XMMM64, R.EAX, R.XMM1)), + ("cvtss2sd", Instruction.create_reg_reg(Code.CVTSS2SD_XMM_XMMM32, R.XMM0, R.XMM1)), + ("cvtsd2ss", Instruction.create_reg_reg(Code.CVTSD2SS_XMM_XMMM64, R.XMM0, R.XMM1)), + ("divpd", Instruction.create_reg_reg(Code.DIVPD_XMM_XMMM128, R.XMM0, R.XMM1)), + ("divsd", Instruction.create_reg_reg(Code.DIVSD_XMM_XMMM64, R.XMM0, R.XMM1)), + ("maxpd", Instruction.create_reg_reg(Code.MAXPD_XMM_XMMM128, R.XMM0, R.XMM1)), + ("minpd", Instruction.create_reg_reg(Code.MINPD_XMM_XMMM128, R.XMM0, R.XMM1)), + ("movdqu", Instruction.create_reg_reg(Code.MOVDQU_XMM_XMMM128, R.XMM0, R.XMM1)), + ("movmskpd", Instruction.create_reg_reg(Code.MOVMSKPD_R32_XMM, R.EAX, R.XMM1)), + ("movupd", Instruction.create_reg_reg(Code.MOVUPD_XMM_XMMM128, R.XMM0, R.XMM1)), + ("mulpd", Instruction.create_reg_reg(Code.MULPD_XMM_XMMM128, R.XMM0, R.XMM1)), + ("mulsd", Instruction.create_reg_reg(Code.MULSD_XMM_XMMM64, R.XMM0, R.XMM1)), + ("orpd", Instruction.create_reg_reg(Code.ORPD_XMM_XMMM128, R.XMM0, R.XMM1)), + ("pmuludq", Instruction.create_reg_reg(Code.PMULUDQ_XMM_XMMM128, R.XMM0, R.XMM1)), + ("pshufd", Instruction.create_reg_reg_u32(Code.PSHUFD_XMM_XMMM128_IMM8, R.XMM0, R.XMM1, 0x1B)), + ("pshufhw", Instruction.create_reg_reg_u32(Code.PSHUFHW_XMM_XMMM128_IMM8, R.XMM0, R.XMM1, 0x1B)), + ("pshuflw", Instruction.create_reg_reg_u32(Code.PSHUFLW_XMM_XMMM128_IMM8, R.XMM0, R.XMM1, 0x1B)), + ("pslldq", Instruction.create_reg_u32(Code.PSLLDQ_XMM_IMM8, R.XMM0, 4)), + ("psrldq", Instruction.create_reg_u32(Code.PSRLDQ_XMM_IMM8, R.XMM0, 4)), + ("psubq", Instruction.create_reg_reg(Code.PSUBQ_XMM_XMMM128, R.XMM0, R.XMM1)), + ("punpckhqdq", Instruction.create_reg_reg(Code.PUNPCKHQDQ_XMM_XMMM128, R.XMM0, R.XMM1)), + ("punpcklqdq", Instruction.create_reg_reg(Code.PUNPCKLQDQ_XMM_XMMM128, R.XMM0, R.XMM1)), + ("shufpd", Instruction.create_reg_reg_u32(Code.SHUFPD_XMM_XMMM128_IMM8, R.XMM0, R.XMM1, 1)), + ("sqrtpd", Instruction.create_reg_reg(Code.SQRTPD_XMM_XMMM128, R.XMM0, R.XMM1)), + ("subpd", Instruction.create_reg_reg(Code.SUBPD_XMM_XMMM128, R.XMM0, R.XMM1)), + ("subsd", Instruction.create_reg_reg(Code.SUBSD_XMM_XMMM64, R.XMM0, R.XMM1)), + ("ucomisd", Instruction.create_reg_reg(Code.UCOMISD_XMM_XMMM64, R.XMM0, R.XMM1)), + ("unpckhpd", Instruction.create_reg_reg(Code.UNPCKHPD_XMM_XMMM128, R.XMM0, R.XMM1)), + ("unpcklpd", Instruction.create_reg_reg(Code.UNPCKLPD_XMM_XMMM128, R.XMM0, R.XMM1)), + ("xorpd", Instruction.create_reg_reg(Code.XORPD_XMM_XMMM128, R.XMM0, R.XMM1)), + ] + + # 2) ABI-infeasible task forms: MMX register operands and the implicit-RDI store. + abi_infeasible_cases = [ + ("cvtpd2pi_mm", (Instruction.create_reg_reg( + Code.CVTPD2PI_MM_XMMM128, R.MM0, R.XMM1),), "MMX register operand outside the leaf ABI"), + ("cvtpd2pi_mm_mem", (Instruction.create_reg_mem( + Code.CVTPD2PI_MM_XMMM128, R.MM0, MemoryOperand(R.RCX)),), "MMX register operand outside the leaf ABI"), + ("cvttpd2pi_mm", (Instruction.create_reg_reg( + Code.CVTTPD2PI_MM_XMMM128, R.MM0, R.XMM1),), "MMX register operand outside the leaf ABI"), + ("movdq2q_mm", (Instruction.create_reg_reg( + Code.MOVDQ2Q_MM_XMM, R.MM0, R.XMM1),), "MMX register operand outside the leaf ABI"), + ("movq2dq_mm", (Instruction.create_reg_reg( + Code.MOVQ2DQ_XMM_MM, R.XMM0, R.MM1),), "MMX register operand outside the leaf ABI"), + ("cvtpi2pd_mm_src", (Instruction.create_reg_reg( + Code.CVTPI2PD_XMM_MMM64, R.XMM0, R.MM1),), "MMX register operand outside the leaf ABI"), + ] + + # 3) cmppd immediates above 7 are a reserved encoding and reject by policy. + cmppd_imm_case = ("cmppd_imm8", (ld_xmm0, Instruction.create_reg_reg_u32( + Code.CMPPD_XMM_XMMM128_IMM8, R.XMM0, R.XMM1, 0x1B), ret_ins), "unsupported cmppd predicate") + + # 4) VEX/EVEX encodings of implemented forms reject as non-legacy. + nonlegacy_cases = [ + ("vaddpd_vex", (ld_xmm1, ld_xmm2, Instruction.create_reg_reg_reg( + Code.VEX_VADDPD_XMM_XMM_XMMM128, R.XMM0, R.XMM1, R.XMM2), ret_ins), "non-legacy encoding"), + ("vmaxsd_vex", (ld_xmm1, ld_xmm2, Instruction.create_reg_reg_reg( + Code.VEX_VMAXSD_XMM_XMM_XMMM64, R.XMM0, R.XMM1, R.XMM2), ret_ins), "non-legacy encoding"), + ("vmovapd_vex", (Instruction.create_reg_mem( + Code.VEX_VMOVAPD_XMM_XMMM128, R.XMM0, MemoryOperand(R.RCX)), ret_ins), "non-legacy encoding"), + ("vmovapd_evex", (Instruction.create_reg_mem( + Code.EVEX_VMOVAPD_XMM_K1Z_XMMM128, R.XMM0, MemoryOperand(R.RCX)), ret_ins), "non-legacy encoding"), + ] + + # 5) Prefixes, register-file policy, state tracking and addressing violations. + seg_load = Instruction.create_reg_mem(Code.MOVDQA_XMM_XMMM128, R.XMM0, MemoryOperand(R.RCX)) + seg_load.segment_prefix = R.FS + other_cases = [ + ("nonvolatile_xmm6", (Instruction.create_reg_mem( + Code.MOVDQA_XMM_XMMM128, R.XMM6, MemoryOperand(R.RCX)), ret_ins), "nonvolatile vector register"), + ("nonvolatile_xmm15", (Instruction.create_reg_reg( + Code.MAXSD_XMM_XMMM64, R.XMM15, R.XMM1), ret_ins), "nonvolatile vector register"), + ("nonvolatile_gpr_ebx", (ld_xmm0, Instruction.create_reg_reg( + Code.CVTSD2SI_R32_XMMM64, R.EBX, R.XMM0), ret_ins), "nonvolatile GPR"), + ("arg_gpr_ecx", (ld_xmm0, Instruction.create_reg_reg( + Code.CVTSD2SI_R32_XMMM64, R.ECX, R.XMM0), ret_ins), "unsupported argument GPR operand"), + ("undefined_xmm3", (ld_xmm0, Instruction.create_reg_reg( + Code.MAXSD_XMM_XMMM64, R.XMM0, R.XMM3), ret_ins), "undefined vector register xmm3"), + ("undefined_dst_merge", (Instruction.create_reg_mem( + Code.MOVHPD_XMM_M64, R.XMM0, MemoryOperand(R.RDX)), ret_ins), "undefined vector register xmm0"), + ("undefined_gpr", (Instruction.create_mem_reg( + Code.MOVNTI_M32_R32, MemoryOperand(R.R8), R.EAX), ret_ins), "undefined GPR rax"), + ("mov_reg_to_reg", (Instruction.create_reg_reg( + Code.MOV_R64_RM64, R.RAX, R.RCX), ret_ins), "unsupported mov instruction"), + ("rip_rel_mem", (Instruction.create_reg_mem( + Code.MOVDQA_XMM_XMMM128, R.XMM0, MemoryOperand(R.RIP, displ=0x1010, displ_size=1)), ret_ins), + "unsupported memory operand"), + ("rsp_mem", (Instruction.create_reg_mem( + Code.MOVDQA_XMM_XMMM128, R.XMM0, MemoryOperand(R.RSP)), ret_ins), + "unsupported memory operand"), + ("addr32_mem", (Instruction.create_reg_mem( + Code.MOVDQA_XMM_XMMM128, R.XMM0, MemoryOperand(R.ECX)), ret_ins), + "unsupported memory operand"), + ("indexed_mem", (Instruction.create_reg_mem( + Code.MOVDQA_XMM_XMMM128, R.XMM0, MemoryOperand(R.RCX, R.RDX, 4)), ret_ins), + "unsupported memory operand"), + ("non_arg_base_rax", (Instruction.create_reg_mem( + Code.MOVDQA_XMM_XMMM128, R.XMM0, MemoryOperand(R.RAX)), ret_ins), + "unsupported memory operand"), + ("segment_prefix", (seg_load, ret_ins), "unsupported instruction prefix"), + ("missing_ret", (ld_xmm0,), "missing terminal ret"), + ("after_ret", (ret_ins, ld_xmm0), "unreachable instruction after ret"), + ] + # Raw-byte controls: iced reports lock on cmpxchg and rep on movsb, and cannot + # encode maskmovdqu's implicit DS:rdi operand (66 0F F7 /r emits it raw). + raw_prefix_cases = [ + ("lock_cmpxchg", bytes.fromhex("f00fb109") + encode_seq(ret_ins), "unsupported instruction prefix"), + ("rep_movsb", bytes.fromhex("f3a4") + encode_seq(ret_ins), "unsupported instruction prefix"), + ("maskmovdqu", bytes.fromhex("660ff7c8") + encode_seq(ret_ins), + "implicit RDI memory operand outside the leaf ABI"), + ] + + all_unit = ( + [(lbl, (ld_xmm0, ld_xmm1, ins, ret_ins), "unsupported instruction") + for lbl, ins in reserved_cases] + + [(lbl, seq + (ret_ins,), reason) for lbl, seq, reason in abi_infeasible_cases] + + [cmppd_imm_case] + + nonlegacy_cases + + other_cases + ) + + for label, seq, expected_reason in all_unit: + raw = encode_seq(*seq) + try: + lift_code(label, 0x1000, raw) + except ValueError as exc: + if expected_reason not in str(exc): + raise AssertionError(f"{label}: expected {expected_reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator unexpectedly accepted rejected control") + + for label, raw, expected_reason in raw_prefix_cases: + try: + lift_code(label, 0x1000, raw) + except ValueError as exc: + if expected_reason not in str(exc): + raise AssertionError(f"{label}: expected {expected_reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator unexpectedly accepted rejected control") + + # End-to-end PE patching controls on a copy of the built native DLL. + pe_bytes = Path(original_path).read_bytes() + with pefile.PE(data=pe_bytes, fast_load=True) as pe: + entry = export_rva(pe, "op_pipeline") + file_off = pe.get_offset_from_rva(entry) + pdata = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] + records = pe.get_data(pdata.VirtualAddress, pdata.Size) + rec_idx = next(i for i in range(0, len(records), 12) + if struct.unpack_from(" max_len: + raise AssertionError(f"{label}: patch ({len(patch)} bytes) exceeds op_pipeline ({max_len})") + damaged = bytearray(pe_bytes) + damaged[file_off:file_off + len(patch)] = patch + struct.pack_into(" +#include +#include +#include + +using word = std::uint64_t; + +struct Vec128 { + std::uint64_t q[2]; +}; + +static std::uint32_t load32(word address) { + std::uint32_t val = 0u; + std::memcpy(&val, reinterpret_cast(address), 4); + return val; +} + +static std::uint64_t load64(word address) { + std::uint64_t val = 0ull; + std::memcpy(&val, reinterpret_cast(address), 8); + return val; +} + +static void store32(word address, std::uint32_t val) { + std::memcpy(reinterpret_cast(address), &val, 4); +} + +static void store64(word address, std::uint64_t val) { + std::memcpy(reinterpret_cast(address), &val, 8); +} + +static Vec128 load128(word address) { + Vec128 v{}; + std::memcpy(v.q, reinterpret_cast(address), 16); + return v; +} + +static void store128(word address, const Vec128& v) { + std::memcpy(reinterpret_cast(address), v.q, 16); +} + +static double q_as_double(std::uint64_t bits) { + double v; + std::memcpy(&v, &bits, 8); + return v; +} + +static std::uint64_t double_as_q(double v) { + std::uint64_t bits; + std::memcpy(&bits, &v, 8); + return bits; +} + +static float d_as_float(std::uint32_t bits) { + float v; + std::memcpy(&v, &bits, 4); + return v; +} + +static std::uint32_t float_as_d(float v) { + std::uint32_t bits; + std::memcpy(&bits, &v, 4); + return bits; +} + +static std::uint32_t lane32(const Vec128& v, unsigned i) { + return static_cast(v.q[i >> 1] >> ((i & 1u) * 32u)); +} + +static void set_lane32(Vec128& v, unsigned i, std::uint32_t val) { + const unsigned shift = (i & 1u) * 32u; + v.q[i >> 1] = (v.q[i >> 1] & ~(0xffffffffull << shift)) | (static_cast(val) << shift); +} + +static std::int32_t s32(std::uint32_t v) { + std::int32_t out; + std::memcpy(&out, &v, 4); + return out; +} + +// CMPPD predicates 0..7: EQ_OQ, LT_OS, LE_OS, UNORD_Q, NEQ_UQ, NLT_US, NLE_US, ORD_Q. +static Vec128 op_cmppd(const Vec128& a, const Vec128& b, std::uint8_t imm8) { + Vec128 out{}; + for (unsigned i = 0; i < 2u; ++i) { + const double x = q_as_double(a.q[i]); + const double y = q_as_double(b.q[i]); + bool res; + switch (imm8 & 7u) { + case 0u: res = (x == y); break; + case 1u: res = (x < y); break; + case 2u: res = (x <= y); break; + case 3u: res = (x != x) || (y != y); break; + case 4u: res = !(x == y); break; + case 5u: res = !(x < y); break; + case 6u: res = !(x <= y); break; + default: res = (x == x) && (y == y); break; + } + out.q[i] = res ? 0xffffffffffffffffull : 0ull; + } + return out; +} + +// MAXSD/MINSD return src2 on ties, unordered inputs and equal values. +static std::uint64_t op_maxsd_q(std::uint64_t a, std::uint64_t b) { + return q_as_double(a) > q_as_double(b) ? a : b; +} + +static std::uint64_t op_minsd_q(std::uint64_t a, std::uint64_t b) { + return q_as_double(a) < q_as_double(b) ? a : b; +} + +// SQRTSD keeps the NaN payload (quieted) and yields the real-indefinite QNaN +// for negative nonzero inputs, matching the host instruction. +static std::uint64_t op_sqrtsd_q(std::uint64_t b) { + const double v = q_as_double(b); + if (v != v) { + return b | 0x0008000000000000ull; + } + if (v < 0.0) { + return 0xfff8000000000000ull; + } + return double_as_q(std::sqrt(v)); +} + +// MXCSR rounding under the default round-to-nearest-even mode. NaN, infinity +// and out-of-range rounded results return the integer indefinite value. +static std::int32_t cvt_round_i32(double v) { + const double r = std::nearbyint(v); + return (r >= -2147483648.0 && r <= 2147483647.0) + ? static_cast(r) + : static_cast(0x80000000u); +} + +static std::int32_t cvt_trunc_i32(double v) { + const double r = std::trunc(v); + return (r >= -2147483648.0 && r <= 2147483647.0) + ? static_cast(r) + : static_cast(0x80000000u); +} + +static std::uint32_t op_cvtsd2si32(std::uint64_t bits) { + return static_cast(cvt_round_i32(q_as_double(bits))); +} + +static std::uint64_t op_cvtsd2si64(std::uint64_t bits) { + const double r = std::nearbyint(q_as_double(bits)); + const bool valid = (r >= -0x1p63 && r < 0x1p63); + return static_cast(valid ? static_cast(r) + : static_cast(0x8000000000000000ull)); +} + +static Vec128 op_cvtpd2dq(const Vec128& a) { + const std::uint32_t lo = static_cast(cvt_round_i32(q_as_double(a.q[0]))); + const std::uint32_t hi = static_cast(cvt_round_i32(q_as_double(a.q[1]))); + return {{static_cast(lo) | (static_cast(hi) << 32), 0ull}}; +} + +static Vec128 op_cvttpd2dq(const Vec128& a) { + const std::uint32_t lo = static_cast(cvt_trunc_i32(q_as_double(a.q[0]))); + const std::uint32_t hi = static_cast(cvt_trunc_i32(q_as_double(a.q[1]))); + return {{static_cast(lo) | (static_cast(hi) << 32), 0ull}}; +} + +static Vec128 op_cvtpd2ps(const Vec128& a) { + const std::uint32_t lo = float_as_d(static_cast(q_as_double(a.q[0]))); + const std::uint32_t hi = float_as_d(static_cast(q_as_double(a.q[1]))); + return {{static_cast(lo) | (static_cast(hi) << 32), 0ull}}; +} + +static Vec128 op_cvtdq2ps(const Vec128& a) { + Vec128 out{}; + for (unsigned i = 0; i < 4u; ++i) { + set_lane32(out, i, float_as_d(static_cast(s32(lane32(a, i))))); + } + return out; +} + +static Vec128 op_cvtps2dq(const Vec128& a) { + Vec128 out{}; + for (unsigned i = 0; i < 4u; ++i) { + set_lane32(out, i, static_cast( + cvt_round_i32(static_cast(d_as_float(lane32(a, i)))))); + } + return out; +} + +static Vec128 op_cvttps2dq(const Vec128& a) { + Vec128 out{}; + for (unsigned i = 0; i < 4u; ++i) { + set_lane32(out, i, static_cast( + cvt_trunc_i32(static_cast(d_as_float(lane32(a, i)))))); + } + return out; +} + +static Vec128 op_cvtdq2pd(std::uint64_t a) { + const std::int32_t lo = s32(static_cast(a & 0xffffffffull)); + const std::int32_t hi = s32(static_cast(a >> 32)); + return {{double_as_q(static_cast(lo)), double_as_q(static_cast(hi))}}; +} + +static Vec128 op_cvtps2pd(std::uint64_t a) { + const std::uint32_t lo = static_cast(a & 0xffffffffull); + const std::uint32_t hi = static_cast(a >> 32); + return {{double_as_q(static_cast(d_as_float(lo))), + double_as_q(static_cast(d_as_float(hi)))}}; +} + +static Vec128 op_cvtpi2pd(std::uint64_t a) { + return op_cvtdq2pd(a); +} +""" + + +def vec_index(register, ins): + """Map XMM0..XMM5 to an index, rejecting all others.""" + if register in VOLATILE_XMM: + return VOLATILE_XMM[register] + if register in NONVOLATILE_VEC: + raise ValueError(f"nonvolatile vector register {register} at RVA {ins.ip:#x}: {ins}") + raise ValueError(f"unsupported vector register {register} at RVA {ins.ip:#x}: {ins}") + + +def gpr_scratch(register, ins): + """Map volatile scratch GPR32/GPR64 (rax, r9, r10, r11) to (name, is_64), rejecting others.""" + if register in SCRATCH_GPR32: + return SCRATCH_GPR32[register], False + if register in SCRATCH_GPR64: + return SCRATCH_GPR64[register], True + if register in NONVOLATILE_GPR: + raise ValueError(f"nonvolatile GPR {register} at RVA {ins.ip:#x}: {ins}") + if register in ARGUMENT_GPRS: + raise ValueError(f"unsupported argument GPR operand {register} at RVA {ins.ip:#x}: {ins}") + raise ValueError(f"unsupported GPR {register} at RVA {ins.ip:#x}: {ins}") + + +def flat_address(ins): + """Lower a flat [base + disp] pointer operand rooted in an argument GPR64.""" + base = ins.memory_base + if (ins.is_ip_rel_memory_operand or base in (R.NONE, R.RIP, R.EIP, R.RSP, R.ESP) + or ins.memory_index != R.NONE or not RegisterExt.is_gpr64(base) + or base not in ARGUMENTS): + raise ValueError(f"unsupported memory operand at RVA {ins.ip:#x}: {ins}") + disp = ins.memory_displacement & ((1 << 64) - 1) + name = ARGUMENTS[base] + return f"({name} + {disp:#x}ull)" if disp else name + + +def lift_code(name, start, raw): + """Decode and lift one bounded straight-line legacy SSE2 leaf function.""" + instructions = list(Decoder(64, raw, ip=start)) + if not instructions or instructions[-1].next_ip != start + len(raw): + raise ValueError(f"truncated instruction stream in {name} at RVA {start:#x}") + if any(ins.is_invalid for ins in instructions): + bad = next(ins for ins in instructions if ins.is_invalid) + raise ValueError(f"invalid instruction at RVA {bad.ip:#x}") + + used = set() + defined = set() + used_gpr = set() + defined_gpr = set() + statements = [] + returned = False + + def read_vec(op_index, ins): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register operand {op_index} at RVA {ins.ip:#x}: {ins}") + register = ins.op_register(op_index) + if register in MM_REGISTERS: + raise ValueError(f"MMX register operand outside the leaf ABI at RVA {ins.ip:#x}: {ins}") + idx = vec_index(register, ins) + if idx not in defined: + raise ValueError(f"undefined vector register xmm{idx} at RVA {ins.ip:#x}: {ins}") + used.add(idx) + return f"xmm{idx}" + + def write_vec(op_index, ins): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register destination at RVA {ins.ip:#x}: {ins}") + register = ins.op_register(op_index) + if register in MM_REGISTERS: + raise ValueError(f"MMX register operand outside the leaf ABI at RVA {ins.ip:#x}: {ins}") + idx = vec_index(register, ins) + used.add(idx) + return idx, f"xmm{idx}" + + def read_gpr(op_index, ins): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected GPR operand {op_index} at RVA {ins.ip:#x}: {ins}") + reg_name, is64 = gpr_scratch(ins.op_register(op_index), ins) + if reg_name not in defined_gpr: + raise ValueError(f"undefined GPR {reg_name} at RVA {ins.ip:#x}: {ins}") + used_gpr.add(reg_name) + return reg_name, is64 + + def write_gpr(op_index, ins): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected GPR destination at RVA {ins.ip:#x}: {ins}") + reg_name, is64 = gpr_scratch(ins.op_register(op_index), ins) + used_gpr.add(reg_name) + return reg_name, is64 + + def vec_src128(op_index, ins): + """Source of a full-width vector operand: xmm name or m128 load expression.""" + if ins.op_kind(op_index) == OpKind.MEMORY: + return f"load128({flat_address(ins)})" + return read_vec(op_index, ins) + + def vec_src64(op_index, ins): + """Source of a low-qword operand: xmm.q[0] or m64 load64 expression.""" + if ins.op_kind(op_index) == OpKind.MEMORY: + return f"load64({flat_address(ins)})" + return f"{read_vec(op_index, ins)}.q[0]" + + for ins in instructions: + if returned: + raise ValueError(f"unreachable instruction after ret at RVA {ins.ip:#x}: {ins}") + if ins.has_lock_prefix or ins.has_rep_prefix or ins.has_repne_prefix or ins.has_segment_prefix: + raise ValueError(f"unsupported instruction prefix at RVA {ins.ip:#x}: {ins}") + if ins.op_code().encoding != EncodingKind.LEGACY: + raise ValueError(f"non-legacy encoding at RVA {ins.ip:#x}: {ins}") + if ins.code in MMX_OPERAND_CODES: + raise ValueError(f"MMX register operand outside the leaf ABI at RVA {ins.ip:#x}: {ins}") + if ins.code in IMPLICIT_ADDRESS_CODES: + raise ValueError(f"implicit RDI memory operand outside the leaf ABI at RVA {ins.ip:#x}: {ins}") + if ins.code not in ALLOWED_CODES: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if ins.code == Code.RETNQ: + statements.append("return;") + returned = True + elif ins.code in (Code.LFENCE, Code.MFENCE): + # Serializing instruction with no observable register state; model it as a + # compiler barrier so the lifted code keeps the ordering contract. + statements.append("std::atomic_signal_fence(std::memory_order_seq_cst);") + elif ins.code in (Code.MOV_R32_RM32, Code.MOV_R64_RM64): + if ins.op0_kind != OpKind.REGISTER or ins.op1_kind != OpKind.MEMORY: + raise ValueError(f"unsupported mov instruction at RVA {ins.ip:#x}: {ins}") + reg_name, is64 = write_gpr(0, ins) + addr = flat_address(ins) + if is64: + statements.append(f"{reg_name} = load64({addr});") + else: + statements.append(f"{reg_name} = static_cast(load32({addr}));") + defined_gpr.add(reg_name) + elif ins.code in (Code.MOV_RM32_R32, Code.MOV_RM64_R64): + if ins.op0_kind != OpKind.MEMORY or ins.op1_kind != OpKind.REGISTER: + raise ValueError(f"unsupported mov instruction at RVA {ins.ip:#x}: {ins}") + reg_name, is64 = read_gpr(1, ins) + addr = flat_address(ins) + if is64: + statements.append(f"store64({addr}, {reg_name});") + else: + statements.append(f"store32({addr}, static_cast({reg_name}));") + elif ins.code in (Code.MOVNTI_M32_R32, Code.MOVNTI_M64_R64): + reg_name, is64 = read_gpr(1, ins) + addr = flat_address(ins) + if ins.code == Code.MOVNTI_M64_R64: + if not is64: + raise ValueError(f"movnti width mismatch at RVA {ins.ip:#x}: {ins}") + statements.append(f"store64({addr}, {reg_name});") + else: + statements.append(f"store32({addr}, static_cast({reg_name}));") + elif ins.code == Code.CMPPD_XMM_XMMM128_IMM8: + imm = ins.immediate8 & 0xff + if imm > 7: + raise ValueError(f"unsupported cmppd predicate {imm:#x} at RVA {ins.ip:#x}: {ins}") + dst = read_vec(0, ins) + src = vec_src128(1, ins) + dst_idx, dst_name = write_vec(0, ins) + statements.append(f"{dst_name} = op_cmppd({dst}, {src}, {imm:#x}u);") + defined.add(dst_idx) + elif ins.code in PACKED_CVT_HELPERS: + src = vec_src128(1, ins) + dst_idx, dst_name = write_vec(0, ins) + statements.append(f"{dst_name} = {PACKED_CVT_HELPERS[ins.code]}({src});") + defined.add(dst_idx) + elif ins.code in QWORD_CVT_HELPERS: + src = vec_src64(1, ins) + dst_idx, dst_name = write_vec(0, ins) + statements.append(f"{dst_name} = {QWORD_CVT_HELPERS[ins.code]}({src});") + defined.add(dst_idx) + elif ins.code == Code.CVTPI2PD_XMM_MMM64: + if ins.op1_kind != OpKind.MEMORY: + raise ValueError(f"MMX register operand outside the leaf ABI at RVA {ins.ip:#x}: {ins}") + dst_idx, dst_name = write_vec(0, ins) + statements.append(f"{dst_name} = op_cvtpi2pd(load64({flat_address(ins)}));") + defined.add(dst_idx) + elif ins.code in (Code.CVTSD2SI_R32_XMMM64, Code.CVTSD2SI_R64_XMMM64): + src = vec_src64(1, ins) + reg_name, is64 = write_gpr(0, ins) + if ins.code == Code.CVTSD2SI_R64_XMMM64: + if not is64: + raise ValueError(f"cvtsd2si width mismatch at RVA {ins.ip:#x}: {ins}") + statements.append(f"{reg_name} = op_cvtsd2si64({src});") + else: + if is64: + raise ValueError(f"cvtsd2si width mismatch at RVA {ins.ip:#x}: {ins}") + statements.append(f"{reg_name} = static_cast(op_cvtsd2si32({src}));") + defined_gpr.add(reg_name) + elif ins.code in SCALAR_MERGE_HELPERS: + dst = read_vec(0, ins) + src = vec_src64(1, ins) + dst_idx, dst_name = write_vec(0, ins) + statements.append(f"{dst_name}.q[0] = {SCALAR_MERGE_HELPERS[ins.code]}({dst}.q[0], {src});") + defined.add(dst_idx) + elif ins.code == Code.SQRTSD_XMM_XMMM64: + dst = read_vec(0, ins) + src = vec_src64(1, ins) + dst_idx, dst_name = write_vec(0, ins) + statements.append(f"{dst_name}.q[0] = op_sqrtsd_q({src});") + defined.add(dst_idx) + elif ins.code in (Code.MOVAPD_XMM_XMMM128, Code.MOVDQA_XMM_XMMM128): + if ins.op1_kind == OpKind.MEMORY: + dst_idx, dst_name = write_vec(0, ins) + statements.append(f"{dst_name} = load128({flat_address(ins)});") + else: + src = read_vec(1, ins) + dst_idx, dst_name = write_vec(0, ins) + statements.append(f"{dst_name} = {src};") + defined.add(dst_idx) + elif ins.code in (Code.MOVAPD_XMMM128_XMM, Code.MOVDQA_XMMM128_XMM): + src = read_vec(1, ins) + statements.append(f"store128({flat_address(ins)}, {src});") + elif ins.code in (Code.MOVHPD_XMM_M64, Code.MOVLPD_XMM_M64): + dst = read_vec(0, ins) + dst_idx, dst_name = write_vec(0, ins) + q_idx = 1 if ins.code == Code.MOVHPD_XMM_M64 else 0 + statements.append(f"{dst_name}.q[{q_idx}] = load64({flat_address(ins)});") + defined.add(dst_idx) + elif ins.code in (Code.MOVHPD_M64_XMM, Code.MOVLPD_M64_XMM): + src = read_vec(1, ins) + q_idx = 1 if ins.code == Code.MOVHPD_M64_XMM else 0 + statements.append(f"store64({flat_address(ins)}, {src}.q[{q_idx}]);") + elif ins.code in (Code.MOVNTDQ_M128_XMM, Code.MOVNTPD_M128_XMM): + src = read_vec(1, ins) + statements.append(f"store128({flat_address(ins)}, {src});") + else: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if not returned: + raise ValueError(f"missing terminal ret in {name} at RVA {start + len(raw):#x}") + + decls = [f" Vec128 xmm{idx}{{}};" for idx in sorted(used)] + decls.extend(f" word {reg_name} = 0ull;" for reg_name in sorted(used_gpr)) + body = [f" {stmt}" for stmt in statements] + lines = [ + f'extern "C" __declspec(dllexport) void lifted_{name}(word rcx, word rdx, word r8) {{', + " (void)rcx; (void)rdx; (void)r8;", + *decls, + *body, + "}", + ] + return "\n".join(lines), len(instructions) + + +def lift(pe, name): + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + source, count = lift_code(name, entry, raw) + return source, entry, count + + +def translate_pe(pe, names): + if pe.FILE_HEADER.Machine != 0x8664 or pe.OPTIONAL_HEADER.Magic != 0x20B: + raise ValueError("expected AMD64 PE32+") + lifted = [lift(pe, name) for name in names] + source = PRELUDE + "\n".join(f"\n{text}" for text, _, _ in lifted) + "\n" + meta = [(name, entry, count) for name, (_, entry, count) in zip(names, lifted)] + return source, meta + + +def translate(image, names): + with pefile.PE(str(image), fast_load=True) as pe: + return translate_pe(pe, names) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("image", type=Path) + parser.add_argument("exports", help="comma-separated export names") + parser.add_argument("output", type=Path) + args = parser.parse_args() + try: + source, meta = translate(args.image, args.exports.split(",")) + args.output.write_text(source, encoding="utf-8") + for name, entry, count in meta: + print(f"{name} at RVA {entry:#x}: {count} instructions") + except (ValueError, OSError, pefile.PEFormatError) as error: + parser.exit(1, f"{error}\n") diff --git a/tools/form_coverage.py b/tools/form_coverage.py index 67926612..e883cac7 100644 --- a/tools/form_coverage.py +++ b/tools/form_coverage.py @@ -71,6 +71,7 @@ "avx2_regs": "cpu_aot_avx2_regs", "avx_int_regs": "cpu_aot_avx_int_regs", "avx_move_regs": "cpu_aot_avx_move_regs", + "sse2_regs": "cpu_aot_sse2_regs", "call_pair": "cpu_aot_call_pair", "movbe": "cpu_aot_movbe", "bmi1": "cpu_aot_bmi1",