Skip to content

s16x16x4 packed type is ~15x slower than scalar on the simd_noop fallback (RP2350/Cortex-M33) #4216

Closed

Description

@zackees

Measurement

testSimdBenchmark on RP2350W 2DCB876B587EA334, 10000 iterations, times in µs (lower is better):

op float s16x16 u16x16 s8x8 s16x16x4 (packed)
mul 738 984 980 891 11568
sub 653 570 568 821 10434

Reproduce with bash autoresearch rp2350w --simd.

The comparison is like-for-like

Every helper in examples/AutoResearch/AutoResearchSimd.h processes four lanes per iteration, so this is not a 1-lane-vs-4-lane artefact:

  • benchFloat4 — four scalar float ops
  • benchS16x16_4 — four scalar fl::s16x16 ops
  • benchSimd4 — one packed fl::s16x16x4 op

Same work, ~15× the time.

Why this is a bug rather than "no SIMD on this chip"

RP2350 is Cortex-M33 without __ARM_FEATURE_DSP, so src/platforms/simd.h falls through to platforms/shared/simd_noop.hpp:

#if   x86/x64                -> simd_x86.hpp
#elif FL_IS_ESP32            -> simd_esp32.hpp
#elif __ARM_FEATURE_DSP == 1 -> simd_arm_dsp.hpp
#else                        -> simd_noop.hpp   // "No SIMD support - use scalar fallback"

A scalar fallback should cost approximately what the equivalent scalar code costs. Failing to accelerate is expected and fine. Being 15× slower than the code it falls back to is not — it means reaching for the portable vector type silently costs an order of magnitude on every platform that lands in this branch.

That branch is not RP-specific: it is the default for every ARM part without the DSP extension, and for any platform not otherwise matched.

Hypothesis — not verified

The fallback vector is:

struct FL_ALIGNAS(16) simd_u32x4 { u32 data[4]; };

16 bytes. Under AAPCS a 16-byte aggregate is not returned in registers, so each operator likely returns through memory, and a dependent chain like the benchmark's (a = op(a, b); b = a + bump;) would round-trip the stack every iteration.

I have not read the generated assembly, so I am offering this as a plausible mechanism consistent with the measurement, not as a diagnosis. Anyone picking this up should confirm against the disassembly before acting on it.

Severity

Low-to-moderate, and deliberately not inflated:

  • s16x16x4 appears nowhere outside src/fl/math/ — no driver or pipeline selects it, so nothing regresses for users who never opt in.
  • The cost is paid only by code that deliberately reaches for the packed type expecting a win, and instead takes a 15× loss.

So this is a correctness-of-expectation problem in an opt-in API, not a live performance regression in the rendering path.

Suggested direction

Either make the no-op fallback compile to genuinely scalar-equivalent code (so the portable type is safe to use everywhere), or have the packed types degrade to the plain scalar implementations when no vector backend is present, so s16x16x4 is never worse than s16x16.

Found while closing the SIMD compute gate on #3899 — the gate itself passes (85/85 correctness tests).

🤖 Generated with Claude Code

https://claude.ai/code/session_01KkufoNxfnNRU9psT3R9F51

Activity

  1. zackees commented on Sep 8, 2026

    @zackees
    MemberAuthor

    Narrowed considerably. Three candidate causes eliminated, including the one I originally proposed, and a much better-supported explanation found.

    Eliminated

    1. The ABI/over-alignment theory I filed — refuted by measurement.

    I hypothesised that the 16-byte simd_u32x4 aggregate was returned through memory. simd_noop.hpp declares all four vector types FL_ALIGNAS(16), which serves no purpose in a scalar fallback and can stop a four-word aggregate living in registers. I removed the alignment and re-measured on RP2350W:

    before   mul simd_us = 11568
    after    mul simd_us = 11659
    

    No change. Not the cause. I have not shipped that change.

    2. FL_IRAM preventing inlining — refuted by inspection.

    Every function in simd_noop.hpp is declared FASTLED_FORCE_INLINE FL_IRAM, and a section attribute can defeat inlining. But FL_IRAM is defined only for stm32, esp32 and esp8266; fl/stl/compiler_control.h:521 makes it a no-op everywhere else, RP included.

    3. Different arithmetic — refuted by inspection.

    s16x16::operator* has a RISC-V inline-asm fast path, but it is gated on #if defined(__riscv) && (__riscv_xlen == 32). RP2350 is Cortex-M33, so it takes the portable #else:

    (static_cast<i64>(mValue) * b.mValue) >> FRAC_BITS

    mulhi_i32_4 does exactly the same (i64)a * b >> 16 per lane. Identical arithmetic, 4 lanes each way. So the gap is not in the math.

    Leading explanation: -Os

    The RP2350W firmware is built with -Os (cc_flags/cxx_flags in .build/pio/rp2350w/build_info.json).

    FASTLED_FORCE_INLINE still inlines, but -Os does not prioritise the scalar-replacement and copy-elision that would keep the aggregates in registers. Every packed operation passes two 16-byte structs by value, builds a third, and returns it — mulhi_i32_4(raw, b.raw) then from_raw(...). At -Os that is real stack traffic on each op. The scalar path manipulates four plain i32 values, which stay in registers with no optimisation effort at all.

    That accounts for a ~12x gap on identical arithmetic, and for why removing the alignment changed nothing: the copies are inherent to the by-value API, not to how the type is aligned.

    Not yet confirmed by disassembly — that is the obvious next step and would settle it. I am flagging the eliminations so the next person does not repeat them.

    Implication

    If this is right, the fix is not a tweak to the fallback's internals. Either that code needs to be compiled at a higher optimisation level, or the packed operations need an API that does not pass and return aggregates by value (in-place operations on references) so -Os has nothing to elide.

    Severity is unchanged and still low: s16x16x4 appears nowhere outside src/fl/math/, so no driver or pipeline selects it.

  2. zackees commented on Sep 8, 2026

    @zackees
    MemberAuthor

    Fourth hypothesis tested and refuted — including the -Os explanation I proposed in my previous comment. Correcting it here.

    -Os is not the cause

    I forced -O2 on the benchmark translation unit with #pragma GCC optimize("O2") (the fallback's operations are FASTLED_FORCE_INLINE, so they optimise as part of the enclosing function) and re-measured on RP2350W:

    op path -Os -O2 change
    float 743 487 −34%
    s16x16 scalar 977 733 −25%
    s8x8 903 728 −19%
    s16x16x4 packed 11659 10352 −11%

    Everything got faster, but the packed type improved least. The ratio against scalar s16x16 went from ~11.9x to ~14.1x — it got relatively worse. Raising the optimisation level does not close the gap, so my previous comment's conclusion was wrong.

    Refined explanation

    What survives all four eliminations is the shape of the data, not the arithmetic, the alignment, the section attributes or the optimisation level:

    struct simd_u32x4 { u32 data[4]; };
    
    FASTLED_FORCE_INLINE simd_u32x4 mulhi_i32_4(simd_u32x4 a, simd_u32x4 b) {
        simd_u32x4 result;
        for (int i = 0; i < 4; ++i) { ... result.data[i] = ...; }
        return result;
    }

    The lanes live in a u32[4] array member, accessed through an indexed loop. The scalar comparison holds four independent named i32 values that a register allocator places trivially. An array inside a struct is far more likely to be materialised in memory and indexed, so each lane costs a load and a store that the scalar version never pays — and that cost is proportional to the work, which is why more optimisation helps it least.

    This is consistent with every measurement so far, and it is the reason the alignment change did nothing: the traffic comes from indexing an array, not from how that array is aligned.

    Still not disassembly-confirmed. That remains the decisive next step, and I have not done it.

    Eliminated so far, so nobody repeats them

    1. 16-byte over-alignment forcing memory return — measured, no change (11568 → 11659).
    2. FL_IRAM defeating inlining — it is a no-op outside stm32/esp32/esp8266.
    3. Different arithmetic — the RISC-V asm fast path is gated on __riscv; ARM and the fallback both compute (i64)a * b >> 16 per lane.
    4. -Os — forcing -O2 improves the packed path least of all four representations.

    Severity unchanged and still low: s16x16x4 appears nowhere outside src/fl/math/, so nothing selects it automatically.

  3. zackees commented on Sep 8, 2026

    @zackees
    MemberAuthor

    Settled by disassembly

    Disassembled benchSimd4<OpMul> from the RP2350W build (arm-none-eabi-objdump -d, release object, -Os). The mechanism is now confirmed rather than inferred.

    The per-lane multiply loop:

    5a:  ldr.w  r3, [r1], #4       ; load lane a from stack
    5e:  ldr.w  r2, [r9], #4       ; load lane b from stack
    64:  smull  r3, r2, r3, r2     ; the actual arithmetic — one instruction
    68:  mov.w  r3, r3, lsr #16
    6c:  orr.w  r3, r3, r2, lsl #16
    70:  str.w  r3, [r0], #4       ; store lane back to stack
    74:  bne.n  5a                 ; loop — NOT unrolled

    Six instructions and a taken branch per lane, of which one is the multiply. The lanes are loaded from and stored back to the stack every operation because they live in a u32 data[4] array member, and the trip-4 loop is not unrolled.

    Whole-struct copies between stack slots, immediately after:

    76:  ldmia.w r4, {r0, r1, r2, r3}
    7a:  stmia.w r7, {r0, r1, r2, r3}
    7e:  vldr    d6, [r4, #16]
    82:  vldr    d7, [r4, #24]
    86:  stmia.w ip, {r0, r1, r2, r3}
    8e:  vstr    d6, [r4, #32]
    92:  vstr    d7, [r4, #40]

    r4, r7, ip and lr are four distinct 16-byte stack buffers. That is the by-value aggregate parameter/return traffic, materialised.

    Frame size and runtime alignment:

    6:   sub    sp, #72             ; 72-byte frame
    2e:  add.w  r4, sp, #15
    32:  bic.w  r4, r4, #15         ; enforce FL_ALIGNAS(16) at runtime

    72 bytes of stack for what is nominally four u32s of state, plus runtime alignment fixup on every call.

    Why each earlier hypothesis failed, in light of this

    • Alignment: real (visible at 2e/32) but a small constant, not the 12x — which is why removing it measured no change.
    • -O2: cannot help much, because the loads and stores are semantically required once the lanes live in an array in memory. It improved the packed path 11% against 25-34% for the scalar paths, exactly as this predicts.
    • Arithmetic: confirmed identical — a single smull per lane, the same operation the scalar path performs.

    Fix direction

    The problem is the representation, not the operations. A scalar fallback whose lanes are an indexed array cannot stay in registers. Named members (u32 x, y, z, w) with explicitly unrolled operations would let the register allocator keep all four lanes live, which is what the scalar s16x16 comparison already does — and it is the reason it is 12x faster while executing the same smull.

    That is a contained change to simd_noop.hpp alone, though it touches every operation in that file.

    Correction log for this issue

    I proposed four causes before disassembling; three were wrong and I have corrected each above:

    1. ABI return-by-memory from over-alignment — refuted by measurement.
    2. FL_IRAM blocking inlining — refuted, it is a no-op outside stm32/esp32/esp8266.
    3. Different arithmetic — refuted, both compute (i64)a * b >> 16.
    4. -Os — refuted, forcing -O2 helped the packed path least.

    The disassembly should have come first.

  4. zackees commented on Sep 8, 2026

    @zackees
    MemberAuthor

    Tried the cheap fix. It does not work, and the disassembly says why.

    Before proposing the invasive change, I tested whether simply unrolling the trip-4 lane loops would recover the performance — same struct layout, same API, same semantics, only the induction variable removed. That would have been a ~16-function, low-risk diff.

    Unrolled all 16 simd_u32x4 lane loops in simd_noop.hpp (each lane body scoped in braces, since several declare locals). Measured on RP2350W:

    before unroll   mul simd_us = 11659
    after unroll    mul simd_us = 11659
    

    Identical. Disassembling the result shows why:

    9a:  smull  r3, r9, r9, r3
    9e:  lsrs   r3, r3, #16
    a0:  orr.w  r3, r3, r9, lsl #16
    a4:  cmp    r2, #4          ; <-- still a trip-4 loop

    The compiler re-rolled it. -Os optimises for size, and rolling four identical bodies back into a loop is smaller. Source-level unrolling cannot survive that, so this avenue is closed — noting it so nobody else spends the attempt.

    What that leaves

    The lanes have to stop living in an indexed array. Named members (u32 x, y, z, w) are what would let the register allocator keep them live, which is exactly what the scalar s16x16 comparison does while executing the identical smull.

    That is not a small change: simd_noop.hpp is 591 lines with 66 operations and 80 data[...] accesses, essentially all of which would be touched.

    Why I have not made that change

    Weighing it honestly:

    • Blast radius is wide. This file is the fallback for every platform without a SIMD backend — AVR, SAMD, nRF52, RP, ARM parts without the DSP extension. I can build and run on RP and on the host; I cannot test most of the affected targets.
    • Benefit is narrow. s16x16x4 appears nowhere outside src/fl/math/, so no driver or pipeline selects it. Nothing regresses today for anyone who does not deliberately opt in.

    A 591-line rewrite of a shared fallback, verifiable on two of many targets, to speed up an API nothing currently calls, is not a trade I should make unilaterally on an unattended bench. Flagging it as the known fix with the cost stated, for a maintainer to weigh.

    If it is wanted, the mechanical part is straightforward and the on-device --simd benchmark gives an immediate before/after.

  5. zackees commented on Sep 10, 2026

    @zackees
    MemberAuthor

    The reason not to do the rewrite was better than it looked — and #4285 removes it

    Your last comment declined the rewrite on this:

    Blast radius is wide. This file is the fallback for every platform without a SIMD backend […] I can build and run on RP and on the host; I cannot test most of the affected targets.

    Correct, and stronger than stated: the fallback is not tested on the host either. platforms/simd.h dispatches on architecture macros with no override, so an x86 host compiles simd_x86.hpp and never reaches simd_noop.hpp. Proven rather than inferred — an #error at the top of the file does not fire anywhere in the test build.

    So the 66 operations shipped to AVR, ESP8266, Cortex-M0/M0+/M3, WASM and RP2350 had no host coverage at all, and a 591-line rewrite of them had nothing to check it.

    #4285 gives it one, and the oracle found three bugs on the way

    The fallback's namespace is now a macro. That lets a test include it beside the host's real backend and check all 66 operations against each other — which immediately turned up three where x86 answers differently from every other backend:

    operation every other backend x86
    avg_u8_16 (a+b)>>1 — truncates _mm_avg_epu8 → rounds
    narrow_u16_to_u8 unsigned clamp: 65280 → 255 signed-saturates: 65280 → 0
    narrow_u16x16_to_u8 as above as above, AVX2

    The API has two averages and they are different operations; x86 returned the same intrinsic for both. What settles it is that simd_x86.hpp's own non-SSE2 path already implemented both the other way — the file gave two different answers depending on whether SSE2 was available.

    Neither is reachable today, and I am not claiming a live bug: avg_u8_16 has no caller in src/, and narrow_u16_to_u8's only caller is blur.cpp.hpp, where the value is at most 255 before it narrows. Contract bugs, fixed, with the differential cases pinning them.

    What this means for the decision here

    It does not make the decision. The two things you weighed are unchanged in kind:

    • benefit is still narrow — s16x16x4 is still selected by nothing outside src/fl/math/;
    • blast radius is still wide — it is still the fallback for every unmatched part.

    What changed is the third factor, the one that made it a bad unilateral trade: the rewrite is no longer unverifiable. All 80 data[...] accesses now sit behind cases that compare each operation to an independent implementation, so it becomes a mechanical refactor with a check, and the on-device --simd benchmark still gives the before/after you described.

    I have not done the rewrite. It remains yours to want.

  6. zackees commented on Sep 10, 2026

    @zackees
    MemberAuthor

    Reproduced unchanged on current master — and division is worse than the packed type

    Re-ran bash autoresearch rp2350w --simd on the same board (2DCB876B587EA334) against master 5ff2d8fd21, to check whether anything merged since had moved these numbers.

    The reported defect is unchanged

    op float s16x16 u16x16 s8x8 s16x16x4 (packed) ratio
    add 697 563 571 733 10758 15.4x
    mul 739 974 975 890 11621 15.7x
    sub 652 578 568 810 10430 16.0x

    Against the figures in the issue body — mul 11568, sub 10434 — these are the same measurement to within noise (11621 and 10430). Nothing in the intervening merges touched it, and add behaves identically to mul/sub, which the original table did not include.

    Division is a separate and larger anomaly

    The same run also benchmarks div, which the issue does not cover:

    op float s8x8 u16x16 s16x16
    div 1806 1223 40655 57649
    • s16x16 division costs 31.9x float and 47x s8x8
    • u16x16 division costs 22.5x float
    • s8x8 division is faster than float (0.7x)

    So the 8-bit fixed-point type divides faster than float, while the 16-bit types cost thirty to fifty times as much for the same operation. That is a different shape from the packed-type problem: it is not the simd_noop fallback path, and it affects the plain scalar s16x16/u16x16 types that a user would reach for first.

    Why I am reporting it here rather than opening a new issue

    It may share a root cause with the packed case — both are "a portable fixed-point type costs an order of magnitude more than the scalar code it is meant to stand in for" — and whoever picks up the packed rewrite will be in the right code to judge that. If they turn out to be unrelated, this half is worth splitting out; I do not have enough to say which.

    Reproduce either with bash autoresearch rp2350w --simd; the timings arrive in the testSimdBenchmark payload.

  7. zackees commented on Sep 10, 2026

    @zackees
    MemberAuthor

    Root cause of the division half: it compiles to a 64-bit software divide

    Traced the div anomaly I reported above to source. It is not the simd_noop fallback — it is the width of the intermediate.

    src/fl/math/fixed_point/s16x16.h:88

    constexpr FASTLED_FORCE_INLINE s16x16 operator/(s16x16 b) const FL_NO_EXCEPT {
        return from_raw(static_cast<i32>(
            (static_cast<i64>(mValue) * (static_cast<i64>(SCALE))) / b.mValue));
    }

    That is an i64 / i32 division. Cortex-M33 has a 32-bit hardware divider (SDIV/UDIV) and no 64-bit divide, so this lowers to __aeabi_ldivmod — a software routine costing hundreds of cycles.

    src/fl/math/fixed_point/s12x4.h:61, the 8-bit family, for contrast:

    (static_cast<i32>(mValue) * (SCALE)) / b.mValue

    i32 / i16 — one SDIV instruction.

    The same shape appears in the shared base.h:73 fallback, so any type whose intermediate_type is 64-bit divides in software.

    It predicts the measurements exactly

    op cost mechanism
    s8x8 div 1223 µs 32-bit hardware SDIV
    float div 1806 µs single-precision FPU
    u16x16 div 40655 µs 64-bit software divide, unsigned
    s16x16 div 57649 µs 64-bit software divide, signed

    Signed costing more than unsigned (57649 vs 40655) is the sign-handling in __aeabi_ldivmod versus __aeabi_uldivmod, which is what you would expect if this is the mechanism. And it explains the otherwise odd result that the 8-bit fixed-point type divides faster than float: it gets the hardware divider while float goes through the FPU, and the 16-bit types get neither.

    Note on what a fix would involve

    The general 16.16 case genuinely needs 48 bits of numerator, so a plain 32-bit divide is not a drop-in. But a 64/32→32 division specialised on the hardware divider is far cheaper than the generic __aeabi_ldivmod, and the common case where the operands are small enough for the result to fit in 32 bits can take a single SDIV. I have not attempted either — flagging the mechanism so whoever does is not starting from the benchmark.

    This may or may not share a root cause with the packed s16x16x4 problem in the issue title. This half is a 64-bit intermediate on a chip without a 64-bit divider; the packed half is a 15x overhead on simd_noop, which is a different mechanism. They may want splitting.

  8. moved this from Triage to Done in FastLED Trackeron Sep 10, 2026
  9. zackees commented on Sep 10, 2026

    @zackees
    MemberAuthor

    Device verification of #4299 on the attached RP2350

    #4299 landed while I was measuring, so the before/after here is on real silicon rather than instruction counts. Same board (2DCB876B587EA334), bash autoresearch rp2350 --simd, 10000 iterations, µs.

    op before (pre-#4299) after (master d7d279ea14) scalar float was now
    add 9975 529 694 14.4x slower 0.76x
    sub 9743 541 693 15.9x slower 0.78x
    mul 10890 842 605 15.6x slower 1.39x

    85/85 device SIMD tests pass on both sides, so the win is not bought with behaviour. The packed type is now at or below scalar float on add and sub, and within 1.4x on mul — which is the outcome this issue was opened for.

    Two details worth recording, since I arrived at the same root cause independently before finding #4299 on master:

    FL_UNROLL(4) alone is sufficient, and I confirmed that in isolation. Leaving mulhi_i32_4 as the only rolled loop while add/sub were unrolled held mul at 6322 µs while add/sub collapsed to ~530 — which pins the cost to the rolled loop rather than to the arithmetic. #4299's FL_SIMD_LANE4 is the better mechanism (it binds the index as a compile-time constant rather than relying on the pragma being honoured, and it covers simd_riscv.hpp too), but the two agree on the cause.

    The fix makes the firmware smaller. Two otherwise-identical bash compile rp2350 --examples AutoResearch builds across my equivalent patch: text 978536 → 976012, total 1043220 → 1040916, i.e. 2304 bytes smaller. Removing the ldmia/stmia stack round-trips for the by-value 16-byte aggregate more than pays for the unrolling, so there is no size/speed trade to weigh here.

    The division half of this issue is untouched by #4299 and still reproduces: s16x16 div 54456 µs against float 1519 (36x), from the i64 / i32 at src/fl/math/fixed_point/s16x16.h:88 lowering to __aeabi_ldivmod, as described in my earlier comment. That is a separate defect in the fixed-point type, not in the SIMD backends, and it survives this issue's closure — worth its own issue if it is not already tracked.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions