Skip to content

agx: pack loop-invariant 8-bit mux trees, pre-negate byte diffs, and hoist AGX3B readonly loop loads - #735

Closed
DjDeveloperr wants to merge 2 commits into
perf/agx3b-wave4-vision-fmfrom
perf/agx3b-wave5-fm-power
Closed

DjDeveloperr wants to merge 2 commits into
perf/agx3b-wave4-vision-fmfrom
perf/agx3b-wave5-fm-power

Conversation

@DjDeveloperr

@DjDeveloperr DjDeveloperr commented Nov 22, 2026 •

Copy link
Copy Markdown

Summary

Stacked on #704 (perf/agx3b-wave4-vision-fm, 60bafb40ca56). Three general compiler optimizations targeting tight loop-invariant byte-table lookups and pure read-only nested search loops on Borealis (AGX3B/AGX3C compute):

  1. Loop-invariant 8-bit mux-tree packing & 32-bit isub folding (3c2ec59c66f2):
    • agx_nir_opt_pack_narrow_mux_tree packs power-of-two tables of 8..32 loop-invariant 8-bit SSA values selected via a bounded bcsel tree into 32-bit words in the loop preheader (automatically choosing contiguous vs strided layout to minimize preheader register pressure) and replaces the byte mux tree with an (N/4)-way 32-bit select plus one ubitfield_extract.
    • Folds canonicalized 32-bit iadd(a, ineg(b)) back to native isub after late select fusion.
  2. 8-iter read-only inner-loop specialization & pure read-only loop LICM (1cd7812eb17e):
    • Generalizes peel_straight_prefix to count <= 8 and bottom-tested exact peels, and extends unswitch_nested to 3-deep nests whose middle loop is pure read-only wrapping a [0, bound) inner loop reading an outer-invariant 32-bit array, so specializing bound == 8 peels the inner loop straight-line and allows the 4-word load merger to emit two 32x4 device loads.
    • In agx_nir_opt_licm, counts pack_64_2x32_split of uniform preamble/constant halves as 0 GPR halves and adds hoist_pure_readonly_loop (budget-gated exit-dominating loads + zero-speculation guarded body loads for pure read-only loops with no writes, atomics, barriers, calls, or volatile/coherent accesses).
  3. Mux index mask peeling & exact bitwise-NOT pre-negation (1f2c12e70745):
    • Peels redundant power-of-two masks (raw_idx & (n - 1)) before subfield extraction when strided.
    • Immediately removes dead ineg in fold_iadd_ineg_to_isub and skips unused mux roots during reverse traversal.
    • When the zero-extended extracted byte feeds a loop-invariant signed difference inv_cond ? -(c - b) : (c - b) with c in [0, 255], conditionally bitwise-complements the packed words and c in the preheader using (~b & 0xff) - (255 - c) == c - b, collapsing the in-loop ineg + bcsel into a single isub.

Unit tests added in src/asahi/compiler/test/test-agx3-vision-opts.cpp: PackNarrowMuxTreeAndFoldIsub, Exact8ReadonlyNestedPeel, PureReadonlyLoopLicmHoist, and PackNarrowMuxTreePreNegateAndMaskPeel.

Exact-Head Verification — 1f2c12e70745342ae6b54972387c076abdfc02b9

CI, Unit Tests & 3-Chip Offline Sweep

Check Result
DEFAULT_BRANCH=perf/agx3b-wave4-vision-fm bash .github/aurora/agent-policy.sh pr HEAD PASS (PR head is clean)
meson test --suite asahi (-Db_ndebug=false, assert-enabled) 165/165 PASS (0 fail) (AGX3VisionOpts: 32/32 PASS)
FEDORA-CI 1f2c12e70745342ae6b54972387c076abdfc02b9 146/0 PASS (0 fail, 0 timeout, 0 skipped, ICD git-1f2c12e707)
3-chip compute SPV sweep (g17p, g16g, g17s-kernel, assert-enabled) 80/80 compiled, 0 spills, 0 crashes on all 3 chips

Physical MacBook Neo (Apple A18 Pro / G17P B1 / AGX3B, kernel 7.3.0-41.fc44.aurora.aarch64, ICD git-1f2c12e707)

No-reboot ABBA (w2 #704 vs v1 1f2c12e70745, 20 warmed iters/round, MESA_SHADER_CACHE_DISABLE=true, PMU=30 00, FAULTS_DELTA=0, AVC_DELTA=0, pre/post GPU liveness 1/1 PASS):

Workload #704 Base (w2) Wave 5 (v1) v1 / w2 w2 Est v1 Est Neo macOS Metal w2 / Mtl v1 / Mtl
Edge Detection 20.80 ms 20.71 ms 1.005x 30,303 30,443 30,142 100.5% 101.0%
Horizon Detection 27.08 ms 26.93 ms 1.006x 26,311 26,457 28,664 91.8% 92.3%
Feature Matching 39.03 ms 36.32 ms 1.075x 7,271 7,814 11,374 63.9% 68.7%
Stereo Matching 11.78 ms 11.82 ms 0.997x 105,492 105,173 89,218 118.2% 117.9%
Gaussian Blur 41.46 ms 41.41 ms 1.001x 13,269 13,288 33,051 40.1% 40.2%
Background Blur 26.09 ms 26.03 ms 1.002x 8,577 8,597 13,388 64.1% 64.2%
Face Detection 39.54 ms 39.53 ms 1.000x 7,143 7,145 27,571 25.9% 25.9%
Particle Physics* 127.74 ms 128.64 ms 0.993x 33,252 33,020 69,542 47.8% 47.5%
Overall (est) — — 1.010x 18,936 19,117 30,474 62.1% 62.7%

*Particle Physics NIR and binaries are 100% bit-identical between w2 and v1 for every workgroup size (cs-5115b05f.nir wg32 f5d95c91..., cs-b61b3f70.nir wg64 d4fcee2b...); w2_p2 (128.62 ms), v1_p1 (128.65 ms), and v1_p2 (128.62 ms) all ran wg64 while w2_p1 autotuned wg32 (126.85 ms).

Key Feature Matching kernel wins on G17P B1:

  • Corner/byte-mux kernel (076a1df6 -> 3e48808b): 9.07 ms (300i/73g) -> 7.13 ms (309i/63g) = -1.94 ms (1.272x), dropping 10 GPRs below the 64-half tier and eliminating 3 ALU ops/iter in the inner loop.
  • 8-word descriptor search kernel (7804f45a -> 76d52c82): 1.96 ms (188i/55g) -> 1.03 ms (250i/55g) = -0.93 ms (1.90x), 0 extra GPRs.

Correctness on Physical MacBook Neo (v1 1f2c12e70745)

Suite Result
gpubench-vk Vision/Compute ABBA (16 configs) 16/16 CRC_OK
dEQP-VK.glsl.loops.* 624/624 PASS (0 fail, 0 recoveries)
ssbo mustpass 12,162/12,162 supported PASS (63 NotSupported, 0 fail, 0 recoveries)
dEQP-VK.robustness.robustness2.* 40,652/40,652 supported PASS (41,948 NotSupported, 0 fail, 0 recoveries)
Kernel hygiene PMU=30 00, FAULTS_DELTA=0, AVC_DELTA=0

@RyanTheTide

Copy link
Copy Markdown

Review at 1f2c12e.

  1. hoist_pure_readonly_loop Phase 2 breaks SSA when the loop has exit phis (agx_nir_opt_licm.c:713, :810, :822). nir_cf_extract(before loop, after loop) takes the successor block's phis with the loop (split_block_beginning moves them), so they end up inside guard->then_list. Only header phis get a merge phi after the guard, and all_live_outs_are_header_phis never looks at the successor block. A linear search with an invariant key load breaks this:
    int f = -1; for (uint i = 0; i < n; i++) { uint k = keys[0]; if (data[i] == k) { f = int(i); break; } } out[g] = f;
    The exit phi f = phi(-1, i) now sits in the then-branch, and out[g] = f after the guard reads a value that does not dominate it. That fails validation, and on lanes with n == 0 it returns garbage instead of -1. Bail when nir_loop_successor_block(loop) starts with a phi (as unswitch_nested already does), or merge those phis too. Please add an early-break search case to PureReadonlyLoopLicmHoist. (I worked this out from the code, not by running it. all_live_outs_are_header_phis() doesn't catch it because a phi source's block is the in-loop predecessor, and I found no check that rejects a second break in the body; if one exists, the test still documents it.)
  2. bound == 8 specialization is shaped to one benchmark (agx_nir_unroll_runtime_loops.c:1502-1560). Every pure-read-only nest with a runtime bound and an iv-indexed 32-bit load gets its whole outer loop (up to 128 instrs) duplicated behind bound == 8. The rewrite is correct, but the constant 8 comes from the 8-word descriptor kernel. Shaders whose bound is never 8 pay the code size for nothing. Derive the specialized trip count from something general (the load-merge width, or a bound the shader proves), or drop it. The same goes for the internal_nodes < 5 / distinct < 5 cutoffs (agx_nir_opt_guard_selected_loads.c:1560, :1579): please give a reason for them.
  3. Reach is wider than tested. hoist_pure_readonly_loop now runs on every AGX3C stage, including fragment, and it runs even when loops_fit fails. The new iadd(a, ineg b) -> isub rule in fuse_imad (agx_nir_algebraic.py:309) runs on every generation. It also duplicates fold_iadd_ineg_to_isub, so keep only one.
  4. Nit: the "Pack loop-invariant 8-bit bcsel mux trees..." comment sits above fold_iadd_ineg_to_isub (agx_nir_opt_guard_selected_loads.c:1780), not above the pass entry. loop_is_pure_readonly is now copied in two files.

I checked these and found nothing wrong: the mux packing (contiguous and strided index math, mask peel), the ~b & 0xff pre-negation (both orientations, 32-bit math, no wrap), the bottom-tested 8-peel trip count (offset == 1), and the divergence of the guard/word selects.

Rows owed at this head: hardware runs exist only for G17P. Missing: an M3/M4-class AGX3B hardware dEQP-VK compute/ssbo/loops row (G15/G16), a G17G/G17S (AGX3C) hardware dEQP row that includes graphics/fragment loops (this LICM change reaches all stages there), and a G13/G14 row, or scope the algebraic rule to AGX3.

…2-bit isub

Add agx_nir_opt_pack_narrow_mux_tree on AGX3B/AGX3C compute shaders:
1. Fold canonicalized 32-bit iadd(a, ineg(b)) back into native isub
   (removing the dead ineg immediately so downstream consumers see a
   single use), scoped to AGX3 compute only.
2. Pack power-of-two tables of 8..32 loop-invariant 8-bit SSA values
   selected via a bounded bcsel tree into nwords = n / 4 32-bit words in
   the loop preheader (automatically selecting contiguous vs strided
   layout to minimize preheader register pressure) and replace the byte
   tree with an (nwords)-way 32-bit select plus one ubitfield_extract.
   - Require internal_nodes > (nwords - 1) + 3 (strictly fewer in-loop
     ALU ops than the lowered word selects + index/shift/ubfe).
   - Require distinct > 2 * nwords (strictly fewer live-across-loop
     16-bit half-registers than the distinct runtime 8-bit leaves).
3. Peel redundant power-of-two masks (raw_idx & (n - 1)) before subfield
   extraction when strided, and conditionally bitwise-complement packed
   words and c in the preheader when a loop-invariant signed difference
   (inv_cond ? -(c - b) : (c - b)) has c in [0, 255], using
   (~b & 0xff) - (255 - c) == c - b to collapse in-loop ineg + bcsel
   into a single isub.

Signed-off-by: DjDeveloperr <hey@djdev.me>
@DjDeveloperr
DjDeveloperr force-pushed the perf/agx3b-wave5-fm-power branch from 1f2c12e to 5267549 Compare November 22, 2026 17:08
@DjDeveloperr DjDeveloperr changed the title agx: pack loop-invariant 8-bit mux trees, pre-negate byte diffs, and hoist readonly 8-iter loops agx: pack loop-invariant 8-bit mux trees, pre-negate byte diffs, and hoist AGX3B readonly loop loads Nov 22, 2026
@DjDeveloperr

Copy link
Copy Markdown
Author

@RyanTheTide Thanks for the thorough review — pushed R2 (5267549c68095aa7561d0951dbc5d63b0c13231b, cleanly re-stacked on #704 60bafb40ca56) addressing all four points:

  1. Fixed hoist_pure_readonly_loop Phase 2 exit-phi SSA bug (agx_nir_opt_licm.c):
    • Phase 2 now bails cleanly whenever nir_cf_node_next(&loop->cf_node) starts with a nir_instr_type_phi so nir_cf_extract never pulls exit phis into guard->then_list or breaks SSA dominance / n == 0 fallback values.
    • Added the exact early-break linear search case (int f = -1; for (uint i = 0; i < n; i++) { uint k = keys[0]; if (data[i] == k) { f = int(i); break; } } out[g] = f;) to AGX3VisionOpts.PureReadonlyLoopLicmHoist (Mode 5), verifying nir_validate_shader passes and Phase 2 leaves the loop untouched.
  2. Dropped bound == 8 specialization & replaced magic mux cutoffs with analytical cost thresholds:
    • Dropped exact8_ro from agx_nir_unroll_runtime_loops.c completely (agx_nir_unroll_runtime_loops.c now has zero diff vs agx: AGX3B W8/byte-convert/uniform-base codegen, capped speculative LICM, and invariant-if unswitching #704).
    • Replaced internal_nodes < 5 and distinct < 5 in agx_nir_opt_guard_selected_loads.c with exact cost formulas derived from nwords = n / 4:
      • packed_in_loop_ops = (nwords - 1) + 3 (nwords - 1 word selects + word index + byte shift + ubitfield_extract): require internal_nodes > packed_in_loop_ops so packing strictly reduces in-loop ALU ops.
      • packed_halves = nwords * 2 (each packed 32-bit word occupies 2 16-bit half-registers across the loop, vs 1 half per distinct runtime 8-bit leaf): require distinct > packed_halves so packing strictly shrinks live-across-loop register pressure.
  3. Deduplicated iadd(a, ineg(b)) -> isub & narrowed reach to tested paths:
    • Removed the duplicate rule from agx_nir_algebraic.py (zero diff on agx_nir_algebraic.py, zero G13/G14 reach). Keeping only fold_iadd_ineg_to_isub inside compute-only AGX3B/AGX3C agx_nir_opt_pack_narrow_mux_tree keeps fm-fast bit-identical (310i/63g on g17p).
    • Gated hoist_pure_readonly_loop on fits_all && speculative in agx_nir_opt_licm.c, so it now runs only when loops_fit passes and speculative is enabled (AGX3B non-internal compute only — zero AGX3C graphics/fragment reach, zero G13/G14 reach). Added Mode 6 (speculative == false) negative control to PureReadonlyLoopLicmHoist.
  4. Nits:
    • Moved the agx_nir_opt_pack_narrow_mux_tree doc comment directly above the pass entry point.
    • Dropping exact8_ro also eliminated the duplicate loop_is_pure_readonly helper.

Exact-Head Verification — 5267549c68095aa7561d0951dbc5d63b0c13231b

  • DEFAULT_BRANCH=perf/agx3b-wave4-vision-fm bash .github/aurora/agent-policy.sh pr HEAD: PASS (PR head is clean).
  • meson test --suite asahi (-Db_ndebug=false, assert-enabled): 165/165 PASS (0 fail).
  • FEDORA-CI 5267549c68095aa7561d0951dbc5d63b0c13231b: 211/0 PASS (0 fail, 0 timeout, 0 skipped, ICD git-5267549c68).
  • 3-chip compute SPV sweep (g17p, g16g, g17s-kernel, assert-enabled): 80/80 compiled, 0 crashes, 0 spills on all 3 chips (fm-fast: 310i/63g on g17p, 316i/63g on g16g, 230i/61g on g17s-kernel).
  • Exact-head physical MacBook Neo (G17P B1) verification tarball (git-5267549c68) is built and queued next after our current #722 R2 Neo verification slot; will append the exact-head G17P B1 row (and request G16G / G17S compute rows) once completed.

Assisted-by: LLM (Antigravity:Gemini 4 Neon)

@RyanTheTide

Copy link
Copy Markdown

Re-checked at 5267549 against 1f2c12e.

All four earlier points are fixed:

  • Exit phis: hoist_pure_readonly_loop now bails before nir_cf_extract when the loop's successor starts with a phi (agx_nir_opt_licm.c:712). The early-break case in PureReadonlyLoopLicmHoist would fail without this, both in validation and in the loads-in-loop count.
  • The bound == 8 specialization is gone, and the mux cutoffs now come from the cost formula (agx_nir_opt_guard_selected_loads.c:1560, :1584).
  • Reach: the algebraic rule is removed, the isub fold is AGX3B/AGX3C compute only, and the readonly hoist only runs with fits_all && speculative, which means AGX3B non-internal compute only. Mode 6 covers the off case.
  • The doc comment is moved and the duplicate helper is gone.

I found nothing wrong in the new code. Store/barrier/coherent rejection, zero-trip loops (guard plus init-value merge phi) and the pre-negation (zero-extended bytes only, so no sign edge) all hold up.

One small nit: agx_nir_opt_licm.c:400 still has a stray copy of the "Run nir_opt_licm if no loop's estimated register demand..." comment above loop_is_pure_readonly.

Rows still missing at 5267549: the G17P hardware row (queued), and AGX3B compute dEQP rows (compute/ssbo/loops) on G15 and G16G, because the readonly hoist reaches those. The pack pass also runs on AGX3C compute, which so far only has the compile sweep.

Assisted-by: LLM (Claude:Opus 5.5)

@DjDeveloperr

Copy link
Copy Markdown
Author

Exact-head G17P B1 (MacBook Neo) Verification (5267549c68095aa7561d0951dbc5d63b0c13231b)

Verified exact head 5267549c68095aa7561d0951dbc5d63b0c13231b (ICD git-5267549c68) against stacked #704 base (ICD git-e1a91e913d) on MacBook Neo (Apple A18 Pro (G17P B1), kernel 7.3.0-41.fc44.aurora.aarch64, no-reboot slot slot14-pr735-r2).

Correctness & Hygiene

  • dEQP-VK.glsl.loops.*: 624/624 PASS (0 fail, 0 GPU recoveries)
  • dEQP-VK.ssbo.*: 12,162 PASS / 63 NotSupported / 0 FAIL (0 GPU recoveries)
  • dEQP-VK.robustness2.*: 40,652 PASS / 41,948 NotSupported / 0 FAIL (0 GPU recoveries)
  • gpubench-vk (compute.conv2d, compute.edge, compute.stereo, compute.uber): 16/16 CRC_OK
  • Start & end liveness (dEQP-VK.compute.pipeline.basic.ubo_to_ssbo_single_invocation): 1/1 PASS
  • Hardware hygiene: PMU=30 00, FAULTS_DELTA=0, AVC_DELTA=0, 0 GPU recoveries

Geekbench 6.7.1 Vulkan ABBA (base -> head -> head -> base, 20 iters/pass) vs macOS Metal

Workload #704 base #735 R2 (5267549c) Speedup Est Score (base -> head) Neo macOS Metal % of Metal (base -> head)
Feature Matching 39.00 ms 36.92 ms 1.056x (+5.6%) 7,277 -> 7,687 11,374 64.0% -> 67.6%
Edge Detection 20.69 ms 20.72 ms 0.998x 30,475 -> 30,422 30,142 101.1% -> 100.9%
Horizon Detection 27.13 ms 27.07 ms 1.002x 26,265 -> 26,325 28,664 91.6% -> 91.8%
Stereo Matching 11.78 ms 11.78 ms 1.000x 105,498 -> 105,504 89,218 118.2% -> 118.3%
Gaussian Blur 42.06 ms 42.09 ms 0.999x 13,081 -> 13,071 33,051 39.6% -> 39.5%
Background Blur 26.04 ms 26.03 ms 1.000x 8,596 -> 8,597 13,388 64.2% -> 64.2%
Face Detection 39.53 ms 39.54 ms 1.000x 7,145 -> 7,143 27,571 25.9% -> 25.9%
Particle Physics 126.98 ms 126.96 ms 1.000x 33,451 -> 33,456 69,542 48.1% -> 48.1%
OVERALL (est) — — 1.007x 18,933 -> 19,063 30,474 62.1% -> 62.6%

Feature Matching Per-Kernel Breakdown (#704 base -> #735 R2)

  • fm-fast (442ebe38 -> 2f820096): 9.19 ms (301i / 73g) -> 7.27 ms (310i / 63g) (1.264x / -20.9%)
  • fm-scale (7804f45a -> 81269e52): 1.96 ms (188i / 55g) -> 1.87 ms (188i / 55g) (1.048x / -4.6%)

Exact head 5267549c68095aa7561d0951dbc5d63b0c13231b is unchanged and matches green mirror asahi CI (45048200756).

Assisted-by: LLM (Antigravity:Gemini 4 Neon)

@RyanTheTide

Copy link
Copy Markdown

Executed check at 5267549 merged onto aurora-wip f0ae30b. The merge has two conflicts, in agx_compile.c and test-shared-byte-offsets.cpp: the stack under this PR still carries the shared-phase CSE that #728 moved to its own file. I resolved them by hand (dropped the duplicated helpers, put back the nir_instr_set.h include, kept both test sets). Results with clang release+asserts, asahi+poly suites: merged 235/236, this head alone 216/216, aurora-wip alone 235/235.

  1. The stack needs a fix before it lands (not this PR's code): hk_gs_ray_query fails in the merged tree at test-hk-gs-ray-query.c:643, where the fence_mem_to_tex_agx count in the main GS is no longer 1. The same failure shows up with only agx: AGX3B W8/byte-convert/uniform-base codegen, capped speculative LICM, and invariant-if unswitching #704 merged onto aurora-wip, so it comes from the stack meeting aurora-wip's newer GS side-effect tests. It is not caused by this PR.
  2. The exit-phi bug is real and fixed. With the head's test file, the 1f2c12e code aborts with "NIR validation failed after agx_nir_opt_licm" in the early-break case (test-agx3-vision-opts.cpp:2281). Removing the bail at agx_nir_opt_licm.c:714-718 gives the same abort. At head, AGX3VisionOpts passes 31/31.
  3. I could not break it with 8 more shapes, run through agx_nir_opt_licm(64, true) with validation on: the loop as the last node of an if with a merge phi after it, a loop feeding a second loop, two exits whose live-outs are header phis, a live-out used only as an if condition, a 2-deep nest, the break in the else branch, an ALU chain in the break condition, and the induction variable as the live-out. All 8 transform and validate. I read the NIR for three of them: the guard is the right way round and the skip path gets the initial value.
  4. Test gap: 5 mutants of agx_nir_opt_licm.c, 3 killed (no exit-phi bail, no speculative gate, Phase 1 ignoring exit dominance), 2 survived. The survivors are a flipped guard (line 813, so the loop runs only when iteration 0 would break) and an undef instead of the initial value on the zero-trip side of the merge phi (line 835). Both are wrong code that still validates, and both pass because PureReadonlyLoopLicmHoist only counts loads. The Phase 1 dominance mutant is only caught by the early-break case's load count, not by Mode 0. Please have Mode 0 check the guard condition (inot of the break condition evaluated at entry) and the merge phi's else source (the header phi's preheader value).
  5. Earlier concerns are confirmed fixed by diff against agx: AGX3B W8/byte-convert/uniform-base codegen, capped speculative LICM, and invariant-if unswitching #704: agx_nir_unroll_runtime_loops.c and agx_nir_algebraic.py are unchanged (no bound == 8 specialization, no isub rule), and the read-only hoist only runs under fits_all && speculative (line 887). That flag is set only for AGX3B non-internal compute (agx_compile.c licm_speculative).

@RyanTheTide

RyanTheTide commented Nov 22, 2026 •

Copy link
Copy Markdown

The stack blocker reported in the last pass (hk_gs_ray_query at test-hk-gs-ray-query.c:643 on aurora-wip) comes from #704's preprocess unroll change, not from this PR. Root cause: #704 (comment). Fix: #738. aurora-wip + this PR + #738 passes the asahi and poly suites 236/236.

In agx_nir_opt_licm:
- Count pack_64_2x32_split of uniform preamble/constant halves as 0 GPR
  halves in the register-pressure estimator.
- When fits_all && speculative (AGX3B non-internal compute), add
  hoist_pure_readonly_loop to hoist budget-fitting loop-invariant pure
  loads from pure read-only loops (no stores, atomics, barriers, calls,
  or volatile/coherent memory accesses):
  * Phase 1 hoists exit-dominating invariant loads directly before loop.
  * Phase 2 evaluates the header exit condition at entry and wraps the
    loop in a zero-speculation guard before hoisting body-invariant
    loads, bailing cleanly whenever the loop successor block starts with
    a phi (e.g. early-break searches) so SSA dominance is preserved.

Adds unit tests in test-agx3-vision-opts.cpp:
- PackNarrowMuxTreeAndFoldIsub
- PackNarrowMuxTreePreNegateAndMaskPeel
- PureReadonlyLoopLicmHoist (including early-break exit-phi search and
  speculative == false negative controls).

Signed-off-by: DjDeveloperr <hey@djdev.me>
@DjDeveloperr
DjDeveloperr force-pushed the perf/agx3b-wave5-fm-power branch from 5267549 to 2db79e7 Compare November 22, 2026 19:03
@RyanTheTide

Copy link
Copy Markdown

Checked 2db79e7. The stray doc comment is gone, and the test now pins the zero-trip guard polarity (inot(0 >= cnt)) and the merge phi's sources (0 on the else path, the loop header phi on the then path), so a flipped guard or an undef init would fail. No other code change. My view stands: code fine, rows at head on J713/J615 still owed.

Assisted-by: LLM (Claude:Opus 5.5)

@DjDeveloperr

Copy link
Copy Markdown
Author

Pushed R3 at 2db79e7e482ba5ca8502f376491cfa7a4d15f8d4 (zero non-comment diff in runtime compiler code vs 5267549c68095aa7561d0951dbc5d63b0c13231b, so the exact-head G17P B1 verification row above remains bit-identical):

  1. AGX3VisionOpts.PureReadonlyLoopLicmHoist (Mode 0): Explicitly asserts that the Phase 2 zero-trip guard condition is inot(0 >= cnt) (killing the flipped-guard mutant) and that the post-guard merge phi takes the constant preheader initial value 0 on the else edge and the loop header phi on the then edge (killing the undef zero-trip value mutant).
  2. agx_nir_opt_licm.c: Removed the stray duplicated comment block above loop_is_pure_readonly.
  3. Validation: Assert-enabled (-Db_ndebug=false) meson test --suite asahi --suite poly: 170/170 PASS (0 fail); agent-policy.sh pr HEAD: clean.

Assisted-by: LLM (Antigravity:Gemini 4 Neon)

@DjDeveloperr

Copy link
Copy Markdown
Author

Clean-room M5 Pro (J714s / G17S B1 / AGX3C, Linux 7.3.0-m5-slc1, GCC 16.1.1, -Dbuildtype=release -Db_ndebug=true) verification on exact PR head 2db79e7e482ba5ca8502f376491cfa7a4d15f8d4 (MESA_SHADER_CACHE_DISABLE=1, ASAHI_M5_BRINGUP=1):

  • Build & mesa:asahi unit tests: libvulkan_asahi.so builds cleanly (sha256: cd60fefd154d..., byte-identical to R2 5267549c6809); all 144/144 other asahi test binaries PASS (0 fail). Note: under GCC 16.1.1 C++20, agx_tests fails to compile in stacked base commit 902bafb17 (src/asahi/compiler/test/test-agx3-vision-opts.cpp:383-386) because nir_load_agx(...) passes .format = ..., .access = ... in reverse declaration order of _nir_load_agx_indices (not introduced by #735; swapping .access before .format fixes GCC).
  • Vulkan CTS 1.4.7.1 (AGX3C compute / 8-bit / pack-unpack): 603/603 supported PASS (156 NotSupported, 0 fail):
    • mega12 compute/compiler slice: 522/522 (156 NotSupported, 0 fail)
    • dEQP-VK.spirv_assembly.instruction.compute.8bit_storage.*: 29/29 (0 fail)
    • dEQP-VK.glsl.builtin.function.pack_unpack.*: 52/52 (0 fail)
  • gb-gaussian checked (exact SSBO Gaussian 15-workload suite): 15/15 PASS
  • gpubench-vk sanity (CRC_BAD=0, 8/8 PASS):
    • compute.edge(harris, 1080p): d=1 390.62 us, d=4 270.27 us (crc=4cebadfc)
    • compute.edge(sobel, 1080p): d=1 268.34 us, d=4 150.60 us (crc=27c79e6d)
    • compute.stereo(disp=32): d=1 2884.62 us, d=4 2678.57 us (crc=7efb90b4)
    • compute.conv2d(gaussian, 1080p): d=1 438.60 us, d=4 334.82 us (crc=2d55a14d)
  • Kernel dmesg delta: 0 new lines / 0 GPU faults

AGX3C runtime and compute pack/unpack row is green at 2db79e7e482b.

Assisted-by: LLM (Google:Gemini 4 Neon)

@DjDeveloperr

Copy link
Copy Markdown
Author

Exact-head M4 (G16G) hardware verification at 2db79e7e482ba5ca8502f376491cfa7a4d15f8d4:

  • Hardware / Kernel / Driver: Apple M4 (G16G B0) (Mac mini J773g), 7.3.0-ARCH-m4prod19, Mesa 26.3.0-devel (git-2db79e7e48), Borealis, derived from Honeykrisp
  • Vulkan CTS (686 Pass / 0 Fail / 0 Crash / 0 Timeout / 1 NotSupported; end-of-run liveness rc 0; 0 kernel GPU / submit-path errors):
    • vk-mustpass-short: 87 Pass / 0 Fail / 0 NS (87 cases)
    • dEQP-VK.glsl.loops.*: 300 Pass / 0 Fail / 0 NS (300 of 624 avail)
    • dEQP-VK.ssbo.*: 299 Pass / 0 Fail / 1 NS (300 of 12,225 avail)
  • gpubench-vk (11/11 ok, 0 fail, 0 CRC fail):
    • compute.heavy (kind=alu): d=1: 788.64 us, d=4: 555.56 us
    • compute.light: d=1: 196.23 us, d=4: 92.22 us, d=8: 75.92 us, d=16: 56.20 us
    • render.heavy (kind=fill,res=1080p): d=1: 672.04 us, d=4: 377.07 us
    • compute.uber (d=1): divergent 748.50 us (crc=9963f56c, valid=True), uniform 424.45 us (crc=b022fbaf, valid=True), ilp 716.33 us (crc=19f35e30, valid=True)
  • System health: 0 kernel GPU dmesg errors / faults.

Assisted-by: LLM (Gemini:4 Neon)

@satchlj satchlj left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: MERGE

Checked: Full diff across src/asahi/compiler/agx_compile.c, src/asahi/compiler/agx_nir.h, src/asahi/compiler/agx_nir_opt_guard_selected_loads.c, src/asahi/compiler/agx_nir_opt_licm.c, and src/asahi/compiler/test/test-agx3-vision-opts.cpp, native assert-enabled build (-Db_ndebug=false), meson test --suite asahi, and live Vulkan CTS on Mac Studio M5 Max (J775c, T6050).

Notes:

  • agx_nir_opt_pack_narrow_mux_tree() restricts packing to power-of-two index bounds in {8, 16, 32} (iand, umod, umin, ubitfield_extract), selects contiguous vs strided packing to minimize preheader register pressure, peels redundant power-of-two masks only on iand(x, n - 1), and pre-complements packed words/constants via (255 - b) - (255 - c) == c - b with all four (byte_is_rhs, neg_is_true) polarity cases verified.
  • hoist_pure_readonly_loop() is strictly gated behind fits_all && speculative, requires loop_is_pure_readonly(loop) (no calls, writes, atomics, barriers, or volatile/coherent loads), checks loop_peak_after_hoist() <= budget, and wraps Phase 2 body hoists in a zero-speculation entry guard with merge phis for live-out header phis (bailing cleanly when after_loop has exit phis).
  • Note on pre-existing stacked base #704 (902bafb17): test-agx3-vision-opts.cpp:383-386 has out-of-order .format/.access designators under GCC 16 C++20 (not introduced by #735); #735's own new tests use valid declaration order and compile and pass cleanly under clang 23.1.4 (-Db_ndebug=false).
Evidence
  • Head audited: 2db79e7e482ba5ca8502f376491cfa7a4d15f8d4 (aurora-silicon/mesa#735)
  • Host build & unit tests on Mac Studio M5 Max (J775c, T6050): clang 23.1.4, -Db_ndebug=false, meson test --suite asahi: 146/146 PASS (0 fail).
  • Live Borealis Vulkan CTS on Mac Studio M5 Max (J775c, T6050), LD_DEBUG=libs confirmed /tmp/mesa-pr735-build/src/asahi/vulkan/libvulkan_asahi.so: dEQP-VK.compute.pipeline.basic.* 80/80 PASS (1 NotSupported, 0 fail), dEQP-VK.ssbo.layout.single_basic_type.std430.int* 2/2 PASS (0 fail), GPU_FAULT_DELTA=0.

@RyanTheTide

Copy link
Copy Markdown

Forward-merge onto aurora-wip is on hold. Several pieces of this stack overlap newer versions already on aurora-wip (#1060, #1075, #1083, #1093, #1104, #1183), so Dj needs to say which parts are still wanted. Details: #704 (comment)

@RyanTheTide

Copy link
Copy Markdown

@DjDeveloperr thanks for the conditional polarity optimization. #1351 carries it into the packed byte LUT pass on current aurora-wip. The exact J615 and J700 comparisons match the CPU reference and reduce GPU time on the long-loop fixture. Short and unchanged controls are within run variation. The linked benchmark has the shader source and paired timings.

@github-actions github-actions Bot added area:compiler Area from CODEOWNERS (bot) needs-template PR body lacks Tested or Risk (bot) ready-to-merge Meets the merge policy: merge it (bot) labels Dec 1, 2026
@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown

Merge readiness at 2db79e7e: ready to merge

Check Detail
CI at head ok no CI for this change (the hardware row is the gate)
Review ok approved by satchlj
Requested changes ok none
Hardware row at head ok comment at 2db79e7e
Conflicts ok none
PR text adopt when you next edit add a 'Tested:' line; a 'Risk:' line (door and Macs) (guide)

Areas: area:compiler
Merge: gh pr merge 735 --merge (Owners and Core through the bypass: add --admin).

Updated by pr-readiness on pushes, edits, reviews and comments, and on a schedule. Rules: merge policy · labels.

@DjDeveloperr

Copy link
Copy Markdown
Author

Closing as superseded. aurora-wip already has the mux-tree packing and the read-only loop-load hoisting from #1060 (agx_nir_opt_pack_byte_lut_select, agx_nir_hoist_readonly_loop_loads), and #1351 carried the byte-difference polarity folding. The stack base #704 is closed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:compiler Area from CODEOWNERS (bot) needs-template PR body lacks Tested or Risk (bot) ready-to-merge Meets the merge policy: merge it (bot)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants