Rust’s `core::arch::asm!` macro embeds target-specific instructions directly in a program. On Cortex-M, it can express operations such as accessing CPU registers or emitting a short instruction sequence when an intrinsic is insufficient. section 5.5.3 section 5.6
Every use is unsafe. The instructions must be valid, and their interface to the compiler must accurately describe inputs, outputs, and effects. An incorrect contract can cause surrounding code to be reordered, eliminated, or transformed incorrectly, producing difficult-to-diagnose bugs. section 5.5.3
Describe the assembly’s interface with operands and options:
- `in(reg)` supplies a value in a general-purpose register; `out(reg)` allocates a register for a result. The compiler chooses the registers. section 5.5.3
- `inout(reg)` binds a value to a register that the instructions both read and overwrite. section 5.5.3
- `options(nomem, nostack, preserves_flags)` promises that the block does not access memory, adjust the stack pointer, or change condition flags. Use each option only when it is true. section 5.5.3
use core::arch::asm;
let x: u32 = 0x1234_5678;
let y: u32;
unsafe {
asm!(
"rev {dst}, {src}",
src = in(reg) x,
dst = out(reg) y,
options(nomem, nostack, preserves_flags),
);
}
The Arm `REV` instruction reverses the byte order of a 32-bit value. Separate input and output operands connect the instruction to Rust variables. section 5.5.3
use core::arch::asm;
let mut x: u32 = 0x1234_5678;
unsafe {
asm!(
"rev {x}, {x}",
x = inout(reg) x,
options(nomem, nostack, preserves_flags),
);
}
The same operation can update one variable in place using `inout(reg)`. The options remain promises about the instruction’s effects. section 5.5.3
// Memory-mapped register address (STM32F103)
const GPIOC_ODR: u32 = 0x4001_100C;
const PC13: u32 = 1 << 13;
unsafe fn toggle_pc13() {
core::arch::asm!(
"ldr {tmp}, [{addr}]",
"eor {tmp}, {tmp}, {bit}",
"str {tmp}, [{addr}]",
addr = in(reg) GPIOC_ODR,
bit = in(reg) PC13,
tmp = out(reg) _,
options(nostack, preserves_flags),
);
}
A multi-instruction block loads, modifies, and stores an STM32F103 GPIO register. It omits `nomem` because the sequence accesses memory; `out(reg) _` declares a temporary output whose value is discarded. section 5.5.3
Prefer `cortex_m::asm` intrinsics for common operations such as barriers, sleep, and debug breakpoints. Reserve `asm!` for instructions or operand constraints those intrinsics do not provide. section 5.6
