Skip to main content

rucc_codegen/select/
x86_64.rs

1//! The x86-64 lowering table.
2//!
3//! Everything below the module comment is generated from `rules/x86-64.rules` by `rucc-rules`
4//! when this crate is built, and none of it is in the repository. The rule file is the only
5//! place the rules are written, which is what makes the table that is matched with and the
6//! table `rucc-verify` proves things about the same table.
7//!
8//! To read the rules, read the rule file. To read the automaton they compile into, build the
9//! crate and read `x86-64.rs` under the build directory, which is a file worth looking at once
10//! for the shape of it and never again.
11
12// A guard is emitted as the comparison the rule writes, so a rule saying a shift count is at
13// least zero and less than the width comes out as two comparisons rather than as a range. That
14// is deliberate: the generated line and the rule it came from should read the same, and the
15// suggestion to write it another way is advice for somebody editing code, which nobody here is.
16#![allow(clippy::manual_range_contains)]
17
18include!(concat!(env!("OUT_DIR"), "/x86-64.rs"));
19
20#[cfg(test)]
21mod tests {
22    use rucc_target::x86_64;
23
24    use super::TABLE;
25    use crate::select::Piece;
26
27    /// The prefix a rule file puts in front of a machine term, which is how it says which target
28    /// the term belongs to. It is not part of the opcode.
29    const PREFIX: &str = "x64.";
30
31    /// The two address constructors, which are not instructions. An addressing mode is an
32    /// argument to `lea` and to every memory operand after it, so it is written as a term in the
33    /// rule file and built by the selector into the instruction that takes it.
34    const AMODES: &[&str] =
35        &["amode_base_index_scale", "amode_index_scale", "amode_base", "amode_base_offset"];
36
37    /// Every head this table can write, in and under the replacements.
38    fn heads() -> Vec<&'static str> {
39        let mut found: Vec<&'static str> = TABLE
40            .rules
41            .iter()
42            .flat_map(|rule| rule.replacement.iter())
43            .filter_map(|piece| match piece {
44                Piece::App { head, .. } => Some(*head),
45                _ => None,
46            })
47            .collect();
48        found.sort_unstable();
49        found.dedup();
50        found
51    }
52
53    #[test]
54    fn every_instruction_the_table_writes_is_described() {
55        for head in heads() {
56            if AMODES.contains(&head) {
57                continue;
58            }
59            let opcode = head.strip_prefix(PREFIX).unwrap_or_else(|| {
60                panic!("{head} is neither an x86-64 term nor an addressing mode")
61            });
62            assert!(
63                x86_64::form(opcode).is_some(),
64                "{head} is selected by a rule and `rucc_target::x86_64` does not say what it \
65                 does with its operands"
66            );
67        }
68    }
69
70    /// The order the operands of a store are written in, which is the IR's and not a choice this
71    /// file makes.
72    ///
73    /// A pattern is matched against an instruction's operand list by position, so a rule that
74    /// names the address where the IR holds the value is a rule that stores to the value and
75    /// writes the address into memory. Nothing in a proof would catch it, because a proof is
76    /// about the rule file agreeing with itself, and both halves would be wrong in the same way.
77    /// `rucc_ir::Builder::store` takes the value first and the machine instruction takes it last,
78    /// which is why the two halves of one of these rules read in opposite orders.
79    #[test]
80    fn a_store_is_written_with_the_value_first_because_that_is_where_the_ir_keeps_it() {
81        let mut seen = 0;
82        for rule in TABLE.rules {
83            let Some(rest) = rule.pattern.strip_prefix("(store.") else { continue };
84            let (width, operands) = rest.split_once(' ').expect("a store takes operands");
85            assert!(
86                operands.starts_with(&format!("(value.{width} ")),
87                "line {}: {} binds something other than the value it is storing first",
88                rule.line,
89                rule.pattern
90            );
91            assert!(
92                operands.contains("(value.i64 "),
93                "line {}: {} reaches no address",
94                rule.line,
95                rule.pattern
96            );
97            seen += 1;
98        }
99        assert_eq!(seen, 12, "the store rules moved and this test did not follow them");
100    }
101
102    /// The instructions the calling convention writes rather than a rule.
103    ///
104    /// Two kinds of them. Naming the register an argument arrived in, where an argument is depends
105    /// on its position in the signature and on the classification of every argument before it,
106    /// and a rule pattern sees one term and has no way to say any of that, so `crate::abi` builds
107    /// these from the convention instead. Calling a name is the same the other way round: what its
108    /// operands are is whatever the signature made them, and a call through an address is the same
109    /// instruction with one operand more. The return is not here, because where a return value
110    /// goes depends on nothing but the value, which is exactly what a rule can say.
111    const CONVENTION: &[&str] = &[
112        "arg_val_8",
113        "arg_val_16",
114        "arg_val_32",
115        "arg_val_64",
116        "arg_val_f32",
117        "arg_val_f64",
118        "call",
119        "call_reg",
120    ];
121
122    /// The instructions the block layout writes rather than a rule.
123    ///
124    /// A rule sees one branch and the layout is about the order of every block in the function, so
125    /// which arm falls through is not something any pattern could say. That answer is what decides
126    /// whether the jump goes to the arm the condition is true for or the other one, and whether
127    /// there is a second jump after it, so all four of these are written where the answer is.
128    const LAYOUT: &[&str] = &["test_rr_8", "jcc_e", "jcc_ne", "jmp"];
129
130    /// The instructions a frame writes rather than a rule.
131    ///
132    /// A prologue, an epilogue, a copy, a spill and a reload are not in the program. They are what
133    /// the allocator's answer costs, so they are written after it, by `crate::finish` reading
134    /// `x86_64::FRAME`. Six of the names that describes are already reachable from a rule, since a
135    /// prologue taking its frame is a subtraction and a spill is a store, and those are not here:
136    /// this is only the ones nothing else can reach.
137    const FRAME: &[&str] =
138        &["push_64", "pop_64", "ret", "mov_rr_64", "movaps_rr", "movaps_rm", "movaps_mr"];
139
140    #[test]
141    fn every_instruction_exempt_from_a_rule_is_one_a_frame_really_writes() {
142        // The same claim as the one about the convention, so that this list cannot grow an opcode
143        // that no frame asks for. In the order `x86_64::FRAME` names them, the moves last because
144        // there is one set of them per class the allocator may spill.
145        let frame = &x86_64::FRAME;
146        let mut written = vec![frame.push, frame.pop, frame.ret];
147        for class in frame.classes {
148            written.extend([class.mov, class.load, class.store]);
149        }
150        // What is left after the ones a rule already reaches, which are the loads and the stores
151        // of a general purpose register, since those are the same instructions a program's own
152        // reads and writes of memory are.
153        written.retain(|opcode| !heads().contains(&format!("{PREFIX}{opcode}").as_str()));
154        assert_eq!(written, FRAME);
155    }
156
157    #[test]
158    fn every_instruction_exempt_from_a_rule_is_one_the_convention_really_writes() {
159        // An exemption list that nothing checks is a hole, since an opcode dropped into it stops
160        // being covered by either direction of the pinning. These are the ones `crate::abi` can
161        // name, at the four integer widths and the two float formats it has names for an
162        // argument in, and no others.
163        let strip = |head: &'static str| head.strip_prefix(PREFIX).expect("an x86-64 term");
164        let named = |ty| strip(crate::abi::head_of(ty).expect("every width the pseudos cover"));
165        let written: Vec<&str> = [8, 16, 32, 64]
166            .into_iter()
167            .map(|bits| named(rucc_ir::Type::int(bits)))
168            .chain(
169                [rucc_ir::Float::F32, rucc_ir::Float::F64]
170                    .map(|at| named(rucc_ir::Type::float(at))),
171            )
172            .chain([strip(crate::abi::CALL), strip(crate::abi::CALL_REG)])
173            .collect();
174        assert_eq!(written, CONVENTION);
175    }
176
177    #[test]
178    fn every_described_instruction_is_reachable_from_a_rule() {
179        let written = heads();
180        for &(opcode, _) in x86_64::INSTS {
181            if CONVENTION.contains(&opcode) || LAYOUT.contains(&opcode) || FRAME.contains(&opcode) {
182                continue;
183            }
184            let head = format!("{PREFIX}{opcode}");
185            assert!(
186                written.contains(&head.as_str()),
187                "{opcode} is described and no rule in {} selects it",
188                TABLE.source
189            );
190        }
191    }
192}