Skip to main content

rucc_asm/
lib.rs

1//! Instruction encoders, the integrated assembler, inline assembly and relaxation.
2//!
3//! Design: `spec/11-asm-objects-debug.md`. Layer rank 11, see `spec/18-package-layout.md`.
4//!
5//! # Status
6//!
7//! What is written are the two things a compiler does with a machine function: the assembly text
8//! `-S` produces, which is [`print()`], and the bytes of a text section, which is [`assemble`].
9//! Section 11.1 asks for one instruction description behind both, and there is one: the walk over
10//! a function is the same walk in both files, reading the same list out of `rucc-target`, and the
11//! only difference is whether an instruction is written down by name or handed to the encoder. So
12//! the listing and the object file cannot come to disagree about what an instruction is.
13//!
14//! What [`assemble`] hands back with the bytes is what the linker has to be told: where each
15//! function starts and how long it is, and every place in the bytes that names something this
16//! file does not contain. The jumps inside a function are not among them, because by the end of a
17//! function every block has a place and they are filled in here.
18//!
19//! The variables a file defines are here for the same reason and in the same shape. [`globals`] is
20//! the one walk over a module's globals, and what it gives back is a list of pieces that
21//! [`print()`] writes down as directives and [`Globals::image`] writes down as bytes, so a `.long`
22//! in a listing and the four bytes in the object beside it cannot come to disagree either. Where a
23//! variable goes is worked out there rather than named by the front end, and what a section is
24//! called is the object format's business.
25//!
26//! [`read`] is the other direction: a file of assembly that somebody else wrote, turned into the
27//! sections and names an object is written from. The directives and the labels are one half of it
28//! and the instructions are the other, and a mnemonic with no bytes behind it is refused by name
29//! with its line number rather than skipped. Nothing there describes the machine a second time:
30//! the bytes of an instruction come from the one encoder in `rucc-target` that the compiler's own
31//! output goes through, so a file this assembles and a file this compiles cannot disagree about
32//! what an instruction is. Branch relaxation is not here yet, so a jump is four bytes of distance
33//! whether it needs them or not, which is correct and longer than gas would have written.
34//!
35//! Every crate in the workspace is published, and publishing implies a promise. This one is
36//! tier 3: its Rust API is explicitly unstable and will change without a major version bump.
37//! Depend on the `rucc` binary's behaviour, not on this.
38
39#![doc(html_root_url = "https://docs.rs/rucc-asm/0.10.67")]
40
41mod att;
42mod bytes;
43mod data;
44mod format;
45mod instruction;
46mod source;
47mod unwind;
48
49pub use crate::att::print;
50pub use crate::bytes::assemble;
51pub use crate::data::{Globals, Piece, Variable, aliases, globals};
52pub use crate::format::Directives;
53pub use crate::source::{Trouble, read};
54
55use std::fmt;
56
57/// The milestone in `spec/17-milestones.md` that fills this crate in.
58pub const MILESTONE: &str = "M3";
59
60/// A function this compiler could not write out as assembly.
61///
62/// Neither of these is a program's fault and neither should ever reach a user, since a machine
63/// function that reaches here has been through the whole backend and the tests pin both of the
64/// claims below. They are errors rather than assertions because the alternative to reporting one
65/// is writing a listing that is quietly wrong, and a wrong listing is the failure section 11.1 is
66/// written to prevent.
67#[derive(Debug, Clone, PartialEq, Eq)]
68pub enum Error {
69    /// An opcode the target has no description of.
70    Opcode {
71        /// The function it turned up in.
72        func: String,
73        /// The opcode, as the machine IR spells it.
74        opcode: String,
75    },
76    /// A register that is still virtual, which is a function that was never allocated.
77    Virtual {
78        /// The function it turned up in.
79        func: String,
80        /// The opcode the register is an operand of.
81        opcode: String,
82    },
83    /// An instruction the description names and the encoder could not write bytes for.
84    ///
85    /// The two halves of the description are meant to hold the same instructions, and a test
86    /// pins that they do, so this is either a row that was left out of one of them or an
87    /// operand the machine cannot express in the instruction that was chosen for it.
88    Encode {
89        /// The function it turned up in.
90        func: String,
91        /// The opcode, as the machine IR spells it.
92        opcode: String,
93        /// What the encoder said, already formatted.
94        why: String,
95    },
96    /// A jump inside a function to somewhere more than two gigabytes away.
97    ///
98    /// A single function that long is not a program anybody wrote, and the four bytes a jump
99    /// carries are all there are, so this is reported rather than wrapped around into a jump
100    /// somewhere else entirely.
101    Distance {
102        /// The function it turned up in.
103        func: String,
104        /// How far the jump would have had to reach.
105        bytes: i64,
106    },
107    /// A machine this crate cannot write assembly for.
108    Machine {
109        /// The triple that was asked for.
110        triple: String,
111    },
112    /// A thread-local variable on a format that does not spell one the way ELF does.
113    ///
114    /// The only one of these that is about a program rather than about this compiler. ELF says a
115    /// thread-local variable with a section flag and a symbol type, and that is written. Windows
116    /// hands out an index at load time and reaches the variable through a table the index names,
117    /// and Mach-O puts a descriptor in front of every one and reaches it by calling through the
118    /// descriptor, so on those two one is refused rather than written out as an ordinary variable
119    /// that every thread would share.
120    Thread {
121        /// The variable, as the C program spelled it.
122        name: String,
123        /// The object format that has no writing of one here, as its own name.
124        format: &'static str,
125    },
126    /// An ifunc, which is not a mistake and not written yet.
127    ///
128    /// The other thing an alias in the IR can be, and a different job from a second name for
129    /// something: the symbol is resolved once at program start by calling a function in this
130    /// object, which wants a symbol type of its own and a relocation of its own. One is refused
131    /// rather than written as an ordinary alias that would go to the resolver instead of to what
132    /// the resolver picked.
133    IFunc {
134        /// The name it defines, as the C program spelled it.
135        name: String,
136    },
137    /// A prologue the target's unwind table has no way to describe.
138    ///
139    /// ELF carries a little program per function and can say anything an instruction did to the
140    /// frame. Windows carries a fixed list of codes instead, each one of a handful of shapes a
141    /// prologue is allowed to have, and a prologue outside that list has no spelling there. The
142    /// one this compiler writes that does not fit is the frame pointer form, which establishes the
143    /// pointer before it takes the frame, so the table is refused rather than written describing a
144    /// frame of the wrong size. A build that does not want a table at all is the way past it, which
145    /// is `-fno-asynchronous-unwind-tables -fno-unwind-tables`.
146    Frame {
147        /// The function it turned up in.
148        func: String,
149        /// What about its prologue, already formatted.
150        why: String,
151    },
152    /// A piece of an initializer nothing here can write down.
153    Image {
154        /// The variable it is part of.
155        name: String,
156        /// What about it, already formatted.
157        why: String,
158    },
159}
160
161impl fmt::Display for Error {
162    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163        match self {
164            Error::Opcode { func, opcode } => {
165                write!(f, "'{func}' has a '{opcode}' and the target does not say what one is")
166            }
167            Error::Virtual { func, opcode } => {
168                write!(f, "'{func}' reached the assembler with a virtual register in a '{opcode}'")
169            }
170            Error::Encode { func, opcode, why } => {
171                write!(f, "'{func}' has a '{opcode}' the encoder refused: {why}")
172            }
173            Error::Distance { func, bytes } => {
174                write!(f, "'{func}' has a jump reaching {bytes} bytes, which does not fit in four")
175            }
176            Error::Machine { triple } => {
177                write!(f, "there is no assembly writer for {triple} in this compiler yet")
178            }
179            Error::Thread { name, format } => {
180                write!(f, "'{name}' is thread-local, which is not written on {format} yet")
181            }
182            Error::IFunc { name } => {
183                write!(f, "'{name}' is an ifunc, which this compiler does not write yet")
184            }
185            Error::Frame { func, why } => {
186                write!(f, "'{func}' has {why}, which no unwind table here can describe")
187            }
188            Error::Image { name, why } => {
189                write!(f, "the initializer of '{name}' has {why} in it, which cannot be written")
190            }
191        }
192    }
193}
194
195#[cfg(test)]
196mod tests {
197    #[test]
198    fn milestone_is_recorded() {
199        assert!(super::MILESTONE.starts_with('M'));
200    }
201}