Skip to content

perf(fl/math): gate libm behind SKETCH_HAS_LARGE_MEMORY; polynomial impls on Low-memory (closes most of #3002) - #3012

Merged
zackees merged 1 commit into
masterfrom
feat/fl-math-libm-free
Jun 14, 2026
Merged

zackees merged 1 commit into
masterfrom
feat/fl-math-libm-free

Conversation

@zackees

@zackees zackees commented Jun 14, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes the dominant share of #3002 — the libm/soft-FP bloat that made bash autoresearch lpc845brk fail to link by ~3.4 KB on the LPC845 JSON-RPC bring-up sketch.

Root cause (LPC845-BRK firmware.map)

fl.math+_5ad9.o (symbol from plugin) (ldexpf)
fl.math+_5ad9.o (symbol from plugin) (atan2)

fl::math's *_impl_* wrappers thinly forwarded to libm (::sqrtf, ::sinf, ::atan2, ::ldexpf, ...). On no-FPU MCUs that anchors libm's internal soft-FP chain (libm_a-s_scalbn.o → __aeabi_dadd, libm_a-w_fmod.o → __aeabi_ddiv, etc.), pulling libgcc's full soft-double helper set into every sketch that linked fl::math — ~6 KB on the 64 KB-flash LPC845. The sketch never actually computed an arctangent or a square root.

Note: the original #3002 hypothesis was that fl::json's double representation was the libm anchor. Investigation showed fl::json already uses float per src/fl/stl/json/types.h:652 ("changed from double to float"). The actual anchor was fl::math's thin libm wrappers — fl.math+_5ad9.o (symbol from plugin) (ldexpf) is unambiguous in the firmware.map.

Changes

  1. src/fl/math/math.cpp.hpp — every *_impl_* function is gated by FL_MATH_USE_LIBM, which derives from SKETCH_HAS_LARGE_MEMORY:

    • Large-memory (SKETCH_HAS_LARGE_MEMORY=1 — host, ESP32, Teensy 4.x, RP2040, SAMD51, STM32F4+): use libm unchanged for full IEEE-754 precision. Existing tests' epsilon(1e-6) / epsilon(1e-10) guarantees are preserved.

    • Low-memory (SKETCH_HAS_LARGE_MEMORY=0 — AVR, LPC8xx, Teensy LC/3.x, STM32F1, ESP8266, ...): hand-rolled polynomial / Newton-Raphson approximations in a detail:: namespace:

      • `sqrt_newton_` — bounded Newton iteration
      • `sin_reduce_` / `cos_reduce_` — range-reduced degree-7 Taylor
      • `log_natural_` — fraction extraction + Taylor on [1,2)
      • `atan_full_` / `atan2_full_` — minimax degree-11 polynomial
      • `ldexp_loop_` — bounded multiply-by-2 loop
      • `pow`, `fmod`, `lround`, `round`, `asin`, `acos`, `tan`, `hypot` derived from the primitives above

    Sketches on Low-memory targets that need full IEEE-754 precision can `#include ` directly; that anchors libm only at the call site that opted in, not from every `fl::sqrt(x)`.

  2. `src/fl/system/sketch_macros.h` — add `FL_IS_ARM_LPC` to the `SKETCH_HAS_LARGE_MEMORY=0` list. NXP LPC8xx parts (LPC845: 16 KB SRAM / 64 KB flash, LPC804: 4 KB SRAM / 32 KB flash) are in the same tier as Teensy LC / STM32F1 — not the Mega-class "high" tier.

  3. `src/platforms/arm/compile_test.hpp` — extend the Low-memory ARM group to include `FL_IS_ARM_LPC` so the platform self-check passes with the corrected `SKETCH_HAS_LARGE_MEMORY=0`.

Verification

Host: `bash test fl/math/math.cpp --cpp` — passes. Libm path is unchanged, all existing `doctest::Approx` precision guarantees hold.

LPC845-BRK firmware.map (after rebuild):

Before After
`fl.math+` → `ldexp`, `ldexpf`, `atan2`, `acos`, `asin`, `fmod`, `hypot`, `log`, `log10`, `pow`, `sqrt`, `atan`, `cos`, `sin`, `tan` `fl.math+` → (no libm references)

Net flash savings on the bring-up sketch: 2664 bytes (3424 B over → 760 B over).

Remaining work

A small residual 760 B is from double-precision compare helpers (`__aeabi_dcmpeq` and friends, ~424 B from `__ledf2` / `__gedf2`) anchored by a path that still uses `double` somewhere in the linked output (likely a remaining downstream consumer of `fl::pow` or similar with a `double` argument). Closing that residual is the natural follow-up needed for `bash autoresearch lpc845brk` to link cleanly end-to-end.

Related

Test plan

  • Host `bash test fl/math/math.cpp --cpp` passes.
  • LPC845 firmware.map confirms zero libm references from `fl.math+`.
  • Follow-up: identify and drop the remaining double-compare anchor so `bash autoresearch lpc845brk` links end-to-end.
  • Cross-platform regression: ESP32, Teensy, AVR — libm path unchanged on Large-memory, polynomial path active on AVR/LPC.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added dynamic math implementation selection based on device memory availability
    • Extended platform support to include ARM LPC microcontrollers
  • Chores

    • Optimized math operations for low-memory devices with memory-efficient approximations
    • Enhanced platform detection and memory-constraint validation for ARM targets

…mpls on Low-memory

Closes the dominant share of FastLED #3002 — the libm/soft-FP bloat that
made `bash autoresearch lpc845brk` fail to link by ~3.4 KB on the LPC845
JSON-RPC bring-up sketch.

Root cause traced via the LPC845-BRK firmware.map:

  fl.math+_5ad9.o (symbol from plugin) (ldexpf)
  fl.math+_5ad9.o (symbol from plugin) (atan2)

`fl::math`'s `*_impl_*` wrappers thinly forwarded to libm (`::sqrtf`,
`::sinf`, `::atan2`, `::ldexpf`, ...). On no-FPU MCUs that anchors libm's
internal soft-FP chain (`libm_a-s_scalbn.o` → `__aeabi_dadd`,
`libm_a-w_fmod.o` → `__aeabi_ddiv`, etc.), pulling libgcc's full soft-
double helper set into every sketch that linked `fl::math` — ~6 KB on
the 64 KB-flash LPC845. The sketch never actually computed an arctangent
or a square root.

Changes
-------

1. **src/fl/math/math.cpp.hpp** — every `*_impl_*` function is now gated
   by `FL_MATH_USE_LIBM`, which derives from `SKETCH_HAS_LARGE_MEMORY`:

   * Large-memory targets (`SKETCH_HAS_LARGE_MEMORY=1` — host, ESP32,
     Teensy 4.x, RP2040, SAMD51, STM32F4+) use libm unchanged for full
     IEEE-754 precision. Existing tests' `epsilon(1e-6)`/`epsilon(1e-10)`
     guarantees are preserved.

   * Low-memory targets (`SKETCH_HAS_LARGE_MEMORY=0` — AVR, LPC8xx,
     Teensy LC/3.x, STM32F1, ESP8266, ...) use hand-rolled polynomial /
     Newton-Raphson approximations in a `detail::` namespace:
     - `sqrt_newton_<F>` — bounded Newton iteration
     - `sin_reduce_<F>` / `cos_reduce_<F>` — range-reduced degree-7 Taylor
     - `log_natural_<F>` — fraction extraction + Taylor on [1,2)
     - `atan_full_<F>` / `atan2_full_<F>` — minimax degree-11 polynomial
     - `ldexp_loop_<F>` — bounded multiply-by-2 loop
     - `pow`, `fmod`, `lround`, `round`, `asin`, `acos`, `tan`, `hypot`
       derived from the primitives above

   Sketches on Low-memory targets that need full IEEE-754 precision can
   `#include <cmath>` directly; that anchors libm only at the call site
   that opted in, not from every `fl::sqrt(x)`.

2. **src/fl/system/sketch_macros.h** — add `FL_IS_ARM_LPC` to the
   `SKETCH_HAS_LARGE_MEMORY=0` list. NXP LPC8xx parts (LPC845: 16 KB
   SRAM / 64 KB flash, LPC804: 4 KB SRAM / 32 KB flash) are in the
   same tier as Teensy LC / STM32F1 — not the Mega-class "high" tier.

3. **src/platforms/arm/compile_test.hpp** — extend the Low-memory ARM
   group to include `FL_IS_ARM_LPC` so the platform self-check passes
   with the corrected `SKETCH_HAS_LARGE_MEMORY=0`.

Verification
------------

* Host: `bash test fl/math/math.cpp --cpp` — passes (libm path unchanged,
  all existing `doctest::Approx` precision guarantees hold).

* LPC845-BRK firmware map (after rebuild):

      before:  fl.math+ → ldexp, ldexpf, atan2, acos, asin, fmod, hypot,
                          log, log10, pow, sqrt, atan, cos, sin, tan
      after:   fl.math+ → (no libm references)

  Net flash savings: 2664 bytes on the bring-up sketch
  (3424 B over → 760 B over).

  A small residual 760 B is from double-precision compare helpers
  (`__aeabi_dcmpeq` and friends, ~424 B from `__ledf2`/`__gedf2`) anchored
  by a path that still uses `double` somewhere in the linked output. That
  is the remaining work toward closing `bash autoresearch lpc845brk`
  end-to-end — tracked as the natural follow-up.

Related
-------

* FastLED #3002 — original "fl::json fixed-point variant" issue. The
  investigation under this PR moved the implementation target from
  "json refactor" to "libm-free fl::math primitives" once the
  firmware.map showed `fl.math+` was the actual libm anchor; fl::json
  already uses `float` (not `double`) per the comment at
  `src/fl/stl/json/types.h:652`.
* FastLED #3009 — LPC845 AutoResearch harness PR (merged on master,
  this PR's verification target).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 14, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 7862a529-d6c1-4aa1-b21e-eec800a92ecd

📥 Commits

Reviewing files that changed from the base of the PR and between 0f81975 and c0da8bd.

📒 Files selected for processing (3)
  • src/fl/math/math.cpp.hpp
  • src/fl/system/sketch_macros.h
  • src/platforms/arm/compile_test.hpp

📝 Walkthrough

Walkthrough

FL_IS_ARM_LPC is added to the limited-memory ARM platform group in platform detection headers. math.cpp.hpp gains a new FL_MATH_USE_LIBM macro derived from SKETCH_HAS_LARGE_MEMORY, switching all public math helpers between libm calls and new detail-namespace hand-rolled approximations (Newton-Raphson sqrt, polynomial trig, Taylor-series log, minimax atan2, loop-based ldexp).

Changes

Conditional math library selection

Layer / File(s) Summary
FL_IS_ARM_LPC platform detection
src/fl/system/sketch_macros.h, src/platforms/arm/compile_test.hpp
sketch_macros.h adds FL_IS_ARM_LPC to the large-memory platform #if defined(...) chain. compile_test.hpp adds it to the limited-memory validation group and updates #error messages to mention LPC8xx.
FL_MATH_USE_LIBM macro + detail approximation primitives
src/fl/math/math.cpp.hpp
FL_MATH_USE_LIBM is defined from SKETCH_HAS_LARGE_MEMORY and guards conditional <math.h> inclusion. A new internal detail namespace introduces Newton-Raphson sqrt_newton_, polynomial sin_reduce_/cos_reduce_, Taylor-series log_natural_, minimax atan_full_/atan2_full_, and loop-based ldexp_loop_.
Public sqrt/sin/cos/log/pow/fabs/round/fmod helpers
src/fl/math/math.cpp.hpp
All fl::*_impl_* wrappers for basic arithmetic and trig are rewritten to call ::sqrtf, ::sinf, ::logf, ::powf, etc. under FL_MATH_USE_LIBM=1, and route to detail implementations otherwise; Arduino round macro push/pop is preserved.
atan2/atan/hypot/asin/acos/tan and ldexp helpers
src/fl/math/math.cpp.hpp
Angle and hypot helpers are gated on FL_MATH_USE_LIBM, using detail::atan2_full_, sqrt-based asin, and cosine-division tan on low-memory targets. ldexp_impl_float/ldexp_impl_double similarly branch to detail::ldexp_loop_.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

🐇 Hopping through the math with care,
No libm here, just polynomials bare!
Newton's steps and Taylor's series hum,
LPC platforms, here we come.
Approximate, but close enough—
Low-memory life can still be tough! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 8.70% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: gating libm behind SKETCH_HAS_LARGE_MEMORY and using polynomial implementations for low-memory targets, directly addressing linker bloat on embedded systems.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/fl-math-libm-free

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@fastled-project-sync fastled-project-sync Bot moved this to Triage in FastLED Tracker Jun 14, 2026
@zackees
zackees merged commit 90f361d into master Jun 14, 2026
8 of 9 checks passed
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 14, 2026
zackees added a commit that referenced this pull request Jun 14, 2026
Add `BareLibmChecker` (PR #3012, issue #3002): bans direct `::sqrtf`,
`::atan2`, `::powf`, `::ldexpf`, etc. in `src/`, forcing new code to
go through `fl::sqrt(x)` / `fl::atan2(y, x)` / ... — which on
Low-memory targets route to hand-rolled polynomial / Newton-Raphson
approximations rather than dragging libm + libgcc soft-FP into the
link.

Exemptions:
- `fl/math/math.cpp.hpp` / `math.h` — the compat shim itself.
- `src/third_party/` — upstream code we don't control.
- Pre-existing heavy users staged for migration (fl/audio, fl/fx,
  fl/gfx, fl/math/{fixed_point,line_simplification,screenmap,transform},
  platforms/esp, platforms/wasm). The discipline this checker enforces
  is "no NEW code that imports libm directly"; the existing subsystems
  (audio FFT in particular needs full IEEE 754) will be ported through
  fl:: over a series of focused refactors.

Suppression: `// ok libm` at end of line to whitelist a specific call.

Fix `src/power_mgt.cpp.hpp:87` — the actual LPC845-BRK blocker. The
old `lroundf(powf(normalized, exponent) * 255.0f)` anchored libm's
full soft-FP chain on no-FPU targets even though everything else
already routes through fl::math. Now uses `fl::powf` / `fl::lroundf`
(the float overloads — fl::pow takes double, so passing floats would
auto-promote and re-anchor double-precision soft-FP).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
zackees added a commit that referenced this pull request Jun 14, 2026
Add `BareLibmChecker` (PR #3012, issue #3002): bans direct `::sqrtf`,
`::atan2`, `::powf`, `::ldexpf`, etc. in `src/`, forcing new code to
go through `fl::sqrt(x)` / `fl::atan2(y, x)` / ... — which on
Low-memory targets route to hand-rolled polynomial / Newton-Raphson
approximations rather than dragging libm + libgcc soft-FP into the
link.

Exemptions:
- `fl/math/math.cpp.hpp` / `math.h` — the compat shim itself.
- `src/third_party/` — upstream code we don't control.
- Pre-existing heavy users staged for migration (fl/audio, fl/fx,
  fl/gfx, fl/math/{fixed_point,line_simplification,screenmap,transform},
  platforms/esp, platforms/wasm). The discipline this checker enforces
  is "no NEW code that imports libm directly"; the existing subsystems
  (audio FFT in particular needs full IEEE 754) will be ported through
  fl:: over a series of focused refactors.

Suppression: `// ok libm` at end of line to whitelist a specific call.

Fix `src/power_mgt.cpp.hpp:87` — the actual LPC845-BRK blocker. The
old `lroundf(powf(normalized, exponent) * 255.0f)` anchored libm's
full soft-FP chain on no-FPU targets even though everything else
already routes through fl::math. Now uses `fl::powf` / `fl::lroundf`
(the float overloads — fl::pow takes double, so passing floats would
auto-promote and re-anchor double-precision soft-FP).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
zackees added a commit that referenced this pull request Jun 14, 2026
…link

Last 692 B of the LPC845-BRK flash deficit (FastLED #3002) came from a
chain that started innocently and ended in libgcc's full soft-double set:

  int_conversion_visitor<i64>::operator()(const float& value)
    result = static_cast<i64>(value);          // <-- __aeabi_f2lz
                                              //      ↓
  _fixsfdi.o → __aeabi_f2ulz                  //      ↓
  _fixunssfdi.o → __aeabi_dmul, __aeabi_dsub  // ~6 KB of soft-double

The cast is reached through `json_value::as_int()`, which `fl::Remote`
calls on every incoming RPC to read the request `id` and `timestamp`.
Even though the variant only holds `float` (not `double` — see
types.h:652), one tag in the variant is enough to instantiate the
visitor's float overload and pull in the chain.

Fix: route (i64)(float) through (i32)(float) when the value is in range
(saturates otherwise). The variant only ever holds float and JSON
integers from any sane RPC payload fit in int32, so this is a
no-behavior-change refactor for the realistic input set, but it lowers
libgcc's chosen helper from `__aeabi_f2lz` (which uses double) to
`__aeabi_f2iz` (which doesn't).

Also strip the gratuitous `static_cast<double>(...)` casts from the
JsonToIntegerVisitor / JsonToBoolVisitor / JsonToFloatVisitor /
JsonToStringVisitor warning-formatting paths — they each pulled in
`__aeabi_dcmpeq` / `__ledf2` / `__gedf2` / `__aeabi_d2f` for no
diagnostic benefit (float has more than enough precision for a
"truncated to int" warning string).

After:
  ❯ arm-none-eabi-size firmware.elf
     text    data     bss
    63088     372    8336    (~2 KB flash headroom on a 64 KB part)

Refs: #3002, #3012, #3013.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant