Undefined reference error with -O3 and -flto

Hi,
If I set -O3 optimization level and enable LTO, linker error occurs:

in function `pxCurrentTCBConst2':
<artificial>:(.text.SVC_Handler+0x20): undefined reference to `pxCurrentTCB'

No errors with -O1, -O2 and -Os or if to disable LTO

I solved problem by adding portDONT_DISCARD macro to pxCurrentTCB declaration:

portDONT_DISCARD PRIVILEGED_DATA TCB_t * volatile pxCurrentTCB = NULL;

but I’m not sure it correct way.

Is this bug of GCC or FreeRTOS? Also problem appears only after size of resulting code starts to exceed ~41 Kb

PS: FreeRTOS V10.4.3, I’m using port from GCC\ARM_CM3, gcc-arm-none-eabi-9-2020-q2-update-win32

LTO is not perfect and also the optimizer although it‘s getting better and better.
I think it‘s not a FreeRTOS bug and rather an issue with the (pretty aggressive) -O3 in combination with LTO.
BTW I’m using -Os for MCU applications running from rather slow flash to minimize the amount of code to be fetched and GCC __attribute__ to optimize certain functions differently. -O3 produces larger code.
I had rare issues even with -Os workarounded/patched myself. Unfortunately it’s a bit try and error.
You could also try to update your GCC toolchain to GCC10-2020-q4. Maybe it helps.

Edit: I think adding portDONT_DISCARD to pxCurrentTCB won’t help. It’s volatile anyway. The optimized calling function is likely the problem where you could try to apply a dedicated attribute or whatever it takes.

Some kind of magic with this error. It went by itself after further refining my source code, even when I removed portDONT_DISCARD before pxCurrentTCB declaration))

Great that it works for you. Thanks.