Home > Software engineering >  Why IAR ARM Cortex-M compiler does not align stack on 8-byte boundary?
Why IAR ARM Cortex-M compiler does not align stack on 8-byte boundary?

Time:09-19

ARM ABI says that the stack should be 8-byte aligned, but I see cases where the stack is aligned only to 4-byte boundary.

For example, I have the following simple busy-delay function:

void delay(int iter) {
   int volatile counter = 0;
   while (counter < iter) { // delay loop
         counter;
   }
}

This compiles with IAR EWARM 9.10.2 on ARM Cortex-M to the following disassembly:

SUB SP, SP, #0x4
...
ADD SP, SP, #0x4
BX LR

The problem is that after SUB SP,SP,4 the stack is misaligned (is aligned only to 4-byte boundary).

Why is this happening? Is this compliant with the ARM ABI? Are there any compiler options to control that?

This question is related, but not a duplicate of: Aligning a Stack pointer 8 byte from 4 byte in ARM assembly

CodePudding user response:

https://developer.arm.com/documentation/dui0375/g/Compiler-Features/Compiler-eight-byte-alignment-features

The Procedure Call Standard for the ARM Architecture (AAPCS) requires that the stack is eight-byte aligned at all external interfaces.

This means that the stack must be eight-byte aligned when calling an ABI-compliant function. This alignment is not required to be maintained at all times. Since this code does not make any function calls while the stack is misaligned, it is legal.

So your interrupt handler needs to be written to properly handle a potentially misaligned stack.

CodePudding user response:

In addition to Nate's answer about the stack not requiring to be aligned at all times, you mentioned in a comment that you are interested in the behaviour when an interrupt occurs.

As long as you do not modify the control register bit CCR.STKALIGN from its default value of 1, then the hardware will automatically align the stack to 8 bytes on exception entry. Also, the return value which the hardware puts in the link register contains a flag to tell it to restore the correct stack pointer value on exception return. Software doesn't need to know about this at all, your interrupt handler can just be an AAPCS compliant function which is allowed to assume 8 byte stack alignment on entry.

For more details see the ARMv7M ARM section B1.5.7.

  • Related