[英]ARM Cortex M7 unaligned access and memcpy
我正在使用 GCC 為 Cortex M7 編譯此代碼:
// copy manually
void write_test_plain(uint8_t * ptr, uint32_t value)
{
*ptr++ = (u8)(value);
*ptr++ = (u8)(value >> 8);
*ptr++ = (u8)(value >> 16);
*ptr++ = (u8)(value >> 24);
}
// copy using memcpy
void write_test_memcpy(uint8_t * ptr, uint32_t value)
{
void *px = (void*)&value;
memcpy(ptr, px, 4);
}
int main(void)
{
extern uint8_t data[];
extern uint32_t value;
// i added some offsets to data to
// make sure the compiler cannot
// assume it's aligned in memory
write_test_plain(data + 2, value);
__asm volatile("": : :"memory"); // just to split inlined calls
write_test_memcpy(data + 5, value);
... do something with data ...
}
我使用 -O2 得到以下 Thumb2 程序集:
// write_test_plain(data + 2, value);
800031c: 2478 movs r4, #120 ; 0x78
800031e: 2056 movs r0, #86 ; 0x56
8000320: 2134 movs r1, #52 ; 0x34
8000322: 2212 movs r2, #18 ; 0x12
8000324: 759c strb r4, [r3, #22]
8000326: 75d8 strb r0, [r3, #23]
8000328: 7619 strb r1, [r3, #24]
800032a: 765a strb r2, [r3, #25]
// write_test_memcpy(data + 5, value);
800032c: 4ac4 ldr r2, [pc, #784] ; (8000640 <main+0x3a0>)
800032e: 923b str r2, [sp, #236] ; 0xec
8000330: 983b ldr r0, [sp, #236] ; 0xec
8000332: f8c3 0019 str.w r0, [r3, #25]
有人可以解釋一下memcpy
版本是如何工作的嗎? 這看起來像是到目標地址的內聯 32 位存儲,但這不是問題,因為data + 5
肯定不會與 4 字節邊界對齊嗎?
這可能是由於我的源代碼中的某些未定義行為而發生的一些優化嗎?
對於 Cortex-M 處理器,通常允許未對齊的字節、半字和字的加載和存儲,並且大多數編譯器在生成代碼時使用它,除非他們被指示不要這樣做。 如果您想阻止 gcc 假設未對齊的訪問正常,您可以使用-mno-unaligned-access
編譯器標志。
如果您指定此標志 gcc 將不再內聯對memcpy
和write_test_memcpy
的調用看起來像
write_test_memcpy(unsigned char*, unsigned long):
push {lr}
sub sp, sp, #12
movs r2, #4
add r3, sp, #8
str r1, [r3, #-4]!
mov r1, r3
bl memcpy
add sp, sp, #12
ldr pc, [sp], #4
Cortex-M 7 , M4, M3 M33, M23 支持非對齊訪問 M0, M+ 不支持非對齊訪問
但是,您可以通過在配置和控制寄存器中設置位 UNALIGN_TRP 來禁用 cortexm7 中對未對齊訪問的支持,任何未對齊的訪問都會產生使用錯誤。
從編譯器的角度來看,默認設置是生成的匯編代碼進行未對齊訪問,除非您使用編譯標志-mno-unaligned-access
禁用它
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.