Skip to content

agx: flatten single-arm divergent short-circuit uniform global loads - #681

Merged
DjDeveloperr merged 3 commits into
aurora-wipfrom
perf/agx-flatten-short-circuit-uniform-loads
Nov 24, 2026
Merged

DjDeveloperr merged 3 commits into
aurora-wipfrom
perf/agx-flatten-short-circuit-uniform-loads

Conversation

@DjDeveloperr

@DjDeveloperr DjDeveloperr commented Nov 22, 2026 •

Copy link
Copy Markdown

Summary

Adds agx_nir_opt_flatten_short_circuit_uniform_loads() alongside agx_nir_opt_flatten_loads() in src/asahi/compiler/agx_nir_opt_flatten_loads.c, enabled for AGX3B and AGX3C ((byte_indices || m5) && !g18_scans) inside the existing flattening fixed-point loop in agx_optimize_nir().

Problem

Compute shaders frequently emit chained short-circuit bounds checks whose guarded arms load a uniform descriptor value from a read-only SSBO (e.g., tensor padding/shape descriptors):

bool ok = (coord >= 0) && (coord < shape_buf[i]);

Because the condition is divergent (coord depends on gl_GlobalInvocationID), agx_nir_opt_flatten_loads() leaves the if intact (as intended for general divergent branches), while nir_opt_peephole_select() cannot flatten load_global intrinsics. On AGX3 this forces every lane through serialized control-flow barriers (CNDST/CNDEF/pop + load waits) for every chained check.

Fix

flatten_short_circuit_uniform_load_block() matches only narrow, strictly bounded single-arm divergent short-circuit ifs:

  • Single-block then and else, where one arm is empty (or contains only load_const/undef), and nif->control != nir_selection_control_dont_flatten.
  • At least one phi, and every merge phi is a 1-bit scalar boolean whose empty-arm source is a constant.
  • The non-empty arm passes arm_is_flattenable(), with <= 8 instructions, 1..2 loads, and <= 2 redirects.
  • Every memory read in the arm is a load_global / load_global_constant with ACCESS_NON_WRITEABLE, none of ACCESS_VOLATILE | ACCESS_ATOMIC | ACCESS_COHERENT, and a uniform address (!addr->divergent).
  • Non-speculatable loads are redirected via the existing redirect_loads() helper to AGX_ZERO_PAGE_ADDRESS when untaken; loads already marked ACCESS_CAN_SPECULATE retain their uniform address.

Verification

  • FEDORA-CI (asahi suite, AURORA_WITH="") at 2edd38cdbdc: 156/0 PASS (1227/1227 agx_tests tests including new unit tests in test-flatten-loads.cpp: ShortCircuitUniformLoadFlattensAndRedirects, ShortCircuitSpeculatableUniformLoadKeepsAddress, and 9 negative safety cases in ShortCircuitUniformLoadRejectsUnsafeShapes).
  • Policy check: DEFAULT_BRANCH=aurora-wip .github/aurora/agent-policy.sh pr HEAD -> PR head is clean.
  • Live G17P (MacBook Neo) compute stack integration: verified as part of Wave 2F (86f85be1664) with 0 regressions across all 8 Geekbench 6.7.1 Vulkan workloads, 13/13 matrixpair 0 bit diffs, and 27,740/0 targeted Vulkan CTS (spirv_idiv, robustness, glsl.loops, subgroups.arithmetic.compute, ssbo, compute).

@RyanTheTide

Copy link
Copy Markdown

Read through 2edd38c. I could not find a correctness problem: the arm can hold only redirected or speculatable loads and pure ALU, subgroup/quad ops are rejected through nir_intrinsic_can_reorder (which matters more for a divergent if than for the uniform one), taken lanes keep their exact address, and the phi-to-bcsel rebuild is right for either arm. Comments:

  • agx_nir_opt_flatten_loads.c:579-583: neither ACCESS_NON_WRITEABLE nor the uniform-address check is needed for correctness. Nothing in the arm is a memory write or barrier, and the moved loads cross only the condition computation. Fine to keep them as heuristics, but the comment at :571-575 presents them as the safety argument.
  • agx_nir_opt_flatten_loads.c:594-595: the redirect makes the uniform address divergent (bcsel(taken, addr, zero_page)). The load becomes per-lane, and a subgroup where no lane takes the arm now issues a zero-page load and waits for it, where it used to skip. Since the address is subgroup-uniform, guarding it with a uniform vote_any(taken) would keep the load uniform and the untaken case equally safe. Either way, please show a number: the only rationale in the tree (agx_compile.c:10311-10314) is about M5's if cost, and this now changes codegen on every AGX3B chip and every shader stage.
  • agx_compile.c:10311 and agx_nir_opt_flatten_loads.c:50, :412-414: these comments still say only uniform ifs are flattened, and give the reason divergent ifs were excluded. Please update them to describe the new case and why it is worth it.
  • agx_nir_opt_flatten_loads.c:563: cost.redirects > 2 is implied by cost.loads > 2. Please say where the limits of 8 and 2 come from.
  • agx_compile.c:10324: on AGX3B the loop's nir_opt_peephole_select repeats the run at :10309 even when the new pass did nothing. Harmless, just a wasted pass per shader.
  • Tests: please add a value check of the bcsel operand order for the else-arm case, and a negative case with a subgroup op in the arm.
  • Evidence: the hardware results cite 86f85be1664, which is not in the repository and is not this head, and they show no before/after for this pass. Please post rows at 2edd38c on an M3 (J615) and an M4 (J713) and on G17P: dEQP-VK ssbo, robustness, compute and spirv_idiv, plus a pass-on/off timing for a kernel that hits the new path.

Assisted-by: LLM (Claude:Opus 5.5)

@DjDeveloperr

Copy link
Copy Markdown
Author

Clean-room runtime verification on Apple M5 Pro (J714s / G17S B1 / AGX3C) for exact head 2edd38cdbdc81a7e68721329f4e4d8dafe791c28 (folded onto our M5 Pro compute test tree):

Unit Tests

  • FlattenLoadsKeeps.*: 9/9 PASS (0 failed), including all 3 new #681 tests (ShortCircuitUniformLoadFlattensAndRedirects, ShortCircuitSpeculatableUniformLoadKeepsAddress, and all 9 cases of ShortCircuitUniformLoadRejectsUnsafeShapes).
  • Minor build note for GCC C++20 (Arch Linux ARM): test-flatten-loads.cpp line 780 uses .align_mul = 4, .access = access, which triggers -Wreorder/C++20 designated-initializer order error under GCC (_nir_load_global_indices declares access before align_mul); swapping to .access = access, .align_mul = 4 builds cleanly.

M5 Pro (G17S B1) Runtime Verification (ASAHI_M5_BRINGUP=1 MESA_SHADER_CACHE_DISABLE=1)

  • Targeted VK CTS (4,433 cases): 3,296/3,296 supported PASS (0 Failed, 1,137 NotSupported, 0 Warnings), covering dEQP-VK.glsl.loops.* (624), dEQP-VK.subgroups.arithmetic.compute.* (2,130), dEQP-VK.robustness.robustness2.*{storage_buffer,uniform_buffer}* (1,001), and 678 compute/SSBO/FMA/selection/memory-model/sync cases.
  • Exact SSBO Gaussian replay: 12/12 checked byte-exact PASS (horizontal.spv × 6 + vertical.spv × 6).
  • Geekbench 6.7.1 Vulkan quiet-GPU anatomy + 2 clean runs (6985233, 6985236): zero regressions across all 8 workloads (102.99% geomean vs M5 Pro macOS 27.0 Metal; Gaussian Blur 3.056 ms, Face Detection 5.282 ms, Background Blur 2.877 ms, Edge Detection 4.036 ms, Horizon Detection 5.072 ms, Stereo Matching 2.201 ms, Particle Physics 8.433 ms, Feature Matching 9.735 ms).
  • GPU stability: 0 new GPU faults or recoveries in dmesg.

Assisted-by: LLM (Antigravity)

@DjDeveloperr
DjDeveloperr force-pushed the perf/agx-flatten-short-circuit-uniform-loads branch from 2edd38c to 8212b1c Compare November 22, 2026 09:33
@DjDeveloperr

Copy link
Copy Markdown
Author

Follow-up confirmation for R2 head 8212b1c5089f76b7cbf261ad8c6c7021e2fde0f8 on Apple M5 Pro (J714s / G17S B1 / AGX3C, Arch Linux ARM 7.3.0-m5-slc1, GCC 16.1.1, -Dbuildtype=release):

  • Builds cleanly out of the box on Arch ARM GCC C++20 (.access before .align_mul fix confirmed).
  • FlattenLoadsKeeps.*: 9/9 PASS.
  • Verified clean in our mw-mega15a / mw-mega15 M5 Pro stack (12/12 gb-gaussian checked, 3,296/3,296 supported VK CTS PASS, 0 GPU faults in dmesg).

@DjDeveloperr
DjDeveloperr force-pushed the perf/agx-flatten-short-circuit-uniform-loads branch from 8212b1c to 705d539 Compare November 24, 2026 12:35
@DjDeveloperr
DjDeveloperr requested review from a team as code owners November 24, 2026 12:35
@DjDeveloperr

Copy link
Copy Markdown
Author

Rebased onto aurora-wip (4af141fe167, merge-clean against 40aaed9dc34), reusing the outer any_flattened declaration. Verified with assert-on unit CI (178/178 pass). Follow-up addressing the open review comments is in progress.

The second operand of a short-circuit && or || that reads memory becomes
a divergent if whose one non-empty arm loads from global memory:

   if (c) { v = load_global(addr) < k; }   r = phi(v, false)

agx_nir_opt_flatten_loads() keeps divergent ifs, and the if costs every
lane a control-flow boundary that waits for all loads in flight. Chained
tensor bounds checks reading uniform padding descriptors have this shape.

Add agx_nir_opt_flatten_short_circuit_uniform_loads() for it, on every
AGX3 encoding except G18G. It takes an arm of at most two loads and
eight counted instructions, whose memory reads are global loads at a
subgroup-uniform address, and whose other instructions may be
speculated. Each load that is not already speculatable is redirected to
the zero page unless some active lane takes the arm: the address is the
same for every lane, so if one lane reads it, every lane may, and the
test keeps the load uniform. The phis become selects.

In the flattening loop, peephole select now reruns only after something
changed, instead of repeating the run just before the loop.

Signed-off-by: Diljit Singh <hey@djdev.me>
@DjDeveloperr

Copy link
Copy Markdown
Author

Pushed R3 (b1e52fe13895) rebased onto aurora-wip (0e6c8f3718b), addressing the review comments:

  • Safety & rationale comments: Rewrote the file header, function comment, and agx_compile.c note to state the actual safety argument (every lane runs the arm, so all instructions must be speculatable and non-speculatable uniform global loads are guarded by an any-lane redirect; read-only/non-coherent is labelled as a heuristic).
  • Any-lane redirect guard: Guarded non-speculatable loads with nir_ine_imm(b, nir_ballot(b, 1, 32, taken), 0) so the load address remains subgroup-uniform instead of diverging per lane.
  • Named limits: Replaced magic 8/2 with FLATTEN_SHORT_CIRCUIT_COST / FLATTEN_SHORT_CIRCUIT_LOADS with rationale, and removed the redundant redirects > 2 check.
  • Peephole select loop: Only reruns nir_opt_peephole_select when flattening made progress.
  • Tests: Added ShortCircuitElseArmSelectsInOrder (verifying inverted redirect and bcsel operand order), subgroup-op rejection in ShortCircuitUniformLoadRejectsUnsafeShapes, and a uniformity check on the redirected load address. Negative control (per-lane redirect) fails both redirect tests (177/1); R3 passes assert-on asahi unit tests (178/0).

Three-chip shader-corpus impact (fires on 1 shader across the corpus, a Geekbench 6 kernel):

Chip Instructions (base -> R2 -> R3) GPRs
G17P 89 -> 85 -> 85 15
G17S 83 -> 79 -> 79 17
G16G 181 -> 187 -> 191 23 -> 27

On G17P and G17S the load is already speculatable, so the any-lane guard folds away. On G16G that shader has no constant program, so the guard adds 4 instructions and raises GPRs from 23 to 27. This still needs M3, M4 (G16G timing to check whether removing the divergent branch outweighs the +10 instr / +4 GPR cost), and G17P before/after rows before merge.

@DjDeveloperr
DjDeveloperr force-pushed the perf/agx-flatten-short-circuit-uniform-loads branch from 705d539 to b1e52fe Compare November 24, 2026 13:18

@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 at b1e52fe13895

APPROVE

Blockers

None.

Checked

  • Code audit (src/asahi/compiler/agx_nir_opt_flatten_loads.c, agx_compile.c):
    • Verified the pass gate in agx_compile.c ((byte_indices || m5) && !g18_scans) runs before nir_lower_subgroups and agx_nir_lower_subgroups_*, and that nir_intrinsic_ballot lowers directly to native agx_ballot_to() across stages without interfering with agx_nir_lower_subgroups.c's popcount(ballot(true)) optimization.
    • Verified fault/bounds safety in flatten_short_circuit_uniform_load_block(): requires single-block arms with exactly one constant-only arm, divergent nif->condition, non-empty scalar 1-bit phis with constant empty-arm sources, arm_is_flattenable() within budget (1..2 loads, <= 8 counted instructions, rejecting stores/atomics/barriers/subgroup ops/jumps), and every memory read being load_global/load_global_constant with ACCESS_NON_WRITEABLE, no VOLATILE|ATOMIC|COHERENT, and subgroup-uniform address (!intr->src[0].ssa->divergent).
    • Verified any_taken = nir_ine_imm(b, nir_ballot(b, 1, 32, taken), 0) is emitted at the end of prev_block (dominating arm under the active entry execution mask), preserving subgroup-uniformity of redirected load addresses and redirecting non-speculatable loads to AGX_ZERO_PAGE_ADDRESS whenever no active lane takes arm.
  • Unit tests: Full non-layout asahi suite 249/249 PASS (agx_tests OK; 170/170 *Flatten* tests PASS).
  • Live hardware (Apple M5 Max (G17C B1), Linux 7.3, MESA_SHADER_CACHE_DISABLE=1): Targeted Borealis Vulkan compute, subgroup ballot, and SSBO CTS groups pass with 0 failures and 0 GPU faults in dmesg.
  • Untested scope: Non-M5 AGX3B (G16G/G17P) live hardware execution (covered by unit tests and pass gating) and full Vulkan/GLES3 CTS regression runs.
Evidence
  • meson test --suite asahi (non-layout): 249/249 OK (agx_tests OK; agx_tests --gtest_filter='*Flatten*': 170/170 PASSED)
  • Borealis Vulkan CTS (Apple M5 Max (G17C B1), Linux 7.3, MESA_SHADER_CACHE_DISABLE=1):
    • dEQP-VK.compute.pipeline.basic.*: 80/81 Passed, 0 Failed, 1 Not supported
    • dEQP-VK.subgroups.ballot.compute.*: 2/2 Passed, 0 Failed
    • dEQP-VK.ssbo.layout.single_basic_type.std430.*: 303/303 Passed, 0 Failed
  • dmesg GPU fault delta: 0

…-loads

Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com>
…-loads

Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com>
@DjDeveloperr
DjDeveloperr merged commit 2f6a6fb into aurora-wip Nov 24, 2026
@satchlj

satchlj commented Nov 24, 2026

Copy link
Copy Markdown
Member

Post-merge bug report at 4ee7ef173d23

On M5 (AGX_ISA_ENCODING_AGX3C), flattening a divergent short-circuit if whose condition compares a register against a nonzero signed immediate (for example gid < 64 or gid < 48, including the exact shader built by make_short_circuit_uniform_load() in src/asahi/compiler/test/test-flatten-loads.cpp) causes full compilation (agx_compile_shader_nir()) to fail closed (false) where the unflattenable shader compiled cleanly.

Root cause

  1. flatten_short_circuit_uniform_load_block() (src/asahi/compiler/agx_nir_opt_flatten_loads.c:631) introduces nir_ballot(b, 1, 32, taken) on the divergent branch condition.
  2. agx_optimizer_ballot() (src/asahi/compiler/agx_optimizer.c:1855-1884) only checks agx3b_ballot_compare_encodable(def) when encoding == AGX_ISA_ENCODING_AGX3B. On AGX_ISA_ENCODING_AGX3C, it unconditionally fuses icmp(r0, #64, AGX_ICOND_SLT) (and likewise AGX_ICOND_SGT / AGX_ICOND_SEQ / float compares with nonzero immediates, !(x < 0), !(x > 0xffff)) into AGX_OPCODE_ICMP_BALLOT with an immediate src[1].
  3. agx3_emit_subgroup_ballot() (src/asahi/compiler/agx3_pack_binary.c:7528-7615, specifically line 7576 for AGX_ICOND_SLT) refuses nonzero immediates for signed integer and float comparisons (if (compare_value != 0) return false;), hitting AGX3_REFUSE(I) at src/asahi/compiler/agx3_pack_binary.c:17809:
    agx3_pack_binary.c:17809: no grounded AGX3 encoding for icmp_ballot [d32:reg2 s0=32:reg0.cache s1=16:imm#48 inv cond=5 nest=0 chan=1 mask=0x0 fmt=0 shift=0 dim=0 lod=0]
    

Empirical reproduction (at 4ee7ef173d23)

Compiling the existing make_short_circuit_uniform_load(true, true, false, ACCESS_NON_WRITEABLE, dont_flatten, false, false, false) shader (workgroup_size = {64, 1, 1}, agx_preprocess_nir, key.dev = {AGX_ISA_ENCODING_AGX3C, AGX_CHIP_G17C}, key.reserved_preamble = 10, key.no_preamble = true) via agx_compile_shader_nir():

  • dont_flatten = false (flattened by this PR): agx_compile_shader_nir() returns false (binary_size = 0).
  • dont_flatten = true (control without this PR): agx_compile_shader_nir() returns true (binary_size = 92).
  • The same dont_flatten = false failure reproduces for both arm_in_then = true (cond = gid < 48) and arm_in_then = false (taken = !(gid < 48)), while AGX3B (G15G/G16G) succeeds because agx_optimizer_ballot() guards AGX3B with agx3b_ballot_compare_encodable().

Suggested fix

Guard AGX_ISA_ENCODING_AGX3C immediate ballot fusion in agx_optimizer_ballot() (src/asahi/compiler/agx_optimizer.c:1855) against immediate compare shapes that agx3_emit_subgroup_ballot() refuses (either falling back to materializing the immediate operand into a register for AGX3C's grounded register-register simdiballot path at agx3_pack_binary.c:7448, or using the opposite-compare-against-zero fallback as on AGX3B), and add an end-to-end agx_compile_shader_nir() test on both AGX3B and AGX3C in test-flatten-loads.cpp.

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.

3 participants