Skip to main content

offlineasm_backend/backends/
text.rs

1//! Shared plumbing for the assembly-text emitters.
2//!
3//! `offlineasm` lowers every mnemonic to the shared IR (`offlineasm_ir`) and
4//! then prints each `Inst` as one or more assembly lines. This module holds
5//! the parts that do not depend on the instruction set: resolving the IR's
6//! opaque label and symbol handles to text, formatting immediates and
7//! displacements, and small encoding predicates the per-ISA emitters share.
8//!
9//! The per-ISA printers live next door: [`text_x86`](super::text_x86),
10//! [`text_arm64`](super::text_arm64), and
11//! [`text_riscv64`](super::text_riscv64).
12
13use super::LowerCtx;
14use offlineasm_ir::{Disp, ExternId, Lbl, SymId};
15
16/// Selects the instruction set a text emitter prints.
17#[derive(Clone, Copy, PartialEq, Eq, Debug)]
18pub enum TextTarget {
19    X86_64,
20    Aarch64,
21    Riscv64,
22}
23
24impl TextTarget {
25    /// Returns the `offlineasm` backend name for this target.
26    pub fn name(self) -> &'static str {
27        match self {
28            TextTarget::X86_64 => "X86_64",
29            TextTarget::Aarch64 => "ARM64",
30            TextTarget::Riscv64 => "RISCV64",
31        }
32    }
33
34    /// Appends the directives that select this target's syntax, if any.
35    pub fn prologue(self, ctx: &mut LowerCtx) {
36        if self == TextTarget::X86_64 {
37            // The dialect is destination-first, so print Intel syntax.
38            ctx.emitter.put_str(".intel_syntax noprefix");
39            ctx.emitter.put_str("");
40        }
41    }
42
43    /// Returns this target's shared register file.
44    pub fn regs(self) -> &'static offlineasm_ir::regs::TargetRegs {
45        use offlineasm_ir::regs::{AARCH64, RISCV64, X86};
46        match self {
47            TextTarget::X86_64 => &X86,
48            TextTarget::Aarch64 => &AARCH64,
49            TextTarget::Riscv64 => &RISCV64,
50        }
51    }
52
53    /// Returns this target's expansion scratch registers.
54    pub fn scratch(self) -> offlineasm_ir::Scratch {
55        self.regs().scratch
56    }
57}
58
59/// Returns the assembler symbol for a label handle.
60///
61/// # Errors
62///
63/// Returns an error if `l` names a handle `ctx` never interned.
64pub fn label_text(ctx: &LowerCtx, l: Lbl) -> Result<String, String> {
65    match l {
66        Lbl::Bound(h) => ctx
67            .ir_labels
68            .get(h.0 as usize)
69            .cloned()
70            .ok_or_else(|| format!("unknown label handle {}", h.0)),
71        Lbl::Fresh(i) => ctx
72            .ir_fresh
73            .get(&i)
74            .cloned()
75            .ok_or_else(|| format!("unknown expansion label {}", i)),
76    }
77}
78
79/// Returns the assembler symbol for an extern handle.
80///
81/// # Errors
82///
83/// Returns an error if `e` names a handle `ctx` never interned.
84pub fn extern_text(ctx: &LowerCtx, e: ExternId) -> Result<String, String> {
85    ctx.ir_externs
86        .get(e.0 as usize)
87        .cloned()
88        .ok_or_else(|| format!("unknown extern handle {}", e.0))
89}
90
91/// Returns the label of the address-table slot holding extern `e`, emitting
92/// the slot the first time: an 8-byte pointer in `.rdata`. COFF has no GOT
93/// relocations, so far externs load their address from this slot instead,
94/// with the same instructions a GOT load uses.
95///
96/// # Errors
97///
98/// Returns an error if `e` names a handle `ctx` never interned.
99pub fn extern_slot(ctx: &mut LowerCtx, e: ExternId) -> Result<String, String> {
100    if let Some(slot) = ctx.extern_slots.get(&e.0) {
101        return Ok(slot.clone());
102    }
103    let symbol = extern_text(ctx, e)?;
104    let slot = synth_name(ctx, "extern", e.0);
105    ctx.emitter.puts(".pushsection .rdata, \"dr\"");
106    ctx.emitter.puts(".p2align 3");
107    ctx.emitter.put_str(&format!("{}:", slot));
108    ctx.emitter.puts(&format!(".quad {}", symbol));
109    ctx.emitter.puts(".popsection");
110    ctx.extern_slots.insert(e.0, slot.clone());
111    Ok(slot)
112}
113
114/// The error for an external symbol in an operand slot that does not take
115/// one. The shared expansion rejects these shapes first, so a printer only
116/// reaches this on a bug.
117pub fn extern_operand_error() -> String {
118    "an external symbol is only a `jmp`/`call` target or an address source".to_string()
119}
120
121/// Returns the assembler text for a symbolic operand slot (`{IDENT}`).
122///
123/// # Errors
124///
125/// Returns an error if `s` names a handle `ctx` never interned.
126pub fn sym_text(ctx: &LowerCtx, s: SymId) -> Result<String, String> {
127    ctx.ir_syms
128        .get(s.0 as usize)
129        .cloned()
130        .ok_or_else(|| format!("unknown symbol handle {}", s.0))
131}
132
133/// Returns the decimal text of an immediate.
134pub fn imm_text(v: i64) -> String {
135    v.to_string()
136}
137
138/// Returns the text of a displacement: a signed decimal, or the `{IDENT}` symbol.
139///
140/// # Errors
141///
142/// Returns an error if `d` is a symbol handle `ctx` never interned.
143pub fn disp_text(ctx: &LowerCtx, d: Disp) -> Result<String, String> {
144    match d {
145        Disp::Const(v) => Ok(v.to_string()),
146        Disp::Sym(s) => sym_text(ctx, s),
147    }
148}
149
150/// Reports whether `v` fits `bits` as a signed value.
151pub fn fits_signed(v: i64, bits: u32) -> bool {
152    match bits {
153        8 => v == (v as i8) as i64,
154        16 => v == (v as i16) as i64,
155        32 => v == (v as i32) as i64,
156        _ => true,
157    }
158}
159
160/// Reports whether `v` fits `bits` as an unsigned value.
161pub fn fits_unsigned(v: i64, bits: u32) -> bool {
162    v >= 0 && (v as u64) >> bits == 0
163}
164
165/// Renders `v` as a signed offset term: `""`, `" + 8"`, or `" - 8"`.
166pub fn offset_term(v: i64) -> String {
167    if v == 0 {
168        String::new()
169    } else if v > 0 {
170        format!(" + {}", v)
171    } else {
172        format!(" - {}", -v)
173    }
174}
175
176/// Returns a symbol name no other label can collide with.
177pub fn synth_name(ctx: &mut LowerCtx, tag: &str, id: u32) -> String {
178    let uid = ctx.emitter.new_uid();
179    ctx.local_symbol(&format!("__offlineasm_synth_{}_{}_{}", tag, uid, id))
180}