天天看點

keil、MDK、armcc 記憶體屏障語句

CMSIS 中定義為 __memory_changed

/* cmsis_armcc.h */

#ifndef   __COMPILER_BARRIER
  #define __COMPILER_BARRIER()                   __memory_changed()
#endif      

記憶體屏障語句:

__schedule_barrier();      

或者:

__memory_changed();      

等同于GCC的:

__asm__ __volatile__("": : :"memory")      

編譯器在優化時,生成的彙編代碼可能與C語言的書寫次序不一緻,這個叫編譯亂序。一般情況下,編譯亂序是無害的,會讓程式執行更快,但是有些情況下,特别是與中斷處理例程有互動的代碼,希望執行的次序完全按照C語言的書寫次序來完成,這個時候就需要加入适當的記憶體屏障指令,避免編譯亂序。

參考 MDK 幫助檔案:

3.6 Compiler intrinsics for inserting optimization barriers

The optimization barrier intrinsics __schedule_barrier, __force_stores, __force_loads, and __memory_changed let you override compiler optimizations by disabling instruction re-ordering and forcing memory updates.

The compiler can perform a range of optimizations, including re-ordering instructions and merging some operations. In some cases, such as system level programming where memory is being accessed concurrently by multiple processes, it might be necessary to disable instruction re-ordering and force memory to be updated.

The optimization barrier intrinsics __schedule_barrier, __force_stores, __force_loads and __memory_changed do not generate code, but they can result in slightly increased code size and extra memory accesses.

參考 MDK 幫助檔案:

B4.10 __schedule_barrier intrinsic

This intrinsic creates a special sequence point that prevents operations with side effects from moving past it under all circumstances. Normal sequence points allow operations with side effects past if they do not affect program behavior. Operations without side effects are not restricted by the intrinsic, and the compiler can move them past the sequence point.

有道翻譯:

This intrinsic creates a special sequence point that prevents operations with side effects from moving past it under all circumstances.

這種内在的特性建立了一個特殊的序列點,在任何情況下都可以防止帶有副作用的操作越過它。

Normal sequence points allow operations with side effects past if they do not affect program behavior.

正常的序列點允許帶有副作用的操作,如果它們不影響程式行為的話。