Access to struct on unaligned address with -Os option on Cortex-M0 produces hard fault
I noticed a problem using the -Os optimization on a Cortex-M0 architecture (STM32F0xx to be precise).
The following struct is defined in the code:
typedef struct
{
uint8_t data[31];
uint8_t crc;
} sample_struct_t;
Then a variable of the struct type is defined:
volatile sample_struct_t sample_struct;
The address of the struct variable is later passed to a function:
uint32_t CRC_val = CRC_CalcBlockCR
Prototype: uint32_t CRC_CalcBlockCR
When the function is called, the MCU goes to Hard Fault. The reason is that the variable is on an unaligned address (as seen in the map file).
0x2000023b sample_struct
The compiler produces the instruction "ldmia r0!, {r2}" with r0 = 0x2000023b in the function CRC_CalcBlockCRC.
This instruction leads to the Hard Fault condition which is correct according to the ARM specification.
If -O2 is enabled instead of -Os, the variable is mapped to 0x2000023c (aligned) and the code works as expected.
In my opinion the compiler should know that a Cortex-M0 architecture cannot perform unaligned memory access operations and therefore should not attempt to map this structure to an unaligned address. The compiler option "-mno-unaligned
The command line of the compiler is:
arm-none-eabi-gcc -c -Ifwlib -Isrc -DHSE_VALUE=8000000 -DUSE_STDPERIPH
The command line of the linker is:
arm-none-eabi-gcc [objects...] -Wl,-Map=
I am using 4.7-2013q3.
Question information
- Language:
- English Edit question
- Status:
- Answered
- Assignee:
- No assignee Edit question
- Last query:
- Last reply:
Can you help with this problem?
Provide an answer of your own, or ask Andre Heßling for more information if necessary.