From 56462cf082e8bf2bae6cb288c5daa4b77289cfb0 Mon Sep 17 00:00:00 2001 From: X-Ryl669 Date: Sat, 27 Feb 2021 00:59:28 +0100 Subject: [PATCH] Make F_CPU a compile-time constant (#21051) --- Marlin/src/HAL/STM32/HAL.cpp | 6 ++++++ Marlin/src/HAL/STM32/inc/Conditionals_adv.h | 6 ++++++ .../share/PlatformIO/scripts/common-cxxflags.py | 13 +++++++++++++ 3 files changed, 25 insertions(+) diff --git a/Marlin/src/HAL/STM32/HAL.cpp b/Marlin/src/HAL/STM32/HAL.cpp index 5c7bc3a00b..4b530cc738 100644 --- a/Marlin/src/HAL/STM32/HAL.cpp +++ b/Marlin/src/HAL/STM32/HAL.cpp @@ -63,6 +63,12 @@ TERN_(POSTMORTEM_DEBUGGING, extern void install_min_serial()); void HAL_init() { FastIO_init(); + // Ensure F_CPU is a constant expression. + // If the compiler breaks here, it means that delay code that should compute at compile time will not work. + // So better safe than sorry here. + constexpr int cpuFreq = F_CPU; + UNUSED(cpuFreq); + #if ENABLED(SDSUPPORT) && DISABLED(SDIO_SUPPORT) && (defined(SDSS) && SDSS != -1) OUT_WRITE(SDSS, HIGH); // Try to set SDSS inactive before any other SPI users start up #endif diff --git a/Marlin/src/HAL/STM32/inc/Conditionals_adv.h b/Marlin/src/HAL/STM32/inc/Conditionals_adv.h index 672d405d6b..9c9a7014c7 100644 --- a/Marlin/src/HAL/STM32/inc/Conditionals_adv.h +++ b/Marlin/src/HAL/STM32/inc/Conditionals_adv.h @@ -24,3 +24,9 @@ #if defined(USBD_USE_CDC_MSC) && DISABLED(NO_SD_HOST_DRIVE) #define HAS_SD_HOST_DRIVE 1 #endif + +// Fix F_CPU not being a compile-time constant in STSTM32 framework +#ifdef BOARD_F_CPU + #undef F_CPU + #define F_CPU BOARD_F_CPU +#endif diff --git a/buildroot/share/PlatformIO/scripts/common-cxxflags.py b/buildroot/share/PlatformIO/scripts/common-cxxflags.py index a0a3b45043..ed863a917a 100644 --- a/buildroot/share/PlatformIO/scripts/common-cxxflags.py +++ b/buildroot/share/PlatformIO/scripts/common-cxxflags.py @@ -11,6 +11,13 @@ env.Append(CXXFLAGS=[ #"-Wno-sign-compare" ]) +# +# Add CPU frequency as a compile time constant instead of a runtime variable +# +def add_cpu_freq(): + if 'BOARD_F_CPU' in env: + env['BUILD_FLAGS'].append('-DBOARD_F_CPU=' + env['BOARD_F_CPU']) + # Useful for JTAG debugging # # It will separe release and debug build folders. @@ -20,3 +27,9 @@ env.Append(CXXFLAGS=[ # if env.GetBuildType() == "debug": env['BUILD_DIR'] = '$PROJECT_BUILD_DIR/$PIOENV/debug' + +# On some platform, F_CPU is a runtime variable. Since it's used to convert from ns +# to CPU cycles, this adds overhead preventing small delay (in the order of less than +# 30 cycles) to be generated correctly. By using a compile time constant instead +# the compiler will perform the computation and this overhead will be avoided +add_cpu_freq()