Home / Learn Chip Programming / Inline Assembly and Intrinsics

Inline Assembly and Intrinsics

Sometimes you need one special instruction: wait for interrupt, disable interrupts, byte swap.

In shortSometimes you need one special instruction: wait for interrupt, disable interrupts, byte swap.

Theory in plain words

Using asm safelyLook for intrinsicNo intrinsic: asm volatileDeclare constraintsTest on target
Using asm safely

What it is

GCC extended asm embeds assembly in C with input/output constraints. Intrinsics (CMSIS: __WFI, __disable_irq, __REV) are safer wrappers.

Why we use it

Some instructions have no C equivalent. Exact timing, atomic sections and special registers need them.

How it works

Prefer intrinsics. If you write asm, declare outputs, inputs and clobbers so the compiler keeps its registers consistent.

Where it is used

  • Entering sleep (WFI)
  • Interrupt control, memory barriers
  • Fast bit tricks (CLZ, REV, SSAT)

Common instructions

GCC inline asm on ARM
static inline void wait_for_interrupt(void) { __asm volatile ("wfi"); }
static inline uint32_t primask_save(void) { uint32_t r; __asm volatile ("mrs %0, primask\n cpsid i" : "=r"(r) :: "memory"); return r; }
static inline void primask_restore(uint32_t r) { __asm volatile ("msr primask, %0" :: "r"(r) : "memory"); }
static inline uint32_t rev_bytes(uint32_t x) { uint32_t r; __asm volatile ("rev %0, %1" : "=r"(r) : "r"(x)); return r; }
// CMSIS: __WFI(), __disable_irq(), __enable_irq(), __REV(x), __CLZ(x), __NOP(), __DSB()
Byte swap (endianness) in JS to check your understandingTry it Yourself

ARM and AVR are little endian: the lowest byte is stored first. Network protocols are big endian, so you often swap.

Careful:The "memory" clobber tells the compiler not to reorder memory accesses around your asm. Forgetting it causes bugs that only appear with -O2.

Quick quiz

1. What does the WFI instruction do?

2. Why prefer intrinsics?

Common questions

What does the WFI instruction do?

Waits for an interrupt (sleep). Core sleeps until an interrupt.

Why prefer intrinsics?

The compiler understands them. The compiler can schedule and check them.