https://gcc.gnu.org/bugzilla/show_bug.cgi?id=111417
Bug ID: 111417 Summary: Incorrect optimization when linker-generated symbols are used Product: gcc Version: 12.2.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: c Assignee: unassigned at gcc dot gnu.org Reporter: cz.finn.cz at gmail dot com Target Milestone: --- Initial conditions are as follows: 1. In our linker script, we define a new symbol: .mram2_data (NOLOAD): { ... } > MRAM2 MRAM2_region_size = LENGTH(MRAM2); 2. In our C code, we declare this symbol as follows: extern U8 MRAM2_region_size[]; 3. Under certain conditions, the value of the symbol is zero - as can be observed in the .map file: 0x0000000000000000 MRAM2_region_size = LENGTH (MRAM2) 4. In our C code we have a function: static void mramDeviceTest(U16 * memory, U32 size, const char * desc) { if((memory != NULL) && (size != 0u)) { (void) rtos_kprintf(RTOS_LOGLEVEL_APP_INFO, "%s (%u @ %p) - test passed", desc, size, memory); } else { (void) rtos_kprintf(RTOS_LOGLEVEL_APP_INFO, "%s (%u @ %p) - test skipped", desc, size, memory); } } 5. This function is called as follows: mramDeviceTest((U16 *) MRAM2_region_start, (uintptr_t) MRAM2_region_size, "MRAM2"); Expected behaviour: since the argument 'size' equals to zero, one would expect, that the function will print something like "MRAM2 (0 @ 68000000) - test skipped". Real (erroneous) behaviour: the function is optimized in a strange way and prints "MRAM2 (0 @ 68000000) - test passed", i.e. the optimizer supposes that 'size' is zero although in reality it obviously isn't. Work around: not to define the argument as 'U8 size' but as 'volatile U8 size'. Code compiled with version 7.2.1 works as expected, code compiled with versions 10.3.1 and 12.2.0 fails. Target architecture: ARM-R5, big endian CFLAGS=-mcpu=cortex-r5 -mfloat-abi=hard -mfpu=vfpv3-d16 -mbig-endian -mthumb -mthumb-interwork -Wall -Wundef -fomit-frame-pointer -ffast-math -g -Wa,-a,-ad -fno-strict-aliasing -MD -O2 -falign-functions=8 -Wimplicit-fallthrough=3 -fno-exceptions -fno-unwind-tables -std=gnu99 -Werror=incompatible-pointer-types LDFLAGS=-mcpu=cortex-r5 -mfloat-abi=hard -mfpu=vfpv3-d16 -mbig-endian -mthumb -mthumb-interwork -g -nostartfiles -Wl,-Map,dist/release/output.map,-T,project/project_gcc.ld,-n -Wl,--no-wchar-size-warning,--cref -Wl,--gc-sections -O2 -falign-functions=8 -mbe32