Skip to content

Fix/math32 constant division guard - #21214

Closed
arnavsharma990 wants to merge 1 commit into
apache:masterfrom
arnavsharma990:fix/math32-constant-division-guard
Closed

arnavsharma990 wants to merge 1 commit into
apache:masterfrom
arnavsharma990:fix/math32-constant-division-guard

Conversation

@arnavsharma990

@arnavsharma990 arnavsharma990 commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

The constant 64-bit division optimization (div64_const / div64_const32) in
include/nuttx/lib/math32.h is unreachable because it is guarded by
CONFIG_HAVE_EXPRESSION_STATEMENT, which is not a real NuttX configuration
option and is never defined anywhere in the repository or nuttx-apps. The guard
has been dead since the feature was introduced (commit 7fc03e0084), and commit
c32b683 ("!compiler: drop CONFIG_HAVE_LONG_LONG") removed the only other
conjunct.

Every affected call site falls through to ordinary 64-bit division, which on
32-bit targets pulls in the software divide helpers (__aeabi_ldivmod →
_udivmoddi4) instead of the intended Granlund–Montgomery reciprocal
multiplication.

This PR:

  1. Centralizes compiler capability detection. include/nuttx/compiler.h
    now detects expression-statement support once and exports
    HAVE_EXPRESSION_STATEMENT for GCC and Clang, excluding Green Hills
    (__ghs__), following the existing convention in that header. Compiler
    identities are no longer tested inside math32.h; the guard consumes the
    reusable capability macro instead. No Kconfig symbol is introduced for the
    capability.

  2. Replaces the dead guard with:

    #if !defined(CONFIG_LIBC_DISABLE_DIV64_OPTIMIZATION) && \
        defined(HAVE_EXPRESSION_STATEMENT)
    
  3. Replaces sizeof(typeof(n)) with sizeof(n) in div_const,
    div_const_roundup, and div_const_roundnearest. typeof is a GNU
    extension unavailable under strict ISO C (-std=c99, used by the Renesas
    RX65N board), which would fail to compile once the optimized path is enabled.

  4. Adds CONFIG_LIBC_DISABLE_DIV64_OPTIMIZATION (default n) in
    libs/libc/Kconfig, so users can opt out on code-size-constrained targets.

This is a performance optimization, not a code-size optimization. The
original feature commit states the goal is to "improve performance of 64-by-32
divisions by about two orders of magnitude." Binary-size impact is secondary and
varies by target.

Affected call sites (64-bit dividends with constant divisors):

  • include/nuttx/clock.h — clock_ticks2time, clock_time2ticks,
    clock_time2ticks_floor, clock_usec2time, clock_time2usec, TICK2SEC,
    TICK2MSEC, MSEC2SEC, etc. (clock_t is int64_t)
  • sched/wdog/wd_start.c:369 — div_const(expired, NSEC_PER_TICK)
  • include/nuttx/timers/oneshot.h:366 — div_const(nsec, NSEC_PER_TICK)
  • include/nuttx/timers/clkcnt.h:183,224,314,318 — div_const(...)

Related issue: #21213

Impact

Primary objective: performance. Replace software 64-by-32-bit division with
an inlined reciprocal multiplication, as described in the original feature
commit.

Binary-size impact (secondary, varies by target). MemBrowse results:

Target Change
mirtoo −1,664 B
arduino-mega2560 −208 B
stm32-nucleo-f103rb −88 B
rx65n-rsk2mb 0 B
hifive1-revb +372 B
esp32-devkitc +260 B
qemu-intel64 +26 B
s698pm-dkit +46,464 B (+12.1%)

The variation reflects inlined reciprocal multiplication versus a shared
software divide helper. The s698pm-dkit regression is substantial and warrants
further investigation.

Default-on policy: the opt-out defaults to n (optimization enabled). This
means targets such as s698pm-dkit inherit the size increase unless they disable
it. This tradeoff is intentional but is flagged here for maintainer decision.

Build process: one Kconfig option added; no build-system changes.
Hardware: no hardware-specific changes.
Documentation: no documentation changes required.
Security: no security implications.
Compatibility: backward compatible. The optimized path computes the same
truncating quotient as ordinary division. Unsupported compilers keep the
original fallback. Users can disable via
CONFIG_LIBC_DISABLE_DIV64_OPTIMIZATION=y.

Testing

Host: macOS (Darwin). Compilers available: Apple Clang 21.0.0 and
arm-none-eabi-gcc 16.2.0.

Board for full build: stm32f4discovery (ARM Cortex-M4, 32-bit), minimal
hello_main configuration with most optional features disabled.

Verification performed:

  1. Capability detection (preprocessor):

    • arm-none-eabi-gcc: #define HAVE_EXPRESSION_STATEMENT 1
    • Clang 21.0.0: #define HAVE_EXPRESSION_STATEMENT 1
    • -D__ghs__ simulation: macro absent (simulation only; no GHS compiler
      available)
  2. Guard selection (#ifdef div64_const probe):

    Configuration Branch
    option undefined (NuttX n) optimized
    option = n optimized
    option = y fallback
  3. Arithmetic equivalence: optimized and fallback both return correct
    results for div_const, div_const_roundup, and div_const_roundnearest,
    including 32-bit dividends, power-of-two divisors, and
    0xffffffffffffffff / 7.

  4. Strict ISO C: -std=c99, -std=c11, -std=gnu99, -std=gnu11 all
    compile a translation unit including clkcnt.h (previously failed on
    typeof).

  5. C++: g++ and clang++ compile and run the arithmetic test in both
    modes.

  6. Full build (stm32f4discovery, arm-none-eabi-gcc 16.2.0):

    Build text data bss __aeabi_ldivmod
    baseline 28,212 800 2,136 present
    option undefined 28,108 800 2,136 absent
    option =n 28,108 800 2,136 absent
    option =y 28,212 800 2,136 present

    Disassembly of clock_systime_timespec: baseline has
    bl __aeabi_ldivmod; optimized build uses umlal.
    The remaining _udivmoddi4 (816 B) comes from lib_ultoa_invert and is out
    of scope.

  7. Kconfig validation (kconfiglib): full tree parsed (29,077 symbols);
    LIBC_DISABLE_DIV64_OPTIMIZATION is bool, prompt/help present, default
    n, and =y evaluates correctly.

  8. Style: nxstyle passes on both modified headers; git diff --check
    passes.

Build log (baseline):

$ arm-none-eabi-size nuttx
   text    data     bss     dec     hex filename
  28212     800    2136   31148    79ac nuttx
$ grep -o "aeabi_ldivmod\|aeabi_uldivmod" nuttx.map | sort | uniq -c
  20 aeabi_ldivmod
  18 aeabi_uldivmod

Build log (optimized):

$ arm-none-eabi-size nuttx
   text    data     bss     dec     hex filename
  28108     800    2136   31044    7944 nuttx
$ grep -o "aeabi_ldivmod\|aeabi_uldivmod" nuttx.map | sort | uniq -c
  18 aeabi_uldivmod

Not performed:

  • No genuine Green Hills build (toolchain unavailable); GHS handling verified
    by preprocessor simulation only.
  • No Renesas RX65N build (no rx-elf-gcc / rx-none-elf-gcc installed); the
    relevant -std=c99 failure mode was reproduced and fixed with host and
    cross GCC instead.
  • No full build of the very latest master source in a fresh tree: unrelated
    config/toolchain drift blocked it, so measurements use the existing
    stm32f4discovery build tree pinned to the same upstream baseline.

@arnavsharma990
arnavsharma990 force-pushed the fix/math32-constant-division-guard branch from e28138e to fb21fc1 Compare October 30, 2026 15:31
@github-actions github-actions Bot added the Size: XS The size of the change in this PR is very small label Oct 30, 2026
@github-actions

github-actions Bot commented Oct 30, 2026 •

Copy link
Copy Markdown

MemBrowse Memory Report · Explore what changed →

arduino-mega2560

  • flash: .text -208 B, .trampolines -4 B (-0.3%, 65,292 B / 262,144 B, total: 25% used)

esp32-devkitc

  • ROM: .flash.text +264 B (+0.2%, 128,524 B / 4,194,272 B, total: 3% used)
  • irom0_0_seg: .flash.text +264 B (+0.3%, 94,396 B / 3,342,304 B, total: 3% used)

hifive1-revb

  • flash: .text +628 B (+0.8%, 85,564 B / 4,194,304 B, total: 2% used)

mirtoo

  • kseg0_progmem: .eh_frame -20 B, .text -1,664 B (-2.5%, 65,676 B / 131,072 B, total: 50% used)

qemu-armv8a

  • Code: .text.nxsig_clockwait -4 B (-0.0%, 354,412 B)

qemu-intel64

  • Code: .text -20 B (-0.0%, 8,687,897 B)

rx65n-rsk2mb

  • ROM: .text +336 B (+0.4%, 90,664 B / 2,097,152 B, total: 4% used)

s698pm-dkit

  • Code: .text +46,448 B (+12.1%, 431,680 B)

stm32-nucleo-f103rb

  • flash: .text -88 B (-0.3%, 34,180 B / 131,072 B, total: 26% used)

Catch memory regressions in CI with MemBrowse. Free for open source.

@arnavsharma990
arnavsharma990 force-pushed the fix/math32-constant-division-guard branch from fb21fc1 to 4b50241 Compare October 30, 2026 18:58

@hartmannathan hartmannathan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Wouldn't it be better to fix CONFIG_HAVE_EXPRESSION_STATEMENT so that it will be defined?

In all likelihood this was never defined because a mistake happened at some time in the past and it wasn't noticed until now.

Fixing CONFIG_HAVE_EXPRESSION_STATEMENT so that it will be defined as intended seems like a better solution to me than checking for GCC, Clang, or Green Hills compilers because there could be other compilers now or in the future.

It is also self documenting: It is not obvious why a check for three specific compilers is written here, while you can immediately see what CONFIG_HAVE_EXPRESSION_STATEMENT is for.

Finally, it's more 'grep'able, since you can easily grep CONFIG_HAVE_EXPRESSION_STATEMENT if you want to know more about it or to find other places that use expression statements. You can't really grep for the more complex condition involving three compilers.

@arnavsharma990
arnavsharma990 force-pushed the fix/math32-constant-division-guard branch 2 times, most recently from 491a21d to 74fe292 Compare October 30, 2026 19:14
@hartmannathan

Copy link
Copy Markdown
Contributor

It's probably not ideal to define CONFIG_HAVE_EXPRESSION_STATEMENT in Kconfig, so instead, you could keep the check for GCC, Clang, and Green Hills but use it to define HAVE_EXPRESSION_STATEMENT. Then, use HAVE_EXPRESSION_STATEMENT to guard the definitions of div_const() and div64_const(). That way, we will have the benefits of HAVE_EXPRESSION_STATEMENT being self documenting and 'grep'able, while keeping the automatic detection (avoiding requiring any manual Kconfig changes that people could forget to do).

The rest of the change looks good to me. Thanks for finding it and submitting a fix!

@hartmannathan

Copy link
Copy Markdown
Contributor

Another reason to use the compiler check to define HAVE_EXPRESSION_STATEMENT: the compiler checking logic might get more complicated in the future. For example a future release of the Green Hills compiler might add support for statement expressions, or other compilers might need to be considered, such as SDCC, or even older versions of GCC or Clang. By decoupling the preprocessor logic that checks for compiler support from the preprocessor logic that controls div*_const(), the compiler checking logic could grow as complex as needed and its result (HAVE_EXPRESSION_STATEMENT) could be used in multiple places.

@arnavsharma990
arnavsharma990 force-pushed the fix/math32-constant-division-guard branch from 74fe292 to 286e7fd Compare October 30, 2026 19:39
@github-actions github-actions Bot added Area: OS Components OS Components issues Size: S The size of the change in this PR is small and removed Size: XS The size of the change in this PR is very small labels Oct 30, 2026
@arnavsharma990

Copy link
Copy Markdown
Contributor Author

Thanks for the review, @hartmannathan ! I've updated the PR to follow your suggestion.

Compiler capability detection is now centralized in include/nuttx/compiler.h through HAVE_EXPRESSION_STATEMENT, and math32.h uses that macro instead of checking compiler identities directly.

I've preserved the sizeof(n) portability fix and the optional Kconfig opt-out. Both optimized and fallback paths have been tested, and the updated changes are pushed in commit 286e7fd8ab.

really appreciate the guidance !

hartmannathan
hartmannathan previously approved these changes Oct 30, 2026

@hartmannathan hartmannathan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM, thank you for finding and fixing this!

The optimized constant 64-bit division path (div64_const / div64_const32)
was guarded by CONFIG_HAVE_EXPRESSION_STATEMENT, which is not a real
NuttX configuration option and is never defined. The guard has been dead
since the feature was introduced (commit 7fc03e0), making the
optimization unreachable on every target.

This revision replaces the dead guard with a reusable compiler-capability
macro HAVE_BUILTIN_CHOOSE_EXPR, defined for GCC and Clang and excluded
under Green Hills, following the convention in compiler.h. math32.h
consumes HAVE_BUILTIN_CHOOSE_EXPR instead of testing compiler identities
directly.

div64_const is now a static inline_function rather than a GNU statement
expression, so it is legal in constant initializers at file scope (e.g.
MSEC2TICK() in board automount config structs). The three macros
(div_const, div_const_roundup, div_const_roundnearest) use
__builtin_choose_expr instead of the conditional operator, which (a) does
not evaluate the unused operand and (b) does not promote a 32-bit result
to uint64_t, preserving the original type and the existing %lu print
sites.

Also replace sizeof(typeof(n)) with sizeof(n) in all three macros. typeof
is a GNU extension unavailable under strict ISO C (e.g. -std=c99 on the
Renesas RX65N board).

Add CONFIG_LIBC_DISABLE_DIV64_OPTIMIZATION (default n) to allow users to
disable the optimization for code-size-constrained targets.

This activates the intended Granlund-Montgomery reciprocal division for
64-bit dividends with a constant divisor, removing the software 64-bit
divide helper (__aeabi_ldivmod) from clock_systime_timespec on 32-bit
targets.

Compiler portability:
- GCC/Clang: verified (host + cross builds, arithmetic suite, codegen)
- GHS: excluded per existing convention; fallback is plain division
- Strict C99: sizeof(n) is standard C, no GNU extension required

Fixes apache#21213

Signed-off-by: Arnav Sharma <[email protected]>
Assisted-by: Claude Opus 5
} \
__n; \
})
#if !defined(CONFIG_LIBC_DISABLE_DIV64_OPTIMIZATION) && \

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This turns div64_const() on for every GCC and Clang build, at every optimisation level. MemBrowse for this head shows s698pm-dkit .text +46,448 B (+12.1%), and CI overflows flash in mr-navq95b:nsh (1040 B), imx95-evk:nsh (1024 B) and b-g431b-esc1:nsh (104 B), which build on master.

Fix: limit it as #20996 does (DEBUG_FULLOPT, 32-bit, not sparc/xtensa/renesas), or join #20996, which changes the same macros for the same problem.

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

Labels

Area: OS Components OS Components issues Size: S The size of the change in this PR is small

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants