machdocs
Home Ecosystem Changelog

Inline assembly

Mach has one inline-assembly form: a block of raw instructions headed by an instruction-set selection, with local-variable substitution. The compiler parses the instruction stream and infers operand direction and clobbers from the opcode semantics - no in / out declarations, no clobber list.

Grammar

asm <selection> {
    # raw instructions in the selection's own dialect, here x86's, whose comments start with #
    mov rcx, {ptr}
    mov rax, [rcx]
    mov {result}, rax
}

How a block is read

A block is found while the file is lexed, before anything is parsed, so every tool that reads source reads it the same way.

Instruction setHeads, for exampleComment to the line's end
x86x86-64, x86-64,avx2#
aarch64armv8-a, armv8.2-a+sha2//, since # begins an immediate, as in add x0, x0, #1
RISC-Vrv64i, rv32i_zicsr#
WebAssemblymvp, wasm1,simd128;;, and (; ... ;) block comments

On x86, aarch64 and RISC-V a /* ... */ comment may span lines and ; ends a statement within a line. A block defines numbered labels only, such as 1:, named by its branches as 1b and 1f. A label defined by name is refused, because a block can be inlined twice.

Operand substitution

{name} names a local, a parameter or a compile-time constant in scope, and resolves by what it names:

A local is read before the block and written back after it, so a block may read and change any local it names. A register a name is placed in is never one the block itself writes.

pub fun add_via_asm(a: i64, b: i64) i64 {
    var result: i64 = 0;
    asm x86-64 {
        mov rax, {a}
        add rax, {b}
        mov {result}, rax
    }
    ret result;
}
val PAGE: i64 = 4096;

pub fun round_up(n: i64) i64 {
    var r: i64 = n;
    asm x86-64 {
        add {r}, {PAGE}
        sub {r}, 1
        and {r}, -4096
    }
    ret r;
}

Here {PAGE} is written as the immediate 4096, and {r} is a register.

Note

A pointer local's pointee is reached by staging the pointer through a scratch register first (mov rcx, {ptr} then mov rax, [rcx]), never by a direct [{ptr}] indirection, since {ptr} may be memory. In a function that requires constant time every local a block names is its own slot.

Only an identifier inside braces names a local, and only outside the dialect's comments, strings and character constants. Any other braced text belongs to the instruction set's own syntax, such as the aarch64 register list {v0.16b}, and reaches its grammar untouched. On WebAssembly every {name} of a local is a pointer to the local's storage.

A body that binds {name} and moves the stack pointer

A {name} placed in memory is a fixed displacement off a base register. The compiler reads each block for writes of the stack pointer first, and a function holding a block that moves it keeps its frame pointer (rbp on x86-64, x29 on aarch64, s0 on riscv) and addresses its locals off that instead. Such a block may bind a {name} and still move the stack pointer:

pub fun spill(a: i64, b: i64) i64 {
    var x: i64 = 0;
    asm armv8-a {
        ldr x9, {x}              // addressed off x29, the frame pointer, not sp
        stp x1, x2, [sp, -16]!
        ldp x1, x2, [sp], 16
    }
    ret x;
}

No block of a function that keeps its frame pointer may write that register, and such a block is refused. A body that binds no {name} may do whatever it likes with the stack pointer, which is what a #[naked] function's hand-written prologue does.

What the compiler infers

A block may leave for good, by a jump out of it or a fault such as hlt or ud2. A ret is refused, since it would skip the epilogue that restores the caller's frame. A body that returns by hand is a #[naked] function's. A block that never falls through is marked #[noreturn].

Calls and jumps (x86-64)

call and jmp take the same three shapes, and which one a statement means is read off the operand.

asm x86-64 {
    call some_symbol     # direct: E8 rel32, relocated against the symbol
    call rax             # indirect through a register
    call [0x100018]      # indirect through an absolute address
    call [rax + 8]       # indirect through a computed address

    jmp  some_symbol     # direct: E9 rel32
    jmp  rax             # indirect through a register
    jmp  [rax + 8]       # ... and the same memory forms
}

The absolute form exists for a fixed-address ABI, one whose entry points are addresses rather than symbols. Its displacement is sign-extended to 64 bits, so an address outside signed 32-bit range is refused rather than silently truncated. call [symbol] and jmp [symbol] are the memory form with the symbol's address as that displacement, so they transfer to the pointer stored at the symbol, not to the symbol.

Both indirect operands are fixed 64-bit in long mode, so a narrower register (jmp eax) is refused rather than widened. An indirect call clobbers exactly as a direct one does. The register or memory holding the target is read, not written.

Operand sizes (x86-64)

A register operand states its own width, so mov eax, [rcx] is a four-byte load and needs nothing else. A memory operand states none, and where the instruction does not settle it either, the width is written out in nasm's spelling. GNU as's spelling with ptr (mov dword ptr [rcx], 1) means the same.

asm x86-64 {
    movzx eax, word [rcx]     # a two-byte load, zero-extended into eax
    movsxd rax, dword [rcx]   # a four-byte load, sign-extended
    mov dword [rcx], 1        # a four-byte store, not the machine word
    neg qword [rcx]           # an eight-byte read-modify-write
}

byte, word, dword and qword are accepted before a memory operand and nowhere else, so mov qword rax, rcx is refused rather than ignored. A vector instruction's memory operand takes xmmword instead. A prefix that contradicts the instruction is a build error, not a dropped token, and what counts as a contradiction is per mnemonic:

ShapeRule
most instructionsevery operand shares one width, so a prefix must agree with any register operand, and with no register operand it sets the width
shl / shr / sar, shld / shrdthe count is cl or an immediate whatever the width of the operand shifted
movzx / movsxthe source is narrower by design, so a memory source must be sized, and strictly narrower than the destination. A four-byte source is movsxd, and movsx rax, dword [rcx] is refused
push / pop, indirect call / jmpfixed 64-bit in long mode, so any narrower prefix names no instruction
lidtits pseudo-descriptor is ten bytes, which no keyword names

So mov eax, word [rcx] is refused (two widths for one access), and so is movzx eax, [rcx]: an unsized source names no width.

Bit scans, strings and segments (x86-64)

asm x86-64,bmi1,lzcnt,popcnt {
    bsf rax, rcx              # index of the lowest set bit
    tzcnt r8, r9              # trailing zeros, 64 for a zero source (bmi1)
    lzcnt eax, dword [rsi]    # leading zeros, 32 for a zero source (lzcnt)
    popcnt rax, rcx           # set bits (popcnt)
    bswap rax                 # reverse the bytes of a 32- or 64-bit register
    imul rax, rcx, 5          # rax = rcx * 5, low half
    shld rax, rcx, 5          # shift rax left, bits from rcx fill from the right
}

popcnt, lzcnt and tzcnt need their extension, which the head above adds to the block. The string instructions take a width suffix and reach memory through their implicit registers, and a rep prefix adds rcx to what they read and write:

asm x86-64 {
    mov rdi, {dst}
    mov rsi, {src}
    mov rcx, {n}
    rep movsb                 # copy rcx bytes from [rsi] to [rdi]
    xor eax, eax
    mov rcx, 8
    rep stosq                 # store rax into 8 quadwords at [rdi]
}

The compiler assumes the ABI's guarantee that the direction flag is clear, so a block that sets it must clear it with cld before the block ends. A memory operand may lead with fs: or gs:, after any width keyword, and the address is then relative to that segment's base. The override is refused on a register, an immediate, a {name} and lea.

asm x86-64 {
    mov rax, fs:[0x28]            # an absolute offset from the fs base
    mov rax, qword gs:[rbx + 8]   # a register-relative one
    movdqu xmm0, gs:[16]
}

Vector registers

The x86-64 and aarch64 grammars take vector registers as operands. A vector register belongs to the floating-point and vector bank, so writing one adds it to the block's vector clobber set, and a live vector value crossing the block is kept the same way a general-purpose one is. A memory base or index is always a general-purpose register, and a vector register in a general-purpose form is refused by name.

The tables below list the baseline forms. They are not the whole surface: the assembler's catalog holds each instruction set entire, so the scalar floating-point forms, aarch64's 64-bit arrangements and multi-register lists assemble too, and an extension's forms assemble under it.

x86-64

The registers are xmm0 to xmm15 in the baseline. A memory operand of a vector instruction is a whole 128-bit vector, written bare or as xmmword [...]. A narrower width prefix is refused. [rip + symbol] addresses RIP-relative data, and a bare [symbol] is the symbol's absolute address, as it is for every instruction.

FormMnemonics
move, either direction between a register and memorymovdqa movdqu movaps movups
xmm, xmm/m128 integer arithmetic: paddb paddw paddd paddq psubb psubw psubd psubq psubusb psubusw pmullw pmulhw pmulhuw pmuludq psadbw
logic: pand por pxor
compares: pcmpeqb pcmpeqw pcmpeqd pcmpgtb pcmpgtw pcmpgtd
interleave and saturate: punpcklbw punpcklwd punpckldq punpckhbw punpckhwd punpckhdq packsswb packssdw
float arithmetic: addps subps mulps divps addpd subpd mulpd divpd
conversions: cvtdq2ps cvttps2dq cvtdq2pd cvttpd2dq cvtps2pd cvtpd2ps
xmm, xmm/m128, imm8pshufd cmpps cmppd
xmm, r64 and r64, xmmmovq
xmm, imm8pslldq psrldq psllq psrlq
asm x86-64 {
    movdqu xmm0, [rsi]            # load 16 bytes
    movdqu xmm1, xmmword [rdx]    # the same, with the width written out
    pxor xmm0, xmm1
    pshufd xmm0, xmm0, 0x1b       # reverse the four 32-bit lanes
    movdqu [rdi], xmm0            # store
}

aarch64

The registers are spelled vN.16b, vN.8h, vN.4s or vN.2d. The suffix is the lane arrangement, and every operand of one instruction shares it. add, sub, and, orr, eor and mov select their vector form when their operands are vector registers. Of those four arrangements, and, orr, eor, mov and mvn exist only at .16b (and .8b), the float members only at .4s and .2d, and mul everywhere except .2d.

FormMnemonics
three registersadd sub mul, and orr eor, cmeq cmgt cmge cmhi cmhs, fadd fsub fmul fdiv, fcmeq fcmgt fcmge
two registersmov mvn rev64
one element structureld1 {vT.<lanes>}, [Xn], st1 {vT.<lanes>}, [Xn]
lanesext, dup, ins

ld1 and st1 post-index their base, either by the structure size (, 16) or by an X register (, x9). Either form writes the base register.

asm armv8-a {
    ld1 {v0.16b}, [x1], 16      // load 16 bytes, then x1 += 16
    ld1 {v1.16b}, [x1], 16
    eor v0.16b, v0.16b, v1.16b
    st1 {v0.16b}, [x2], x9      // store, then x2 += x9
}

Constant-time checking

The multiply and float members are variable-latency operations, so the constant-time check in a #[constant_time] function treats them as it treats their scalar counterparts. The check tracks secrets per register bank, so a secret in xmm3 is never mistaken for a secret in rbx. In such a function a store of a secret is admitted only where something states the destination may hold one, such as memory reached through a pointer loaded from a {name} whose pointee type is secret:

#[constant_time("soft")]
fun copy(src: *^u64, dst: *^u64, count: *u64) {
    asm x86-64 {
        mov rax, {src}
        mov rcx, [rax]            # a secret
        mov rdx, {dst}
        mov [rdx], rcx            # admitted: dst's pointee is secret
        mov rdx, {count}
        mov qword [rdx], 1        # admitted: a public value
    }
}

Extension instructions

Some instructions exist only on processors that implement an extension beyond the instruction set's baseline. Such an instruction is refused unless the target selects the extension (the manifest's ext key), the enclosing function admits it with #[extension(...)], or the block's head adds it. The refusal names the instruction, the extension, and the ways to admit it. Some of the rows:

Instruction setExtensionMnemonics
x86_64ssse3pshufb, palignr
x86_64sse41pblendw, ptest, pinsrd, pextrd, pmulld, the pmovsx / pmovzx family
x86_64shasha256rnds2, sha256msg1, sha256msg2
x86_64popcnt, lzcnt, bmi1popcnt, lzcnt, tzcnt
x86_64aes, pclmulthe aesenc family, pclmulqdq
x86_64fsgsbaserdfsbase, rdgsbase, wrfsbase, wrgsbase
aarch64sha2sha256h, sha256h2, sha256su0, sha256su1
aarch64aes, pmullaese, aesd, aesmc, aesimc, pmull, pmull2
aarch64sb, ditsb, msr dit, ...
riscvzicntrrdtime, rdcycle, rdinstret

cpuid is baseline on x86_64 and is how a program finds out which extensions the processor has:

use std.types.bool.bool;

pub fun has_sha() bool {
    var b: u32 = 0;
    asm x86-64 {
        mov eax, 7
        xor ecx, ecx
        cpuid
        mov {b}, ebx
    }
    ret ((b >> 29) & 1) == 1;
}

Privileged and system instructions

The privileged and system instruction families are reachable from inline assembly on every target. Access permission is not checked: whether a register is readable or writable depends on the privilege level the code runs at, which the compiler does not know, and an access the current level cannot make traps at run time.

Systems instructions (x86-64)

asm x86-64 {
    cli                       # clear the interrupt flag
    sti                       # ... and set it
    cld                       # clear DF before entering a program
    hlt                       # park the core
    in al, dx                 # port i/o, through dx or by immediate port
    out dx, al
    rdtsc                     # the time-stamp counter
    rdmsr                     # the model-specific registers
    wrmsr
    lidt [rax]                # install an interrupt descriptor table
    pushfq                    # save RFLAGS
    popfq                     # ... and restore it
    swapgs                    # per-CPU state on a syscall entry
    mov rax, cr2              # the faulting address in a page-fault handler
    mov cr3, rax              # switch page tables
    mov eax, cs               # the live selector, for programming STAR
    mov ds, ax                # load a data selector
}

Control registers are cr0, cr2, cr3, cr4 and cr8, and a control-register move takes a 64-bit general-purpose register on its other side. Segment registers can be read into a general-purpose register, and every one but cs can be written from one. None of these writes a register the allocator tracks except rdtsc, rdmsr and cpuid. In a function with a compiler-built frame iretq is refused like ret, so a handler that ends in it is a #[naked] function.

Code width (x86)

A block on x86 may switch the width its code is read at with .code16, .code32 and .code64. The statements after a directive are read, checked and encoded as code of that width, so a boot sector or the switch into long mode is written as instructions:

#[naked]
#[section(".boot")]
fun boot() {
    asm x86-64 {
    .code32
        mov eax, cr4
        or eax, 0x20                # PAE
        mov cr4, eax
        call 1f
    1:
        pop eax
        add eax, 8
        push 8
        push eax
        retf
    .code64
        mov ax, 0x10
        mov ds, ax
        jmp _start
    }
}

System registers and barriers (aarch64)

mrs and msr name a system register by its architectural name, in either case, or by its encoding exactly as ARM and GNU as spell it, which makes the surface complete rather than a list that always lags the architecture.

asm armv8-a {
    mrs x0, cntvct_el0        // the virtual counter
    mrs x1, CNTFRQ_EL0        // ... and its frequency, capitalized as ARM spells it
    msr vbar_el1, x2          // install an exception vector base
    msr daifset, 0xf          // mask every interrupt
    mrs x3, s3_3_c14_c0_2     // the same register as `mrs x3, cntvct_el0`
}

A field the architecture cannot hold is refused rather than truncated. msr <field>, imm writes a PSTATE field (daifset, daifclr, spsel, pan, uao, ssbs, dit, tco), and the immediate may be spelled bare or with Arm's #. dit exists only with FEAT_DIT, so outside a constant-time function the block needs it from its head:

asm armv8-a+dit {
    msr dit, 1                // turn on data-independent timing for this thread
    dsb nsh                   // ... and make the write take effect before what follows
    isb
}

dmb and dsb take the Arm ARM's option vocabulary (sy, st, ld, ish, nsh, osh and their st / ld forms), and sb needs the sb extension:

asm armv8-a+sb {
    dmb ish                   // data memory barrier, inner shareable
    dsb nsh                   // data synchronization barrier, non-shareable
    isb                       // instruction synchronization barrier
    sb                        // speculation barrier, under the `sb` extension
}

Exception conduits and waits (aarch64)

asm armv8-a {
    svc 0                     // the kernel, at EL1
    hvc 0                     // the hypervisor, at EL2
    smc 0                     // the secure monitor, at EL3
    wfi                       // wait for an interrupt: the correct idle loop
    wfe                       // wait for an event
}

hvc and smc are how PSCI is reached, which is the only way to power off or restart a virt board. Both follow the SMC Calling Convention, so the compiler declares them as destroying x0 to x17. x18 to x30 and SP survive. The waits write nothing, so an idle loop holds every live value across them.

Jumps and control-and-status registers (riscv64)

A jump or call target is a symbol or a numeric local label. j and jal reach a symbol within 1 MiB, so a target that may live in another module or a shared object is spelled call or tail. A conditional branch to a symbol is relaxed into the inverted branch over a j.

asm rv64i {
    j    1f               # a numeric local label resolves in place
    call some_symbol      # auipc + jalr, +-2 GiB, may reach a PLT stub
1:
    beq  a0, a1, 1b       # a conditional branch to a numeric local label is one word
}

The Zicsr extension's six instructions reach a CSR by name or by its twelve-bit numeric address, which parses as the ordinary integer it looks like. The rdtime / rdcycle / rdinstret pseudos are Zicntr's, so a block that spells them needs zicntr from its head, the target or the function:

asm rv64i_zicntr {
    csrrw a0, mstatus, a1   # read mstatus into a0, write a1 into it
    csrr  a0, mtvec         # the read-only pseudo
    csrw  stvec, a1         # install a trap vector
    rdtime a0               # the unprivileged counters, which need zicntr
    csrr  a0, 0xc01         # the same register as `csrr a0, time`
}

Raw encodings

Four data directives emit their values verbatim, for an encoding the instruction set's mnemonic table does not name. They work on every target with an assembler.

asm x86-64 {
    .byte 0x0f, 0x01, 0xd0    # xgetbv
}
asm armv8-a {
    .word 0xd53be040          // mrs x0, cntvct_el0
}

The widths are GNU as's, per target, and .word is the one that differs:

Directivex86-64aarch64 / riscv64
.byte1 byte1 byte
.word2 bytes4 bytes
.long4 bytes4 bytes
.quad8 bytes8 bytes

Values are written in the target's byte order, so .word 0xd503201f is the aarch64 nop as its manual prints it. A non-negative value is read unsigned, and a negative one is its two's complement at the directive's width. A value the width cannot hold is refused rather than truncated, and one directive carries up to 256 payload bytes. On aarch64 a statement must emit a whole number of 4-byte instruction words, and on riscv64 a whole number of 2-byte parcels. x86-64 has no such constraint.

Cost

A raw encoding is an instruction stream the parser cannot read, so by default the block's clobber set becomes every register in every bank, and a #[constant_time] function may not contain one at all. A real mnemonic is always preferable where one exists.

Declaring a raw encoding's effects

That default is correct and expensive: with nothing held live across the statement, the allocator spills every value in a callee-saved register. A raw encoding may instead state what it writes, with a :: clause on the directive.

asm x86-64 {
    mov dx, {port}
    .byte 0xee :: writes()                 # out dx, al - reads dx and al, writes nothing
    .byte 0x0f, 0x31 :: writes(rax, rdx)   # rdtsc - lands its result in EDX:EAX
}
asm armv8-a {
    .word 0xd4000002 :: writes(x0, x1, x2, x3)   // hvc #0, returning per SMCCC
}
asm rv64i {
    .word 0xc0102573 :: writes(a0)               # csrr a0, time
}

writes() with an empty list is a declaration that the encoding writes no register. Leaving the clause off keeps the conservative default. Registers are named in the target's own vocabulary, in either bank:

TargetGeneral-purposeFloat / vector
x86-64rax to r15xmm0 to xmm15
aarch64x0 to x30, sp, xzrv0 to v31
riscv64x0 to x31, psABI aliases (a0, t0, sp, ...)f0 to f31, psABI aliases (fa0, ft0, ...)

A width spelling of a general-purpose register names the whole register, so writes(ebx) clobbers all of rbx. A lane arrangement such as v2.4s is refused. A malformed clause, an unknown register, and an unknown attribute all fail the build. A clause may only follow a data directive, so it can only narrow the conservative default. writes(...) is the only attribute.

Not checked

The compiler does not decode the payload, so it cannot verify that the bytes write only what the clause says. Under-declaring is a miscompile: the allocator will keep a value in a register the encoding overwrites. Declare everything the instruction's manual says it writes, including implicit destinations. A #[constant_time] function still refuses a data directive whether or not it is declared.

Multi-arch dispatch

Different architectures use different mnemonics, registers, and calling conventions. There is no nested arch-block construct inside asm and no asm ... or ... chain. Instead, wrap each block in $if on $mach.build.arch.

pub fun pause() {
    $if ($mach.build.arch == $mach.arch.x86_64) {
        asm x86-64 {
            pause
        }
    }
    $or ($mach.build.arch == $mach.arch.aarch64) {
        asm armv8-a {
            isb
        }
    }
    $or ($mach.build.arch == $mach.arch.riscv64) {
        asm rv64i_zihintpause {
            pause
        }
    }
}

The discarded branches do not compile, so each asm block only needs to be valid for the target its arm selects. Each is still lexed in its own instruction set's dialect, so its head must name a selection and its body must close.

From a previous major

A v6 head named an architecture: x86_64, aarch64, riscv64 or riscv32. It is refused with an `asm` head names a selection of masc's since v7, not an architecture, and mach migrate writes x86-64, armv8-a, rv64i and rv32i. A v6 body took # as a comment on every instruction set. On aarch64 and WebAssembly mach migrate writes such a comment as // and ;;.

When to use it

For operations that exist as named standard-library functions (atomics, fences, traps, the SIMD long tail) use the library API. Those wrappers already contain the arch-dispatched asm.

See also

  • Decorators - #[naked], whose body may hold only asm, #[noreturn] and #[extension]
  • Secrecy - how a #[constant_time] function validates an asm block
  • Comptime control flow - $if over $mach.build.arch