Skip to content

Emit-C lowers 64-bit swap_bytes/popcount/clz/ctz/bitreverse at 32 bits (rotate fixed in #2044) #1006

Closed

Description

@eas4ai

Restated 2026-10-25. rotate_left/rotate_right are fixed at every width (#2044). What is left: emit-C still lowers swap_bytes, popcount, clz, ctz and bitreverse at 32 bits for an i64 operand.


Original report

Summary

The emit-C lane lowers every bit intrinsic at a hardcoded 32-bit width regardless of operand type. A 64-bit rotate_left emits a 32-bit rotate (truncate + & 31u + 32u), silently computing the wrong value while the LLVM lane is correct.

Repro (seed stage1 at 450733e)

rotate64_probe.w (.audit/probes/ccodegen/): 1i64.rotate_left(1) + 256i64.swap_bytes().

  • LLVM run: rot=2 rot-ok swap=281474976710656 rc=0 (correct).
  • build --emit-c: line 7736 emits { uint32_t __with_v = (uint32_t)(_1); uint32_t __with_n = (uint32_t)(1) & 31u; _4 = (int32_t)((__with_v << __with_n) | (__with_v >> (32u - __with_n))); } for the i64 operand — verified in fresh emission by primary.
  • Value proof (rot_demo.c, preserved beside the probe): the exact emitted expression on v=(1<<33)|3, n=1 gives 6; correct 64-bit rotate gives 17179869190. Compiled with plain cc -O1, exit code differs.

Root-cause chain (verified by reading + execution)

emit_builtin_numeric_call_term (src/CCodegen.w:7075+, primary-read): ROTATE_LEFT/RIGHT, INT_SWAP_BYTES (__builtin_bswap32), POPCOUNT, CLZ (== 0 ? 32), CTZ, BITREVERSE32 — all hardcode 32-bit types/masks with no width dispatch. The function receives ret_tid (the width is available) and ignores it. No uint64_t/& 63u/64u path exists anywhere in the intrinsic emitters (grep-verified).

Severity

High for the emit-C lane: silent wrong-code generation (no diagnostic, valid C, wrong values) for all six intrinsics on 64-bit operands. Same 32-bit-truncation disease as #943 (comptime lane), different lane — the width-narrowing pattern keeps recurring per-lane instead of once centrally.

Suggested fix (owner's call)

Dispatch on operand width (the ignored ret_tid) with 64-bit forms (__builtin_bswap64, __builtin_popcountll, __builtin_clzll, mask 63u, width 64u).

Audit provenance

Read-only end-to-end audit, CCodegen leg (child complete examination 1-9613, independently verified by primary: branch reads + fresh --emit-c + LLVM-run control + C-level value proof). Lane umbrella: #955. Sibling classes already open: #990 (enum repr), #983/#982 (emit-C skips/stubs).

Activity

  1. ehartford commented on Sep 16, 2026

    @ehartford
    Contributor

    Review: reproduced

    Verdict. Established on current main by running the same program through both backends. Every bit intrinsic in the C backend is emitted at a hardcoded 32-bit width: for i64 operands the emitted C truncates to uint32_t, masks the shift count with & 31u, and calls __builtin_bswap32 / __builtin_bitreverse32, so rotate_left, rotate_right, swap_bytes, and bitreverse all return wrong values while the LLVM backend is correct. grep finds no 64-bit form (63u, bswap64, popcountll, clzll, ctzll) anywhere in src/CCodegen.w. popcount, clz, and ctz share the same emitter shape by source and were not executed here.

    Tested revision and compiler

    item value
    source main @ 5809ac1 (2026-09-14); the emitters at CCodegen.w:7077-7166 are unchanged since 450733e
    compiler with build of 5809ac1 in a detached worktree, self-reports with v0.15.2.1
    C compiler Apple cc -O1 against the worktree's out/lib/{rt_core,rt_darwin_aarch64,compat_runtime,panic_runtime,fiber_stubs,cimport_stubs}.o (the set build/emit_c.w:582-587 links)
    platform macOS Darwin 25.6.0, arm64

    Repro

    fn main:
        let v: i64 = (1i64 << 33) | 3
        print(f"rotl={v.rotate_left(1)} expect=17179869190")
        print(f"rotr={v.rotate_right(1)} expect=-9223372032559808511")
        print(f"swap={256i64.swap_bytes()} expect=281474976710656")
        print(f"brev={1i64.bitreverse()} expect=-9223372036854775808")
    
    intrinsic on i64 expected LLVM (with run) C backend (--emit-c, cc, run)
    rotate_left(1) of (1<<33)|3 17179869190 17179869190 4309073936
    rotate_right(1) -9223372032559808511 correct 4309073936
    256.swap_bytes() 281474976710656 correct 65536
    1.bitreverse() -9223372036854775808 correct -2147483648

    Emitted C for the i64 operands (from bits.c):

    { uint32_t __with_v = (uint32_t)(_1); uint32_t __with_n = (uint32_t)(1) & 31u; _6 = (int32_t)((__with_v << __with_n) | (__with_v >> (32u - __with_n))); }
    _27 = (int32_t)__builtin_bswap32((uint32_t)(_26));
    _38 = (int32_t)__builtin_bitreverse32((uint32_t)(_37));
    

    Source

    src/CCodegen.w:7077-7166 in emit_builtin_numeric_call_term: ROTATE_LEFT (:7077) and ROTATE_RIGHT (:7093) use uint32_t, & 31u, 32u; INT_SWAP_BYTES (:7108) __builtin_bswap32; POPCOUNT (:7122) __builtin_popcount((unsigned int)...); CLZ (:7136) and CTZ (:7150) == 0 ? 32 : __builtin_clz/ctz((unsigned int)...); BITREVERSE (:7164) __builtin_bitreverse32. None consult the operand or result type id that the function receives. The Sema side (src/SemaCheck.w:19167-19169) admits these methods on all integer widths, so the frontend contract is width-generic and only the C lowering is not.

    Spec

    The specification defines these as integer methods without a width restriction (the LLVM backend honours that), so the C backend is producing different results for the same program, which AGENTS.md classes as a silent miscompile. #943 (closed) was the comptime lane's version of the same 32-bit narrowing; this is the C lane's.

    Related PRs

    None merged or open touch these emitters. #955 (open) is the emit-C lane umbrella; #983 and #990 (this queue) are sibling C-backend divergences.

    Would I champion a fix? Yes; it is a width dispatch on data the emitter already has.

    Acceptance criteria:

    1. Each emitter selects the C type, mask, width constant, and builtin by operand width (uint8_t/16/32/64, & 63u, 64u, __builtin_bswap64, __builtin_popcountll, __builtin_clzll/ctzll with the == 0 ? 64 guard, __builtin_bitreverse64), with i8/i16 handled explicitly rather than widened.
    2. The probe above prints identical lines on both backends; a second probe covers popcount, clz, ctz on i64 and on u8.
    3. An emit-C differential test over all six intrinsics x {i8,i16,i32,i64} runs in the emit-c lane.
    4. Optional: a single width-aware helper so the narrowing pattern cannot recur per intrinsic (the report's "per-lane" point).

    Untested

    popcount/clz/ctz on 64-bit were read, not run; u64 operands and the 8/16-bit cases were not run on either backend. Linux and Windows not executed.

  2. ehartford commented on Oct 3, 2026

    @ehartford
    Contributor

    Also in the 32-bit rotate itself (CCodegen.w ROTATE_LEFT/ROTATE_RIGHT): __with_n = n & 31u then __with_v >> (32u - __with_n) shifts by 32 when n is 0 (or a multiple of 32), which is undefined behavior in C. The LLVM backend had the same shape ((x << n) | (x >> (W - n)), poison at n = 0 or W) and now lowers to llvm.fshl/fshr (stack #2032, impl-1864 layer); emit-C needs the masked form (v << n) | (v >> ((-n) & (W-1))) at the operand's own width.

  3. ehartford commented on Oct 3, 2026

    @ehartford
    Contributor

    emit-C rotate now matches the LLVM backend's funnel shift (9475185) and comptime_rotate_bits: fix-2036 commit 33b2240c (CCodegen.rotate_text). The C text was 32-bit for every integer type and shifted by 32 when the count was 0. It now computes at the value's own width W (8/16/32/64/128; any other width refuses loudly), takes the count modulo W (so -1 is W - 1), and returns the value unchanged for a count of 0, so no shift is ever by W. test/emit_c/rotate_widths.w covers u8, i8, u16, u32, i32, u64 and i64 at counts 1 (right), 0, W, W + 1 and -1; both backends print the same lines.

  4. added a commit that references this issue on Oct 3, 2026
  5. changed the title [-]Emit-C hardcodes 32-bit bit-intrinsics: 64-bit rotate/byteswap/popcount/clz/ctz/bitreverse miscompile[/-] [+]Emit-C lowers 64-bit swap_bytes/popcount/clz/ctz/bitreverse at 32 bits (rotate fixed in #2044)[/+] on Oct 25, 2026
  6. ehartford commented on Oct 25, 2026

    @ehartford
    Contributor

    Triage 2026-10-25, with v0.15.3.0 (main a261b65): reproduced for the five non-rotate intrinsics.

    $ cat main.w   # a: i64 = 1, b: i64 = 256, c: i64 = -1
    print(a.rotate_left(1)); print(b.swap_bytes()); print(c.popcount()); print(a.clz()); print(b.ctz()); print(a.bitreverse())
    $ with run main.w   # LLVM
    2
    281474976710656
    64
    63
    8
    -9223372036854775808
    $ with build main.w --emit-c -o main.c
    { uint64_t __with_v = (uint64_t)(_1); … & 63u … }          # rotate: 64-bit, correct
    _8 = (int32_t)__builtin_bswap32((uint32_t)(_2));
    _12 = (int32_t)__builtin_popcount((unsigned int)(_3));
    _16 = (_1) == 0 ? 32 : (int32_t)__builtin_clz((unsigned int)(_1));
    _20 = (_2) == 0 ? 32 : (int32_t)__builtin_ctz((unsigned int)(_2));
    _24 = (int32_t)__builtin_bitreverse32((uint32_t)(_1));
    

    post-release: part of the emit-C lane campaign (#955).

  7. added this to the post-v0.16.0 milestone on Oct 28, 2026
  8. added a commit that references this issue on Nov 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions