Repository navigation
Fix/math32 constant division guard - #21214
arnavsharma990 wants to merge 1 commit into
Conversation
e28138e to
fb21fc1
Compare
|
fb21fc1 to
4b50241
Compare
hartmannathan
left a comment
There was a problem hiding this comment.
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.
491a21d to
74fe292
Compare
|
It's probably not ideal to define The rest of the change looks good to me. Thanks for finding it and submitting a fix! |
|
Another reason to use the compiler check to define |
74fe292 to
286e7fd
Compare
|
Thanks for the review, @hartmannathan ! I've updated the PR to follow your suggestion. Compiler capability detection is now centralized in I've preserved the really appreciate the guidance ! |
hartmannathan
left a comment
There was a problem hiding this comment.
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
286e7fd to
5680cf0
Compare
| } \ | ||
| __n; \ | ||
| }) | ||
| #if !defined(CONFIG_LIBC_DISABLE_DIV64_OPTIMIZATION) && \ |
There was a problem hiding this comment.
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.
Summary
The constant 64-bit division optimization (
div64_const/div64_const32) ininclude/nuttx/lib/math32.his unreachable because it is guarded byCONFIG_HAVE_EXPRESSION_STATEMENT, which is not a real NuttX configurationoption and is never defined anywhere in the repository or nuttx-apps. The guard
has been dead since the feature was introduced (commit
7fc03e0084), and commitc32b683("!compiler: drop CONFIG_HAVE_LONG_LONG") removed the only otherconjunct.
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 reciprocalmultiplication.
This PR:
Centralizes compiler capability detection.
include/nuttx/compiler.hnow detects expression-statement support once and exports
HAVE_EXPRESSION_STATEMENTfor GCC and Clang, excluding Green Hills(
__ghs__), following the existing convention in that header. Compileridentities are no longer tested inside
math32.h; the guard consumes thereusable capability macro instead. No Kconfig symbol is introduced for the
capability.
Replaces the dead guard with:
Replaces
sizeof(typeof(n))withsizeof(n)indiv_const,div_const_roundup, anddiv_const_roundnearest.typeofis a GNUextension unavailable under strict ISO C (
-std=c99, used by the RenesasRX65N board), which would fail to compile once the optimized path is enabled.
Adds
CONFIG_LIBC_DISABLE_DIV64_OPTIMIZATION(defaultn) inlibs/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_tisint64_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:
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). Thismeans 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), minimalhello_mainconfiguration with most optional features disabled.Verification performed:
Capability detection (preprocessor):
#define HAVE_EXPRESSION_STATEMENT 1#define HAVE_EXPRESSION_STATEMENT 1-D__ghs__simulation: macro absent (simulation only; no GHS compileravailable)
Guard selection (
#ifdef div64_constprobe):n)nyArithmetic equivalence: optimized and fallback both return correct
results for
div_const,div_const_roundup, anddiv_const_roundnearest,including 32-bit dividends, power-of-two divisors, and
0xffffffffffffffff / 7.Strict ISO C:
-std=c99,-std=c11,-std=gnu99,-std=gnu11allcompile a translation unit including
clkcnt.h(previously failed ontypeof).C++:
g++andclang++compile and run the arithmetic test in bothmodes.
Full build (stm32f4discovery, arm-none-eabi-gcc 16.2.0):
__aeabi_ldivmod=n=yDisassembly of
clock_systime_timespec: baseline hasbl __aeabi_ldivmod; optimized build usesumlal.The remaining
_udivmoddi4(816 B) comes fromlib_ultoa_invertand is outof scope.
Kconfig validation (kconfiglib): full tree parsed (29,077 symbols);
LIBC_DISABLE_DIV64_OPTIMIZATIONisbool, prompt/help present, defaultn, and=yevaluates correctly.Style:
nxstylepasses on both modified headers;git diff --checkpasses.
Build log (baseline):
Build log (optimized):
Not performed:
by preprocessor simulation only.
rx-elf-gcc/rx-none-elf-gccinstalled); therelevant
-std=c99failure mode was reproduced and fixed with host andcross GCC instead.
config/toolchain drift blocked it, so measurements use the existing
stm32f4discovery build tree pinned to the same upstream baseline.