Skip to main content

offlineasm_ir/
lib.rs

1//! Defines the target-independent IR for offlineasm mnemonics, shared by
2//! the `offlineasm` and `onlineasm` assemblers.
3//!
4//! This crate is the single place where mnemonic *algorithms* live. Both
5//! assemblers run the same front half:
6//!
7//! ```text
8//! spelling -`Mnemonic`-> `expand()` + `Op`s -> [`Expansion`] -backend-> machine code | asm text
9//! ```
10//!
11//! * [`Mnemonic`] names the *operation*, one variant per operation rather than
12//!   one per spelling: `addp`/`addq` are the same value, and `mnem` holds one
13//!   constant per accepted spelling. [`Mnemonic::from_str`] is the crate's
14//!   only string comparison, and each frontend calls it once per instruction.
15//! * [`expand()`] turns one [`Mnemonic`] plus its `Op`s into core [`Inst`]
16//!   nodes.
17//!   Multi-instruction sequences (`truncatef2q`'s bias path,
18//!   `cq2f`'s halving path, `bcd2i`, ...) are expanded here once, using only
19//!   core nodes plus internal labels, so every backend inherits them.
20//! * Backends implement the core [`Inst`] variants with their ISA. Adding a
21//!   new backend means implementing `Inst`, never re-deriving 400+
22//!   mnemonics. `onlineasm`'s backends (`x86`/`aarch64`/`riscv64`) emit
23//!   machine code; `offlineasm`'s backends emit assembly text.
24//!
25//! # Operand order
26//!
27//! Mnemonics read destination first: `move dst, src`, and `addq dst, lhs,
28//! rhs` means `dst = lhs + rhs`. Branches and tests have no destination, so
29//! they keep `lhs, rhs, lbl` / `value, lbl`. Sources keep their relative
30//! order after the destination.
31//!
32//! # Registers
33//!
34//! [`Gpr`]/[`Fpr`] hold architecture physical numbers (x86 `rax = 0`,
35//! aarch64 `x0 = 0`, riscv `x10 = 10`, ...). Name resolution (offlineasm vreg
36//! to number, including the per-arch default maps) lives in [`regs`], so both
37//! frontends share one vocabulary.
38//!
39//! # Labels and symbols
40//!
41//! [`Label`] and [`SymId`] are opaque handles: each frontend owns a table
42//! and interprets the index its own way (`onlineasm` holds asmkit label
43//! handles and `offlineasm` holds symbol text). The IR never names either.
44//!
45//! # Implicit pairs
46//!
47//! A few nodes name no explicit register for ISA-implicit operands and use
48//! the *accumulator convention* instead: the dividend/quotient lives in the
49//! `t0` role, the high half / CAS expected value in the `t2` role
50//! (x86 `rax`/`rdx`, aarch64 `x0`/`x2`, riscv `x10`/`x12`). Each backend maps
51//! the roles to its own registers. User code keeps `t0`/`t2` mapped at their
52//! ABI homes (as the default maps do).
53//!
54//! # Pending flags
55//!
56//! `*S` ALU nodes ([`Inst::AluS`]) and every compare/test leave *pending
57//! flags*. [`Inst::FlagBranch`] and [`Inst::Adc`]/[`Inst::Sbb`] consume
58//! them. Nodes from one mnemonic expansion run back-to-back, so the
59//! state is always well-defined there. Across mnemonics it matches existing
60//! usage (`bo`/`bs`/`bz`/`bnz` directly after a flag-setting op). RISC-V has
61//! no flags: its backend materializes the predicate into a reserved scratch
62//! register, which nothing else clobbers.
63
64/// Names a general-purpose register by its architecture physical number.
65#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
66pub struct Gpr(pub u8);
67
68/// Names a floating-point or vector register by its architecture physical number.
69#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
70pub struct Fpr(pub u8);
71
72/// Identifies a code label with a frontend-owned handle.
73///
74/// The frontend owns the meaning: `onlineasm` maps the index to an asmkit
75/// label handle, `offlineasm` to a symbol name. The same handle appears in
76/// operands ([`Op::Label`]) and at [`Inst::Bind`].
77#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
78pub struct Label(pub u32);
79
80/// Identifies a symbolic operand with a frontend-owned handle.
81///
82/// Only `offlineasm` produces these, for offsets it cannot fold to an
83/// integer at compile time: the frontend renders the index as the assembler
84/// template's `{IDENT}` placeholder. `onlineasm` has no symbolic operands
85/// and rejects them.
86#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
87pub struct SymId(pub u32);
88
89/// Identifies an external symbol with a frontend-owned handle.
90///
91/// `onlineasm` maps the index to an asmkit symbol (an `ExternalName`),
92/// `offlineasm` to the symbol's assembler text.
93#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
94pub struct ExternId(pub u32);
95
96/// Says how generated code reaches an external symbol.
97#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
98pub enum Reach {
99    /// A direct PC-relative reference. The symbol must be within the
100    /// instruction's range of the code.
101    Near,
102    /// Through a pointer-sized slot in an address table next to the code,
103    /// so the symbol can be anywhere.
104    Far,
105}
106
107/// Refers to an external symbol.
108#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
109pub struct Extern {
110    pub id: ExternId,
111    pub reach: Reach,
112}
113
114/// Refers to a code label. `Bound` comes from the frontend (a concrete
115/// handle). `Fresh` labels are created by [`expand()`] for internal
116/// sequences and are scoped to one expansion. Backends must resolve them
117/// per mnemonic lowering.
118#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
119pub enum Lbl {
120    Bound(Label),
121    Fresh(u32),
122}
123
124/// Holds a memory displacement: a folded constant, a frontend-owned symbol,
125/// or the address of a code label.
126#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
127pub enum Disp {
128    Const(i32),
129    /// Holds `{IDENT}` in the `offlineasm` text template. `onlineasm` and
130    /// RISC-style backends that must fold it reject this variant.
131    Sym(SymId),
132    /// Addresses the memory at the label's address, PC-relatively. On x86-64
133    /// this is `[rip + disp32]`; on AArch64 it is the closest form, an
134    /// `ldr`/`ldrsw` literal (`A64Ldr19`, ±1 MiB). Only valid with no base
135    /// and no index. A label is never a displacement on its own: use
136    /// [`Mem::label`].
137    Label(Label),
138    /// Like [`Disp::Label`], but asks for the page-pair form on AArch64
139    /// (`adrp` + `ldr`/`str` low-12, ±4 GiB) instead of a literal load.
140    /// x86-64 lowers it exactly like [`Disp::Label`].
141    LabelFar(Label),
142}
143
144impl Disp {
145    /// Returns the constant value, or `None` when symbolic.
146    pub const fn constant(self) -> Option<i32> {
147        match self {
148            Disp::Const(v) => Some(v),
149            Disp::Sym(_) | Disp::Label(_) | Disp::LabelFar(_) => None,
150        }
151    }
152
153    /// Returns the constant value, treating a symbolic displacement as `0`.
154    ///
155    /// Machine-code backends call this only after rejecting `Disp::Sym`.
156    pub const fn const_or_zero(self) -> i32 {
157        match self {
158            Disp::Const(v) => v,
159            Disp::Sym(_) | Disp::Label(_) | Disp::LabelFar(_) => 0,
160        }
161    }
162
163    /// Returns the label this displacement addresses, if any.
164    pub const fn label(self) -> Option<Label> {
165        match self {
166            Disp::Label(l) | Disp::LabelFar(l) => Some(l),
167            Disp::Const(_) | Disp::Sym(_) => None,
168        }
169    }
170}
171
172/// Holds a resolved machine address: `disp(base, index, scale)`.
173/// Every backend lowers this. RISC backends synthesize the index/scale part
174/// with the expansion scratch registers.
175#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
176pub struct Mem {
177    /// Holds the base register. `None` selects the absolute (`[disp]`) form:
178    /// x86-64 encodes it directly, AArch64 and RISC-V 64 materialize the
179    /// address into a scratch register.
180    pub base: Option<Gpr>,
181    /// Holds the index register and scale, when present.
182    pub index: Option<(Gpr, u8)>,
183    /// Holds the displacement.
184    pub disp: Disp,
185}
186
187impl Mem {
188    /// Builds `[base + disp]`.
189    pub fn base(base: Gpr, disp: i32) -> Self {
190        Self {
191            base: Some(base),
192            index: None,
193            disp: Disp::Const(disp),
194        }
195    }
196
197    /// Builds `[disp]`, with no base register.
198    pub fn absolute(disp: Disp) -> Self {
199        Self {
200            base: None,
201            index: None,
202            disp,
203        }
204    }
205
206    /// Builds the memory at `label`'s address, PC-relatively (see
207    /// [`Disp::Label`]).
208    pub fn label(label: Label) -> Self {
209        Self::absolute(Disp::Label(label))
210    }
211
212    /// Builds the memory at `label`'s address using the long-range page-pair
213    /// form on AArch64 (see [`Disp::LabelFar`]).
214    pub fn label_far(label: Label) -> Self {
215        Self::absolute(Disp::LabelFar(label))
216    }
217
218    /// Returns the base register, or register 0 for the absolute form.
219    ///
220    /// Backends check [`Mem::base`] for the absolute form first and only
221    /// call this on a based address.
222    pub fn base_reg(&self) -> Gpr {
223        self.base.unwrap_or(Gpr(0))
224    }
225}
226
227/// Holds one operand of a mnemonic invocation.
228#[derive(Clone, Copy, PartialEq, Eq, Debug)]
229pub enum Op {
230    Imm(i64),
231    Gpr(Gpr),
232    Fpr(Fpr),
233    Mem(Mem),
234    Label(Lbl),
235    Sym(SymId),
236    /// Only `call`, `jmp`, `move`, and the `lea` family accept it.
237    Extern(Extern),
238}
239
240impl Op {
241    /// Reports whether `self` is the immediate `0`.
242    pub fn is_zero_imm(&self) -> bool {
243        matches!(self, Op::Imm(0))
244    }
245}
246
247/// Names an integer operand width.
248#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
249pub enum Width {
250    B8,
251    B16,
252    B32,
253    B64,
254}
255
256impl Width {
257    /// Returns the width in bytes.
258    pub fn bytes(self) -> u32 {
259        match self {
260            Width::B8 => 1,
261            Width::B16 => 2,
262            Width::B32 => 4,
263            Width::B64 => 8,
264        }
265    }
266
267    /// Reports whether `v` fits in `self` as a signed value.
268    pub fn fits(self, v: i64) -> bool {
269        match self {
270            Width::B8 => v == (v as i8) as i64,
271            Width::B16 => v == (v as i16) as i64,
272            Width::B32 => v == (v as i32) as i64,
273            Width::B64 => true,
274        }
275    }
276}
277
278/// Names a scalar float kind.
279#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
280pub enum FKind {
281    F32,
282    F64,
283}
284
285/// Names an integer comparison condition.
286#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
287pub enum IntCc {
288    /// Equal.
289    Eq,
290    /// Not equal.
291    Ne,
292    /// Unsigned above (`>`, x86 `a`).
293    Hi,
294    /// Unsigned above-or-equal (`>=`, x86 `ae`).
295    Hs,
296    /// Unsigned below (`<`, x86 `b`).
297    Lo,
298    /// Unsigned below-or-equal (`<=`, x86 `be`).
299    Ls,
300    /// Signed greater-than.
301    Gt,
302    /// Signed greater-or-equal.
303    Ge,
304    /// Signed less-than.
305    Lt,
306    /// Signed less-or-equal.
307    Le,
308}
309
310/// Names a float comparison condition.
311#[allow(dead_code)]
312#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
313pub enum FCc {
314    /// Equal.
315    Eq,
316    /// Not equal.
317    Ne,
318    /// Greater than.
319    Gt,
320    /// Greater than or equal.
321    Ge,
322    /// Less than.
323    Lt,
324    /// Less than or equal.
325    Le,
326    /// Unordered-or-equal (x86 `je` after `ucomi*`).
327    EqUn,
328    /// Unordered-or-not-equal.
329    NeUn,
330    /// Unordered-or-greater.
331    GtUn,
332    /// Unordered-or-greater-or-equal.
333    GeUn,
334    /// Unordered-or-less.
335    LtUn,
336    /// Unordered-or-less-or-equal.
337    LeUn,
338}
339
340/// Names a pending-flag predicate.
341#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
342pub enum PredFlag {
343    /// Overflow (x86 `o`, ARM `vs`).
344    O,
345    /// Sign / minus (x86 `s`, ARM `mi`).
346    S,
347    /// Zero / equal (x86 `z`, ARM `eq`).
348    Z,
349    /// Not-zero (x86 `nz`, ARM `ne`).
350    Nz,
351}
352
353/// Names a value test.
354#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
355pub enum TestKind {
356    /// Sign bit set (`bts*`, `t*s`).
357    Sign,
358    /// Whole value zero (`bt*z`, `t*z`).
359    Zero,
360    /// Whole value nonzero (`bt*nz`, `t*nz`).
361    NonZero,
362}
363
364/// Names a shift or rotate operation.
365#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
366pub enum ShiftOp {
367    /// Shift left.
368    Shl,
369    /// Shift right, sign-extending.
370    ShrSar,
371    /// Shift right, zero-filling.
372    Shr,
373    /// Rotate left.
374    Rotl,
375    /// Rotate right.
376    Rotr,
377}
378
379/// Names a float rounding mode.
380#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
381pub enum RoundMode {
382    /// To nearest.
383    Nearest,
384    /// Toward negative infinity.
385    Down,
386    /// Toward positive infinity.
387    Up,
388    /// Toward zero.
389    Trunc,
390}
391
392/// Names a jump or call target.
393#[derive(Clone, PartialEq, Eq, Debug)]
394pub enum Target {
395    Label(Lbl),
396    Reg(Gpr),
397    Mem(Mem),
398    Abs(i64),
399    Extern(Extern),
400}
401
402/// Supplies the scratch registers an expansion may use.
403#[derive(Clone, Copy, Debug)]
404pub struct Scratch {
405    /// First scratch GPR.
406    pub gpr: Gpr,
407    /// Second scratch GPR.
408    pub gpr2: Gpr,
409    /// Scratch FPR.
410    pub fpr: Fpr,
411}
412
413/// Reports a mnemonic expansion failure.
414#[derive(Clone, Debug, PartialEq, Eq)]
415pub enum ExpandError {
416    /// Unknown mnemonic spelling.
417    UnknownMnemonic(String),
418    /// Wrong operand count or kind.
419    BadOperand { mnemonic: String, msg: String },
420    /// Patch requested on a non-patchable mnemonic.
421    NotPatchable(String),
422}
423
424impl ExpandError {
425    /// Replaces the mnemonic spelling carried by `self`.
426    pub fn renamed(self, spelling: &str) -> Self {
427        match self {
428            ExpandError::UnknownMnemonic(_) => ExpandError::UnknownMnemonic(spelling.to_string()),
429            ExpandError::BadOperand { msg, .. } => ExpandError::BadOperand {
430                mnemonic: spelling.to_string(),
431                msg,
432            },
433            ExpandError::NotPatchable(_) => ExpandError::NotPatchable(spelling.to_string()),
434        }
435    }
436}
437
438impl std::fmt::Display for ExpandError {
439    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
440        match self {
441            ExpandError::UnknownMnemonic(m) => write!(f, "unknown mnemonic `{}`", m),
442            ExpandError::BadOperand { mnemonic, msg } => {
443                write!(f, "`{}`: bad operand: {}", mnemonic, msg)
444            }
445            ExpandError::NotPatchable(m) => {
446                write!(
447                    f,
448                    "`{}` cannot be a patch site (use jmp/call/branch/move-imm)",
449                    m
450                )
451            }
452        }
453    }
454}
455
456impl std::error::Error for ExpandError {}
457
458pub mod expand;
459pub mod inst;
460pub mod mnemonic;
461pub mod regs;
462pub mod riscv;
463
464pub use expand::{
465    aligned_push_bytes, aligned_push_offset, check_callee_saved, expand, patch_kind, Expansion,
466    PatchKind,
467};
468pub use inst::*;
469pub use mnemonic::{mnem, LeaForm, Mnemonic, SUPPORTED_MNEMONICS};
470pub use regs::{RegInfo, RegKind, TargetRegs, VReg, TARGETS};
471
472// Layout budget: emission keeps one expansion inline on the stack, so the IR
473// node types must stay small. These fire at compile time when a change grows
474// past what `Expansion` was sized for; grow `EXPANSION_INLINE` or accept the
475// spill consciously instead of deleting them.
476const _: () = {
477    assert!(
478        core::mem::size_of::<Op>() <= 16,
479        "Op grew past the 16-byte inline budget"
480    );
481    assert!(
482        core::mem::size_of::<Inst>() <= 72,
483        "Inst grew past the 72-byte inline budget"
484    );
485    assert!(
486        core::mem::size_of::<BranchArgs>() <= 56,
487        "BranchArgs grew past the 56-byte inline budget"
488    );
489};