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    /// Three kinds of them. Naming the register an argument arrived in, where an argument is
105    /// depends on its position in the signature and on the classification of every argument before
106    /// it, and a rule pattern sees one term and has no way to say any of that, so `crate::abi`
107    /// builds these from the convention instead. Calling a name is the same the other way round:
108    /// what its operands are is whatever the signature made them, and a call through an address is
109    /// the same instruction with one operand more.
110    ///
111    /// The second half of a value that comes back in two registers is the third. A return of one
112    /// value is a rule, because where that value goes depends on nothing but the value, which is
113    /// exactly what a rule can say. A return of two is not, because which register the second half
114    /// is in depends on the first half: the two register files are counted separately, so a
115    /// `double` and a `long` both come back at place zero and two `long`s do not.
116    const CONVENTION: &[&str] = &[
117        "arg_val_8",
118        "arg_val_16",
119        "arg_val_32",
120        "arg_val_64",
121        "arg_val_f32",
122        "arg_val_f64",
123        "ret_val2_8",
124        "ret_val2_16",
125        "ret_val2_32",
126        "ret_val2_64",
127        "ret_val2_f32",
128        "ret_val2_f64",
129        "call",
130        "call_reg",
131    ];
132
133    /// The instructions the block layout writes rather than a rule.
134    ///
135    /// A rule sees one branch and the layout is about the order of every block in the function, so
136    /// which arm falls through is not something any pattern could say. That answer is what decides
137    /// whether the jump goes to the arm the condition is true for or the other one, and whether
138    /// there is a second jump after it, so all four of these are written where the answer is.
139    const LAYOUT: &[&str] = &["test_rr_8", "jcc_e", "jcc_ne", "jmp"];
140
141    /// The instructions a frame writes rather than a rule.
142    ///
143    /// A prologue, an epilogue, a copy, a spill and a reload are not in the program. They are what
144    /// the allocator's answer costs, so they are written after it, by `crate::finish` reading
145    /// `x86_64::FRAME`. Six of the names that describes are already reachable from a rule, since a
146    /// prologue taking its frame is a subtraction and a spill is a store, and those are not here:
147    /// this is only the ones nothing else can reach.
148    const FRAME: &[&str] =
149        &["push_64", "pop_64", "ret", "mov_rr_64", "movaps_rr", "movaps_rm", "movaps_mr"];
150
151    /// The instructions no rule selects yet, because the rules that selected them were taken out.
152    ///
153    /// A different kind of exemption from the three above. Those say an instruction is written
154    /// somewhere a rule cannot reach and always will be. These say nobody reaches one at all right
155    /// now, and name the work that puts the rules back.
156    ///
157    /// The rules went out under `tamnd/rucc#368`. C promotes the operands of an arithmetic
158    /// operator to `int`, so a byte add and a two byte compare are things no C program asks the
159    /// back end for, and the rules at those widths sat proved and never selected over the whole
160    /// torture corpus at every optimization level. The width narrowing pass in `tamnd/rucc#375` is
161    /// what asks for them, and the rules come back with it.
162    ///
163    /// The descriptions stayed. A description says what an x86-64 instruction is, how long it is
164    /// and how it encodes, and that is true whether or not anything selects it. Taking them out
165    /// would be deleting a correct account of the machine to make a list shorter, and putting them
166    /// back is then a second thing to get right rather than a line of a rule file.
167    const NARROW: &[&str] = &[
168        // The two address arithmetic, one entry per width. `and_rr_8`, `or_rr_8` and `xor_rr_8`
169        // are not here because the one bit rules select them: a one bit value lives in a byte
170        // register and its `and`, `or` and `xor` are the byte forms.
171        "add_rr_8",
172        "add_rr_16",
173        "sub_rr_8",
174        "sub_rr_16",
175        "and_rr_16",
176        "xor_rr_16",
177        "imul_rr_8",
178        "imul_rr_16",
179        // The same against an immediate.
180        "or_ri_8",
181        "or_ri_16",
182        "xor_ri_8",
183        "xor_ri_16",
184        "imul_ri_8",
185        "imul_ri_16",
186        // One operand.
187        "neg_r_8",
188        "neg_r_16",
189        "not_r_8",
190        "not_r_16",
191        // The divides, which are four instructions per width because the quotient and the
192        // remainder come out of one division in two different registers.
193        "idiv_quo_8",
194        "idiv_quo_16",
195        "idiv_rem_8",
196        "idiv_rem_16",
197        "div_quo_8",
198        "div_quo_16",
199        "div_rem_8",
200        "div_rem_16",
201        // The shifts by a value, whose count is in `cl` whatever the width being shifted is.
202        "shl_rcl_8",
203        "shl_rcl_16",
204        "shr_rcl_8",
205        "shr_rcl_16",
206        "sar_rcl_8",
207        "sar_rcl_16",
208        // The compares. A comparison in C promotes its operands the same way an addition does, so
209        // the narrow forms of the ten conditions are unreachable for the same reason. The `ne`
210        // forms are not here: a truth test on a narrow scalar is a compare against zero at that
211        // scalar's own width, so `char c; if (c)` selects `cmp_set_ne_8`.
212        "cmp_set_e_8",
213        "cmp_set_e_16",
214        "cmp_set_l_8",
215        "cmp_set_l_16",
216        "cmp_set_le_8",
217        "cmp_set_le_16",
218        "cmp_set_g_8",
219        "cmp_set_g_16",
220        "cmp_set_ge_8",
221        "cmp_set_ge_16",
222        "cmp_set_b_8",
223        "cmp_set_b_16",
224        "cmp_set_be_8",
225        "cmp_set_be_16",
226        "cmp_set_a_8",
227        "cmp_set_a_16",
228        "cmp_set_ae_8",
229        "cmp_set_ae_16",
230        // A one bit value widened to a byte or to two bytes, which nothing asks for at either
231        // width. The four byte and eight byte forms are what a `_Bool` read turns into.
232        "bit_to_8",
233        "bit_to_16",
234    ];
235
236    #[test]
237    fn every_instruction_exempt_from_a_rule_is_one_a_frame_really_writes() {
238        // The same claim as the one about the convention, so that this list cannot grow an opcode
239        // that no frame asks for. In the order `x86_64::FRAME` names them, the moves last because
240        // there is one set of them per class the allocator may spill.
241        let frame = &x86_64::FRAME;
242        let mut written = vec![frame.push, frame.pop, frame.ret];
243        for class in frame.classes {
244            written.extend([class.mov, class.load, class.store]);
245        }
246        // What is left after the ones a rule already reaches, which are the loads and the stores
247        // of a general purpose register, since those are the same instructions a program's own
248        // reads and writes of memory are.
249        written.retain(|opcode| !heads().contains(&format!("{PREFIX}{opcode}").as_str()));
250        assert_eq!(written, FRAME);
251    }
252
253    #[test]
254    fn every_instruction_exempt_from_a_rule_is_one_the_convention_really_writes() {
255        // An exemption list that nothing checks is a hole, since an opcode dropped into it stops
256        // being covered by either direction of the pinning. These are the ones `crate::abi` can
257        // name, at the four integer widths and the two float formats it has names for an
258        // argument in, and no others.
259        let strip = |head: &'static str| head.strip_prefix(PREFIX).expect("an x86-64 term");
260        let named = |ty| strip(crate::abi::head_of(ty).expect("every width the pseudos cover"));
261        // The second half of a pair at place one, which is the place a rule cannot name. The first
262        // half at place zero is `ret_val_*` and is reached by a rule, so it is not on this list.
263        let second = |ty| strip(crate::abi::ret_of(ty, 1).expect("every width the pseudos cover"));
264        let widths = || {
265            [8, 16, 32, 64]
266                .into_iter()
267                .map(rucc_ir::Type::int)
268                .chain([rucc_ir::Float::F32, rucc_ir::Float::F64].map(rucc_ir::Type::float))
269        };
270        let written: Vec<&str> = widths()
271            .map(named)
272            .chain(widths().map(second))
273            .chain([strip(crate::abi::CALL), strip(crate::abi::CALL_REG)])
274            .collect();
275        assert_eq!(written, CONVENTION);
276    }
277
278    #[test]
279    fn every_described_instruction_is_reachable_from_a_rule() {
280        let written = heads();
281        for &(opcode, _) in x86_64::INSTS {
282            if CONVENTION.contains(&opcode) || LAYOUT.contains(&opcode) || FRAME.contains(&opcode) {
283                continue;
284            }
285            if NARROW.contains(&opcode) {
286                continue;
287            }
288            let head = format!("{PREFIX}{opcode}");
289            assert!(
290                written.contains(&head.as_str()),
291                "{opcode} is described and no rule in {} selects it",
292                TABLE.source
293            );
294        }
295    }
296
297    /// The staleness rule every list in this project is kept under, on the one list here whose
298    /// entries are meant to leave. A rule that starts selecting one of these is `tamnd/rucc#375`
299    /// arriving, and the entry goes with it. An entry naming an instruction nothing describes is a
300    /// misspelling, and it would sit here exempting nothing.
301    #[test]
302    fn an_instruction_a_rule_now_selects_is_off_the_list_of_the_ones_left_for_later() {
303        let written = heads();
304        for &opcode in NARROW {
305            let head = format!("{PREFIX}{opcode}");
306            assert!(
307                !written.contains(&head.as_str()),
308                "a rule in {} selects {opcode} now, so it is not waiting on tamnd/rucc#375",
309                TABLE.source
310            );
311            assert!(
312                x86_64::INSTS.iter().any(|&(described, _)| described == opcode),
313                "{opcode} is not an instruction anything describes"
314            );
315        }
316    }
317}