Repository navigation
perf(esp32): add fl::sort_small for bounded containers; cut ClocklessIdf5 bloat - #2908
Conversation
…Idf5 bloat Closes #2907. Adds `fl::sort_small` — a public template that delegates directly to `fl::detail::insertion_sort` and skips the runtime fall-through inside `fl::detail::quicksort_impl`. Migrates three call sites in the `ClocklessIdf5` ctor transitive closure to use it. ## Why this is a real win `fl::sort` at `src/fl/stl/algorithm.h:564` dispatches to `detail::quicksort_impl`, which contains: ```cpp if (last - first <= 16) { insertion_sort(first, last, comp); return; } Iterator pivot = partition(first, last, comp); quicksort_impl(first, pivot, comp); quicksort_impl(pivot + 1, last, comp); ``` The bound is a runtime check, not `constexpr`. Per-template-parameter instantiation of `fl::sort` therefore emits the whole quicksort + partition + median-of-three + heap_sort body even when the call site provably operates on a bounded container ≤ 16 elements. The non-insertion-sort body is dead code for those call sites. `fl::sort_small` calls `detail::insertion_sort` directly, so the quicksort body is never instantiated for call sites that opt in. The new template guards an empty-or-single-element fast path to match the existing `fl::sort` precondition. ## Migrated call sites (all in ClocklessIdf5 transitive closure) | Site | Container | Bound | Why bounded | |---|---|---:|---| | `src/fl/channels/manager.cpp.hpp:137` | `mDrivers` | 4 | "Only 1-4 drivers expected" per existing comment | | `src/fl/channels/manager.cpp.hpp:251` | `mDrivers` | 4 | same — re-sort after priority change | | `src/platforms/esp/32/drivers/rmt/rmt_5/channel_driver_rmt.cpp.hpp:362` | `fl::vector_inlined<ChannelDataPtr, 16>` | 16 | inline-capacity template parameter | All three are reachable from `BusTraits<Bus::RMT>::registerWithManager()` (called at `idf5_clockless.h:45`), which is the entry point that anchors the 48,694 B map-derived attribution to `ClocklessIdf5` in the 2026-06-06 measured audit (see #2886 audit comment). ## Out of scope (deferred follow-ups) Seven other `fl::sort` sites exist in `src/` that also operate on small bounded containers, but they're either outside the `ClocklessIdf5` transitive closure or in alternate drivers (parlio/uart). Migration is a one-line follow-up per site; deferred so the measured savings here are clearly attributable to the `ClocklessIdf5` closure. ## Expected savings Conservative estimate: 1-3 KB per template instantiation of the eliminated quicksort body. Across the three sites (each is a distinct `Compare` type → distinct instantiation), expected total reduction is 3-9 KB on the ESP32-S3 NEOPIXEL Blink build. The Stage 6 regression gate (`tests/test_esp32s3_bloat_regression.py`, baseline = `350568`) will validate the measurement on this PR's CI run. If the build comes in lower, a follow-up commit lowers the baseline file in the same PR. ## Verification - `bash lint --cpp` → all C++ linting checks pass. - Behavior preserved: `fl::sort_small` has the same semantic contract as `fl::sort` (same return = nothing, same compare-by-<, same in-place mutation, idempotent on already-sorted input). Only O() characteristics change: O(n²) worst case instead of O(n log n) — fine when n is bounded. - The 3 migrated sites all operate on ≤ 16-element containers per the table above. Refs #2886, #2907, #2904, #2906.
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (3)
📝 WalkthroughWalkthroughThis PR introduces Changessort_small API and migrations
Estimated code review effort🎯 2 (Simple) | ⏱️ ~8 minutes Poem
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
…small) (#2909) Measured against `master @ 731e4d5` (PR #2908 just merged): Total flash: 350,127 B (3,627 sized flash symbols). (was: 350,568 B / 3,631 symbols on master @ 824cb5c) Delta: −441 B / −4 symbols, attributable to the 4 dead-stripped template instantiations from the eliminated quicksort_impl call sites: - fl::detail::quicksort_impl - fl::detail::partition - fl::detail::heap_sort - fl::detail::median_of_three The map-derived attribution to `fl::ClocklessIdf5<...>::ClocklessIdf5()` itself stays at 48,694 B — the rodata-pool blocks anchored under main.cpp.o weren't reachable from the quicksort code, so they don't shift. This is the measured fl::sort_small saving. Real but smaller than the 3-9 KB projected in #2907 — the existing quicksort_impl was more compact than expected. Refs #2886, #2907, #2908.
…rop __ieee754_pow (#2911) Closes #2910. Replaces `fl::pow(double, double)` with `fl::s16x16::pow` (integer fixed-point) in the two FastLED-owned callers that pull `__ieee754_pow` (libm, 2,723 B in the post-#2908 audit) into release builds. ## What changes | File | Site | Before | After | |---|---|---|---| | `src/fl/math/ease.cpp.hpp` | `Gamma8Impl::Gamma8Impl(float)` | `fl::pow(double, double)` per LUT entry | one `fl::s16x16(gamma)` ctor + per-entry `fl::s16x16::pow` | | `src/fl/gfx/colorutils.cpp.hpp` | `applyGamma_video(u8, float)` | bare `pow(orig, gamma)` (float args → double) | `fl::s16x16::pow` | `fl::s16x16::pow` is implemented as `exp2_fp(exp * log2_fp(base))` where `exp2_fp` and `log2_fp` are pure integer LUT-based implementations — zero libm dependency. The chain is broken at the ctor / function entry: the public API still takes `float gamma`, but that float is converted once to `fl::s16x16` via the constexpr ctor (one fmul + cast → `__mulsf3` + `__fixsfsi`, both << 100 B). ## Precision sanity-check - `Gamma8Impl` LUT is u16-valued. `s16x16` has 16 fractional bits (~1.5×10⁻⁵ resolution) — well above the LUT's 16-bit output resolution. - `applyGamma_video` is u8 → u8. Same story. - Result is computed in [0, 1] then scaled to u16 / u8 with round-half-up via integer math: `((raw_u32 * scale) + 0x8000) >> 16`. ## Why s16x16 is enough `s16x16` is 16 integer + 16 fractional bits — range ~[-32768, 32767]. - Gamma values are typically in [1.0, 4.0]: fits with massive headroom. - `(i/255)` is in [0, 1]: stored as raw [0, 65536]. - Intermediate `exp * log2_fp(base)` for `base ∈ (0, 1]` and `exp ∈ [1, 4]`: `log2(base) ∈ [-∞, 0]`, but `s16x16::log2_fp` clamps small inputs. The product stays in s16x16 range. - `exp2_fp(...)` returns [0, ~1] for the gamma case → fits. ## Out of scope - `third_party/cq_kernel/fft_precision.h` — third-party FFT macro-driven. - `third_party/stb/truetype/stb_truetype.cpp.hpp` — third-party font rasterizer. - `fl::pow` fixed-point template specializations — different overloads, not affected. ## Verification - `bash lint --cpp` → all C++ linting checks pass. - `bash test --cpp fl/gfx/gamma_lut` could not be run from the disposable PR worktree due to the known meson source-path bug at #2887. The same diff applied to the main checkout will run on CI's `unit tests linux` job. - Behavior preserved (modulo ±1 LSB rounding from fixed-point vs double): `Gamma8Impl` LUT entries should match the original within rounding precision; `applyGamma_video` preserves the "never-down-to-zero" invariant via explicit `result == 0 → 1`. ## Expected savings - Eliminated: `__ieee754_pow` (2,723 B). - Eliminated: any related double-math symbols only reachable via this path. - Added: `__mulsf3`, `__fixsfsi` (<< 100 B each — likely already linked by other float math sites). - Net: projected ~2-2.5 KB on the ESP32-S3 NEOPIXEL Blink build. The Stage 6 regression gate (`tests/test_esp32s3_bloat_regression.py`, baseline = `350127`) validates the measurement on this PR's CI run. A follow-up commit lowers the baseline file accordingly. Refs #2886, #2910, #2908, #2909.
…DISABLE_SPI_CHIPSETS (#2914) Closes #2913. Adds an opt-in build flag `FASTLED_DISABLE_SPI_CHIPSETS=1` that gates the SPI dispatch branch in `fl::Channel::showPixels`. For NEOPIXEL-only sketches the SPI branch is dynamically unreachable, but the compiler cannot prove that — every `pixelIterator.writeXXX(...)` reference inside the 11-case switch is statically reachable, keeping ~720 B of encoder bodies and the switch-table footprint linked. ## Measured baseline (post-#2911, `master @ 6bd4ebd`) Dead-code SPI encoder symbols currently linked into a NEOPIXEL Blink: | Symbol | Size | |---|---:| | `fl::PixelIterator::writeLPD8806<fl::vector_psram<u8>>` | 235 B | | `fl::PixelIterator::writeSK9822<fl::vector_psram<u8>>` | 197 B | | `fl::PixelIterator::writeAPA102<fl::vector_psram<u8>>` | 197 B | | `fl::PixelIterator::writeSM16716<fl::vector_psram<u8>>` | 91 B | | **Total** | **720 B** | Plus the `showPixels` body itself shrinks by the switch-table footprint (~300-500 B for an 11-case xtensa switch). Projected total saving: **~1.0-1.2 KB** on a NEOPIXEL Blink build with the flag enabled. ## Behavior - **Flag unset (default):** No change. The SPI dispatch is present; every existing example using APA102 / SK9822 / etc. continues to work. - **Flag set (`-DFASTLED_DISABLE_SPI_CHIPSETS=1`):** The SPI branch is removed at preprocess time. `showPixels()` on a channel whose chipset is an `SpiChipsetConfig` falls through to the post-dispatch event emission with no data encoded — the channel silently emits nothing. Users opt in with the understanding that they're not using SPI chipsets in this build. This mirrors the opt-in build-flag pattern shipped in #2894 (Stage 2 / boot-banner shim) — minimal default-change risk, real savings for users who can accept the constraint. ## Files - `src/fl/channels/channel.cpp.hpp` — `#if !defined(FASTLED_DISABLE_SPI_CHIPSETS) || !FASTLED_DISABLE_SPI_CHIPSETS` wraps the `else if (mChipset.is<SpiChipsetConfig>())` block. The gate's behavior + savings are documented inline at the comment block above the branch. - `docs/SLIM_ESP32S3.md` — adds row 6 to the "Release-build flash savers" priority table with the new flag, its constraint, and PR link. ## Verification - `bash lint --cpp` → all C++ linting checks pass. - The flag follows the established opt-in pattern; default behavior unchanged. - Measured saving will be validated on the post-merge build (a `-DFASTLED_DISABLE_SPI_CHIPSETS=1` build of Blink, compared against the current `347,004 B` baseline). ## Expected savings - Eliminated: writeAPA102 (197 B), writeSK9822 (197 B), writeLPD8806 (235 B), writeSM16716 (91 B) = 720 B (PixelIterator SPI encoders reachable only from showPixels' SPI branch). - Eliminated: ~300-500 B of switch-table + dispatch code in `showPixels` body. - Net: ~1.0-1.2 KB projected on NEOPIXEL Blink with flag set. The Stage 6 regression gate (`tests/test_esp32s3_bloat_regression.py`, baseline = `347004`) does NOT change in this PR because it measures the default-flag build, which is unchanged. A separate follow-up records the flag-on measured number once a measurement run lands. Refs #2886, #2913, #2908, #2911.
…dies on FASTLED_LOG_RUNTIME_ENABLED (#2918) Closes #2917. Wraps the bodies of the two `FL_NO_INLINE` cold-path emit helpers in `fl::ChannelEngineRMTImpl` with `#if FASTLED_LOG_RUNTIME_ENABLED`. In release builds (NDEBUG → `FASTLED_LOG_VERBOSITY=0` per Stage 1) the helpers collapse to ~5 B function bodies (parameters cast to `(void)`, single `ret`), down from ~410-418 B each. ## Why the existing FL_NO_INLINE + FL_WARN pattern wasn't enough ```cpp FL_NO_INLINE void emitRecoveryWarning(...) FL_NOEXCEPT { fl::sstream msg; // [1] constructed unconditionally msg << "..." << ... << external_words; // [2] 15 operator<< calls fire FL_WARN(msg.str()); // [3] expands to no-op in release } ``` In release builds: - `FL_WARN(X)` expands to `do { if (false) { ... << X; } } while(0)` — optimizer DCEs the inner block (`msg.str()` call elided). - But `fl::sstream msg;` at [1] and `msg << ...` at [2] are **outside** the `if (false)` block. They have observable side effects on `msg`'s internal buffer (heap allocation, sequential writes), so the optimizer keeps the constructor + all 15 `operator<<` calls live in the function body. Result: the FL_NO_INLINE pulled the diagnostic chain out of the function it was hoisted from (`createChannel`) — into its own symbol — but the bytes stayed in the binary. ## Measured baseline (post-#2916 ELF, `master @ 5ca722e`) | Symbol | Size | |---|---:| | `fl::ChannelEngineRMTImpl::emitAllocationFailureError` (`$isra$0`) | 418 B | | `fl::ChannelEngineRMTImpl::emitRecoveryWarning` (`$isra$0`) | 410 B | | **Total in scope** | **~828 B** | Both symbols collapse to ~5 B after this PR. ## Behavior preserved - **Debug builds (`FASTLED_LOG_VERBOSITY=1`, default for non-NDEBUG):** the diagnostic emits exactly as before. Users debugging RMT allocation failures still see the multi-line action-required message. - **Release builds (`FASTLED_LOG_VERBOSITY=0`, NDEBUG default since #2890):** the helper bodies become empty; the callers in `attemptAllocationRecovery` still call them (the call overhead is ~5 B / site), but the bodies cost nothing. The FL_WARN macro itself was always a no-op in release; this PR makes the body that *built the message* match the macro's release-build behavior. ## Other emit helpers — audit notes - `attemptAllocationRecovery` (315 B total): contains its own FL_WARN and FL_LOG_RMT calls plus actual retry-loop arithmetic. The diagnostic calls go through the standard `FL_WARN` macro which is already `do { if (false) { ... } } while(0)` in release — the optimizer DCEs the inline chain. The 315 B is the retry-loop body + `Rmt5ChannelConfig retry_config(...)` construction; NOT the diagnostic emission. Leaving as-is. - `handleAllocateTxFailure` (63 B): already a `FL_NO_INLINE` cold helper at 63 B post-Stage-1 — almost entirely the fallback retry body. No further gating needed. ## Out of scope - Removing the FL_WARN calls from the source. They're useful in debug builds; the gate keeps them debug-build-active. - Auditing every FL_WARN call site in the RMT5 driver — the inline ones inside hot function bodies are already collapsed correctly by the `if (false)` DCE. ## Verification - `bash lint --cpp` → all C++ linting checks pass. - Behavior preserved by construction: the gate is on a build-time define that defaults to "diagnostics on" in debug builds. - Measured saving validated on this PR's CI run via the Stage 6 regression gate. Expected: `total_flash` drops by ~700-800 B from the current baseline of `347,004 B`. A follow-up commit ratchets the baseline file in the same PR. Refs #2886, #2917, #2908, #2911, #2914.
perf(esp32): add fl::sort_small for bounded containers; cut ClocklessIdf5 bloat
Closes #2907.
Adds
fl::sort_small— a public template that delegates directly tofl::detail::insertion_sortand skips the runtime fall-through insidefl::detail::quicksort_impl. Migrates three call sites in theClocklessIdf5ctor transitive closure to use it.Why this is a real win
fl::sortatsrc/fl/stl/algorithm.h:564dispatches todetail::quicksort_impl, which contains:The bound is a runtime check, not
constexpr. Per-template-parameterinstantiation of
fl::sorttherefore emits the whole quicksort +partition + median-of-three + heap_sort body even when the call site
provably operates on a bounded container ≤ 16 elements. The
non-insertion-sort body is dead code for those call sites.
fl::sort_smallcallsdetail::insertion_sortdirectly, so thequicksort body is never instantiated for call sites that opt in. The
new template guards an empty-or-single-element fast path to match the
existing
fl::sortprecondition.Migrated call sites (all in ClocklessIdf5 transitive closure)
src/fl/channels/manager.cpp.hpp:137mDriverssrc/fl/channels/manager.cpp.hpp:251mDriverssrc/platforms/esp/32/drivers/rmt/rmt_5/channel_driver_rmt.cpp.hpp:362fl::vector_inlined<ChannelDataPtr, 16>All three are reachable from
BusTraits<Bus::RMT>::registerWithManager()(called at
idf5_clockless.h:45), which is the entry point thatanchors the 48,694 B map-derived attribution to
ClocklessIdf5inthe 2026-06-06 measured audit (see #2886 audit comment).
Out of scope (deferred follow-ups)
Seven other
fl::sortsites exist insrc/that also operate onsmall bounded containers, but they're either outside the
ClocklessIdf5transitive closure or in alternate drivers(parlio/uart). Migration is a one-line follow-up per site; deferred so
the measured savings here are clearly attributable to the
ClocklessIdf5closure.Expected savings
Conservative estimate: 1-3 KB per template instantiation of the
eliminated quicksort body. Across the three sites (each is a distinct
Comparetype → distinct instantiation), expected total reduction is3-9 KB on the ESP32-S3 NEOPIXEL Blink build.
The Stage 6 regression gate (
tests/test_esp32s3_bloat_regression.py,baseline =
350568) will validate the measurement on this PR's CIrun. If the build comes in lower, a follow-up commit lowers the
baseline file in the same PR.
Verification
bash lint --cpp→ all C++ linting checks pass.fl::sort_smallhas the same semantic contractas
fl::sort(same return = nothing, same compare-by-<, samein-place mutation, idempotent on already-sorted input). Only O()
characteristics change: O(n²) worst case instead of O(n log n) —
fine when n is bounded.
table above.
Refs #2886, #2907, #2904, #2906.
Summary by CodeRabbit