Skip to content

[AUTOMATED] Give the MSVC x87 math intrinsics their operands - #1561

Merged
mahaloz merged 20 commits into
Noelo-Lab:mainfrom
borancar:x87-intrinsics
Nov 13, 2026
Merged

mahaloz merged 20 commits into
Noelo-Lab:mainfrom
borancar:x87-intrinsics

Conversation

@borancar

@borancar borancar commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

On x86-32, MSVC compiles sin(x), cos(x), sqrt(x), atan2(y, x), pow, fmod and their siblings into a call to a CRT intrinsic (__CIsin, __CIatan2, ...) that takes its operand in ST0 (two operands: ST1, ST0) and returns there. No x86win.cspec model has an ST0 input, so the call gets no argument and the expression that computed the operand disappears. The fixture is VC8 /O2 output of:

void polar(float angle, float r, float *out) {
    float rad = angle * 0.0174532925f;
    out[0] = (float)(cos(rad) * r);
    out[1] = (float)(sin(rad) * r);
    out[2] = (float)sqrt(out[0] * out[0] + out[1] * out[1]);
}

$ kuna decompile decompiler/crates/kuna-analysis/tests/fixtures/x87intrinsic_i386.obj _polar
  a0 = (float)((long double)a0 * (long double)0.01745329238474369);
  v2 = (long double)__CIcos();
  v1 = a2;
  *a2 = (float)(v2 * (long double)a1);
  v2 = (long double)__CIsin();
  ...
  v1[2] = (float)(long double)__CIsqrt();

With this change:

  v3 = __CIcos((long double)a0);
  ...
  v4 = __CIsin((long double)a0);
  ...
  v1[2] = (float)__CIsqrt(v5 * v5 + v4 * v4);

Fix

  • Two dedicated models are registered on x86-32: __kuna_x87unary (one float input and output in ST0, extrapop 4) and __kuna_x87binary (inputs ST1, ST0 in source order, output ST0, ST1 killed). A shared model cannot take an x87 input without inventing it on every other callee. The two-operand helpers pop a slot, which a model cannot state; MSVC calls them with only their operands on the x87 stack, so nothing the caller keeps is displaced.
  • The analysis tier binds them to __CIsqrt/sin/cos/tan/exp/log/log10/asin/acos/atan and __CIpow/atan2/fmod by name (an object's undefined externs included) and locks long double name(long double...); with the model alone, an operand the caller spills and reloads around the call (the usual cos-then-sin shape) failed the input trial.
  • In a stripped PE32 i386 image the VS2005 CRT objects are recognized whole, without storing their code: a 16-byte anchor, the object length, the relocation ranges, and an FNV-1a hash of the masked object. sin/cos differ in four unpatched bytes, log/log10 in three. atan2's object is two ten-byte stubs, too small to hash: __CIatan2 is the stub that jumps into the (hash-recognized) two-operand dispatcher and is not fmod's.
  • On a stripped 3.5 MB VC8 game: eight one-operand and three two-operand intrinsics recognized; all 409 one-operand calls (207 functions) get their operand, where 351 printed without one, and the 43 atan2/pow/fmod calls in their wrappers get both (float Angulo(float x, float y) { return atan2(x, y); } decompiled as one parameter and sub_6521ea()). Speed within noise; of 32 i386 PE/COFF fixtures only the new one changes.

Tests

tests/stages/kuna-x87intrinsics.xml decompiles the fixture and pins that no intrinsic is called without an operand, cos and sin of the scaled angle, sqrt of the sum of squares, atan2(y, x) in source order, and pow/fmod with both operands. Unit tests cover the prototype, the name matching, the signature hashes and the scan. No existing expectation moved.

Fixes #1560

[AUTOMATED] change made by an agent session.

thotypous and others added 4 commits November 7, 2026 21:42
Noelo-Lab#1560)

MSVC compiles sin(x), cos(x), sqrt(x) and their siblings on x86-32 as
`fld x; call __CIsin`, with the operand and result in ST0. No x86win.cspec
model takes an ST0 input, so the call recovered no argument and the
expression that computed the operand was dead-code eliminated.

- A dedicated model, __kuna_x87unary (ST0 in, ST0 out, extrapop 4), is
  registered on x86-32.
- The analysis tier binds it to __CIsqrt/sin/cos/tan/exp/log/log10/asin/
  acos/atan by name, and in a stripped PE32 i386 image to the VS2005 CRT
  objects recognized by anchor + masked FNV-1a hash (no CRT code stored),
  and locks `long double name(long double)` so a spilled operand still
  passes.

Stage test kuna-x87intrinsics added; stages baseline re-recorded for it.

[AUTOMATED] change made by an agent session.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…oelo-Lab#1560)

__CIpow, __CIatan2 and __CIfmod take their operands in ST1 and ST0 (source
order) and return in ST0. They get a second model, __kuna_x87binary, with
ST1 killed by the call: they pop one slot, which a model cannot state, but
MSVC calls them with only their operands on the x87 stack.

pow.obj and 87fmod.obj are recognized like the one-operand objects;
87ctriga.obj's stubs are too small to hash, so __CIatan2 is the dispatcher
stub (into a hash-recognized 87cdisp.obj) that is not fmod's.

[AUTOMATED] change made by an agent session.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@borancar borancar changed the title [AUTOMATED] Give MSVC x87 one-operand intrinsics their ST0 operand [AUTOMATED] Give the MSVC x87 math intrinsics their operands Nov 12, 2026
mahaloz and others added 10 commits November 13, 2026 16:44
…re whole-byte pulls

Review fixes on top of the bitfield root/read-order change:

- DWARF import again turns a whole-byte struct bitfield into a plain field,
  as on main and upstream's wire decode. Kept as bitfields, those fields lost
  their type to inference (constants compared with them printed as character
  literals, ZEXT18 casts), lost names on partial accesses, and exposed two
  wrong-C shapes below. The dwarf_member_layout fixtures and test return to
  main's; the review fixture's DWARF runs cover the functions main lays out.
- A LOAD or STORE whose pointer reaches exactly one whole-byte bitfield moves
  the field's integer type, and constants compared with a root pull take the
  field's type, so `jp->state == 1` no longer prints `'\x01'`.
- A SUBPIECE leaving a signed field in its top bits marks it sign-extended,
  so `SEXT(SUBPIECE(x))` of `int a:8` pulls `s.a` instead of a raw byte read.
- The insert trace lifts a mapped final write's own output to its input:
  `t.type = 6` on a stack struct no longer re-stores the old byte. Constants
  are never pull roots.
- Repeated pulls of the same bits of one LOAD share the first pull, so a word
  tested several times after a call prints one saved read, not one per test.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKQeLQDThvbHGNoGw8h
…rity, opt-in lines

`cvftrace` applies only to PE32 i386 images with a `.trace` section, so it now
follows the target-gated rule: `on` (default) names traced routines, `lines`
adds the file:line comments (opt-in like `dwarf_lines`), `off` disables both.

CVF names were committed through the FID rename and symbol streams, so on an
image with a COFF symbol table a traced name replaced `_sample` at the
definition while call sites kept `_sample`, and against a PDB name the
winner was whichever sorted first. They now ride a separate lowest-priority
stream applied after every other name source: a placeholder is renamed, an
undiscovered entry becomes a function, and a named function keeps its name
with no alias.

The decoder's file tables share one 65,536-name budget across records; a
16 MiB section of empty names allocated 480 MB before.

The end-to-end test now links with the mingw clang driver (no lld-link), and
covers default, `lines`, `off`, export and COFF-symbol precedence.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKQeLQDThvbHGNoGw8h
A root pull of a stack or global struct's whole-byte field rewired the
root's INDIRECT and MULTIEQUAL reads to the field value, which merged the
field into the whole variable: `peek(&t); a = t.type; create(&t);` printed
`t = t.type;` and read the byte through a cast. Those marker reads now keep
the storage; ordinary reads still take the pull. A shared pull is never
substituted for a complete record whose value is mapped storage.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKQeLQDThvbHGNoGw8h
…ported caps

No real CVF image is available to sweep, so the default is now as narrow as
the format allows:

- A trace name only renames an existing `sub_<addr>` placeholder function.
  No function is created at a traced address any more, so a routine marker
  inside a function (or inside an instruction) can no longer split it.
- A name that any function, data symbol or registered alias already uses is
  skipped, so the fallback step can no longer take `exported` (or a COFF or
  `--define-function` name) away from its real address. A name the trace gives
  two addresses, or an address it gives two names, is dropped.
- Routine names must be Fortran identifiers (letters, digits, `_`, `$`, at
  most 127 bytes); any other name declines its record.
- The file-name budget is charged only to accepted records, and any size cap
  that stops decoding prints one `[kuna cvftrace]` note.
- The end-to-end test prints SKIP when clang cannot link an i686 mingw DLL,
  and covers collisions, duplicates, interior markers, COFF precedence and
  the cap note.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKQeLQDThvbHGNoGw8h
Also fills the `by_signature` field main added to `FidMatch` (a CVF name is
metadata, not a signature guess).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKQeLQDThvbHGNoGw8h
…ics off __cdecl

- The atan2 stub search rescanned the whole section once per stub that jumps
  to the dispatcher, O(N^2) at load on a crafted PE32 (16,000 stubs: 3.9 s,
  100,000: minutes). The stubs are now collected in one pass and only a lone
  non-fmod stub is named; the masked hash walks its sorted wild ranges, and
  at most 64 hits of one anchor are examined per section. 100,000 stubs and
  a 4 MB anchor-tiled section now load as fast as base.
- A C runtime import is seeded __cdecl (engine step 5d); an intrinsic
  imported from msvcr*.dll (`_CIcos`, VS2008 /MD) was then read as a ten-byte
  stack argument, taking the caller's pushed arguments with it. Intrinsics are
  exempt and keep their x87 model; regression fixture x87import_pe_i386.exe.
- Names need the CRT's underscore spelling (`_CIsin`/`__CIsin`), so a bare
  `CIsin` on another image is left alone; `_CIsinh/_CIcosh/_CItanh` added.
- The model-fact commit is one helper shared with the Swift bindings.
- Fixtures README rows with SHA-256; spec 01/04 prose.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKQeLQDThvbHGNoGw8h
A ZPULL or SPULL that names its field through its LOAD's pointer prints as
that memory read (`p->mid`), but its ordering checks applied only once the
LOAD itself was absorbed. When the same word also feeds a read-modify-write,
the LOAD stays printed until the INSERT absorbs it, so pull absorption and
variable folding could print the field read after the field store and an
aliasing store: on 32-bit MIPS and PowerPC a register-pair return printed
`p->hi = v; *q = 7; return p->mid;` although the word is read once, before
both stores. Such a pull now takes the LOAD's store/call/write ordering
checks. Regression: a prebuilt MIPS-BE object (rmw.c) and a CLI test
asserting the read precedes both stores.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKQeLQDThvbHGNoGw8h
@mahaloz

mahaloz commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

[AUTOMATED] Thanks for this. Every pow/atan2/fmod call I checked in real MSVC binaries loads its operands in the order your model uses: ST1 is the first argument and ST0 the second, and only the two operands are on the x87 stack at the call. I pushed 01875a0 on top of your branch with two fixes.

  1. Load time on a crafted PE32 grew quadratically. Repro: a .text holding the 87cdisp.obj dispatcher and N mov edx,imm; jmp <dispatcher> stubs:
$ kuna functions pe_32000_stubs.exe      # 17.3 s before (main: 0.3 s); 0.4 s after

table_stubs rescanned the whole section for every stub. The stubs are now collected in one pass, and only a single non-fmod stub is named __CIatan2. The masked hash walks its sorted wild ranges, and at most 64 hits of one anchor are examined per section, so a section tiled with the shared anchor also loads as fast as main.

  1. An intrinsic imported from msvcr*.dll was still seeded __cdecl by the engine's C runtime import rule (step 5d), so its locked long double operand was read off the caller's stack:
$ kuna decompile decompiler/crates/kuna-analysis/tests/fixtures/x87import_pe_i386.exe 0x401000 | grep _CIcos
# before:  _CIcos((long double)CONCAT64(CONCAT24(*(unsigned short *)&a0,v4),v2))
# after:   _CIcos((long double)v1)        (v1 = *a0, loaded into ST0)

Intrinsics are now exempt from that rule. The new clean-room fixture is x87import_pe_i386.asm, and the stage test gained two assertions for it.

The commit also:

  • requires the CRT's underscore spelling (_CIsin, __CIsin), so a bare CIsin on another image is left alone
  • adds _CIsinh, _CIcosh and _CItanh
  • folds the model commit into one helper shared with the Swift bindings
  • adds fixtures README rows with SHA-256

mahaloz and others added 6 commits November 13, 2026 22:15
Conflicts resolved: count sites (kuna_phases/tests.rs, catalog_bytecompat.rs,
kuna-catalog.xml) and docs/options.md (main side taken, re-derived after build).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKQeLQDThvbHGNoGw8h
Settables 211 -> 212 (cvftrace); KUNA-CATALOG Noelo-Lab#15 217 -> 218 by hand;
docs/options.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKQeLQDThvbHGNoGw8h
main's FLIRT change (Noelo-Lab#1548) added FidMatch.by_signature. The x87
intrinsic names the hash recognizer commits are built with
by_signature: false: each comes from an exact whole-object hash/byte
match and keys the call's model binding, so it is authoritative like the
metadata streams (PDB, ObjC, Swift), the same as Noelo-Lab#1553's __ftol helpers.
With true, a FID or FLIRT database that spells the helper differently at
the same address would make the agreement rule leave sub_ and silently
drop the binding.

main (Noelo-Lab#1506) made AnalysisCtx.image an Option (None only for the
image-free deferred-entry, listing-consumer, operand-refs and 4-byte
string runs). X87IntrinsicPass is registered in passes_for, which always
runs with Some(image), so it reads the image with main's
`ctx.image.expect("load-time analysis image")`, as libcsigs, libctypes,
libgcc and the protos pass in the same list do.

Conflicts resolved: passes.rs (main's IncrementalLinkPass and the PR's
X87IntrinsicPass both registered after CallFixupPass), spec 01 (main's
callfixup continuation paragraph first, then the PR's x87 intrinsics
bullet), kuna-base xml.rs (both comment lines; count re-derived) and
docs/baseline-stages.json (key-level merge, +8 X87INTRINSICS names).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKQeLQDThvbHGNoGw8h
@mahaloz
mahaloz merged commit e9d20a0 into Noelo-Lab:main Nov 13, 2026
@borancar
borancar deleted the x87-intrinsics branch November 13, 2026 23:08
mahaloz added a commit to borancar/kuna that referenced this pull request Nov 14, 2026
main's calleereginputs (Noelo-Lab#1559) and x87 intrinsics (Noelo-Lab#1561) add items at the
same spots as this branch; every conflict is an addition next to another,
and both are kept, main's first: the Architecture cache field and its
initializer, the FuncCallSpecs field, initializer, clone line and accessor
pair, the FlowEnvironment default method and its ArchFlowEnv override, the
flow call-spec setter (set_callee_reg_model, then set_callee_purge, under
the same direct-callee condition) and the p4_calls module list. The model
choice (ActionDefaultParams) and the proven pop (ActionExtraPopSetup) stay
in their own actions. Also kuna-base xml.rs (both comment lines; count
re-derived) and docs/baseline-stages.json (key-level merge, +10
CALLEEPURGE names).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKQeLQDThvbHGNoGw8h
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[AUTOMATED] x86-32 MSVC: calls to the x87 math intrinsics (__CIsin, __CIcos, __CIsqrt, ...) lose their operand

4 participants