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, 14, "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 instruction the memory model writes rather than a rule.
142    ///
143    /// A barrier computes nothing, so there is no equality for the solver to discharge and no
144    /// pattern for a rule to be written as. What makes it the right answer is what the machine
145    /// promises about the order two other instructions become visible in, which is a claim about
146    /// the program around it rather than about any value. `crate::lower` writes it by name, at the
147    /// strongest ordering and nowhere else, and `crate::expand` says why the strongest is the only
148    /// one that costs anything here.
149    const BARRIER: &[&str] = &["mfence"];
150
151    /// The instructions that produce two values, which is one more than a rule can name.
152    ///
153    /// A rule replaces a term with a term, and a term is the value one instruction computes. A
154    /// compare and exchange computes two: what it found at the address, and whether what it found
155    /// was what the program expected. There is no way to write the second one down in the rule
156    /// language, and inventing one would be inventing a language for a single instruction.
157    ///
158    /// So `crate::lower` writes it by name, the way it writes the barrier by name, and for a reason
159    /// that is about the rule language rather than about the machine. What the solver would have
160    /// been asked to prove about it is the easy half in any case: the arithmetic is a comparison
161    /// and a select, and what is hard is that the whole of it happens at once, which is the same
162    /// claim about the program around it that a barrier makes.
163    const ATOMIC: &[&str] = &["cmpxchg_8", "cmpxchg_16", "cmpxchg_32", "cmpxchg_64"];
164
165    /// The instructions whose operation is in the payload rather than in the head.
166    ///
167    /// A different exemption from the one above, on instructions that produce one value each and so
168    /// could be named by a rule if the rule had anything to match on. The head a pattern matches is
169    /// an opcode and a type, and every read modify write in the IR is the one opcode `atomic_rmw`.
170    /// Which of the thirteen operations it performs is carried beside the instruction rather than in
171    /// its name, so a pattern written for the exchange would match the add and the nand as well, and
172    /// the rule language has no way to look at what a rule matched to tell them apart.
173    ///
174    /// Giving each operation its own opcode is the other way out and is a worse trade: it is
175    /// thirteen opcodes at four widths where the IR wants one, and every pass that treats a read
176    /// modify write as one thing would then have a list of fifty two.
177    ///
178    /// So `crate::lower` writes these by name too. Three operations here, out of the thirteen: the
179    /// bitwise ones need a loop around a compare and exchange, which is control flow and so is built
180    /// before selection rather than during it, and they are the rest of `tamnd/rucc#311`.
181    const PAYLOAD: &[&str] =
182        &["xchg_8", "xchg_16", "xchg_32", "xchg_64", "xadd_8", "xadd_16", "xadd_32", "xadd_64"];
183
184    /// The instructions a frame writes rather than a rule.
185    ///
186    /// A prologue, an epilogue, a copy, a spill and a reload are not in the program. They are what
187    /// the allocator's answer costs, so they are written after it, by `crate::finish` reading
188    /// `x86_64::FRAME`. Six of the names that describes are already reachable from a rule, since a
189    /// prologue taking its frame is a subtraction and a spill is a store, and those are not here:
190    /// this is only the ones nothing else can reach.
191    const FRAME: &[&str] =
192        &["push_64", "pop_64", "ret", "mov_rr_64", "movaps_rr", "movaps_rm", "movaps_mr"];
193
194    /// The instructions that reach the x87 stack, which are selected but not from here.
195    ///
196    /// A third kind of exemption, and the same reason all the way down the list.
197    ///
198    /// Every one of these is written by `crate::lower`, as part of a group rather than on its own.
199    /// What one of them leaves behind and the next picks up is the top of the x87 stack, which is
200    /// not a register anything allocates from and not a value a pattern could bind, so a rule
201    /// could neither match the middle of a group nor name what its replacement produced. And an
202    /// add here reads two addresses and writes a third, where one machine IR instruction carries
203    /// one addressing mode, so the group cannot be folded into a single opcode the way
204    /// `ucomisd_set_e` folds a comparison and a `setcc` either.
205    ///
206    /// So these are exempt for the reason `FRAME` is exempt rather than for the reason the list
207    /// below is, and they will stay exempt. Two of them are not reached by anything yet all the
208    /// same: `fsub_p` and `fdiv_p` are the other direction of the subtraction and the division,
209    /// which a code generator that pushed its operands the other way round would need and this one
210    /// does not. `fabs` is a third, since C spells that as a call to a library function.
211    const X87: &[&str] = &[
212        "fld_t",
213        "fstp_t",
214        "fld_s",
215        "fld_l",
216        "fild_l",
217        "fild_ll",
218        "fstp_s",
219        "fstp_l",
220        "fistp_l",
221        "fistp_ll",
222        "fnstcw",
223        "fldcw",
224        "fadd_p",
225        "fsub_p",
226        "fsubr_p",
227        "fmul_p",
228        "fdiv_p",
229        "fdivr_p",
230        "fchs",
231        "fabs",
232        "fucomip_set_a",
233        "fucomip_set_ae",
234        "fucomip_set_b",
235        "fucomip_set_be",
236        "fucomip_set_e",
237        "fucomip_set_ne",
238        "fucomip_set_p",
239        "fucomip_set_np",
240        "fucomip_set_e_and_np",
241        "fucomip_set_ne_or_p",
242    ];
243
244    /// The instructions no rule selects yet, because the rules that selected them were taken out.
245    ///
246    /// A different kind of exemption from the three above. Those say an instruction is written
247    /// somewhere a rule cannot reach and always will be. These say nobody reaches one at all right
248    /// now, and name the work that puts the rules back.
249    ///
250    /// The rules went out under `tamnd/rucc#368`. C promotes the operands of an arithmetic
251    /// operator to `int`, so a byte add and a two byte compare are things no C program asks the
252    /// back end for, and the rules at those widths sat proved and never selected over the whole
253    /// torture corpus at every optimization level. The width narrowing pass in `tamnd/rucc#375` is
254    /// what asks for them, and the rules come back with it.
255    ///
256    /// The descriptions stayed. A description says what an x86-64 instruction is, how long it is
257    /// and how it encodes, and that is true whether or not anything selects it. Taking them out
258    /// would be deleting a correct account of the machine to make a list shorter, and putting them
259    /// back is then a second thing to get right rather than a line of a rule file.
260    const NARROW: &[&str] = &[
261        // Three of the two address forms against an immediate. The `narrow` pass does write the
262        // shape, since `char c = a | 1;` narrows to a byte `or` against a byte constant, and no
263        // rule selects these yet: the constant goes into a register and the register with
264        // register rule takes it. Their `add`, `sub` and `and` siblings do have rules and are
265        // reached by the bitfield lowering, so this is six rules missing rather than a shape
266        // nothing writes.
267        "or_ri_8",
268        "or_ri_16",
269        "xor_ri_8",
270        "xor_ri_16",
271        "imul_ri_8",
272        "imul_ri_16",
273        // The divides, which are four instructions per width because the quotient and the
274        // remainder come out of one division in two different registers. `narrow` refuses these
275        // on purpose: the most negative byte over minus one is a defined hundred and twenty eight
276        // at four bytes and is the overflow that raises at one, so narrowing a division wants a
277        // range that rules the pair out and there is no range analysis yet.
278        "idiv_quo_8",
279        "idiv_quo_16",
280        "idiv_rem_8",
281        "idiv_rem_16",
282        "div_quo_8",
283        "div_quo_16",
284        "div_rem_8",
285        "div_rem_16",
286        // The shifts by a value, whose count is in `cl` whatever the width being shifted is. The
287        // same refusal for the same kind of reason: a count of twenty is a defined shift to zero
288        // at four bytes and is poison at one, so only a count that is a constant below the narrow
289        // width narrows, and that one selects the immediate forms which do have rules.
290        "shl_rcl_8",
291        "shl_rcl_16",
292        "shr_rcl_8",
293        "shr_rcl_16",
294        "sar_rcl_8",
295        "sar_rcl_16",
296    ];
297
298    #[test]
299    fn every_instruction_exempt_from_a_rule_is_one_a_frame_really_writes() {
300        // The same claim as the one about the convention, so that this list cannot grow an opcode
301        // that no frame asks for. In the order `x86_64::FRAME` names them, the moves last because
302        // there is one set of them per class the allocator may spill.
303        let frame = &x86_64::FRAME;
304        let mut written = vec![frame.push, frame.pop, frame.ret];
305        for class in frame.classes {
306            written.extend([class.mov, class.load, class.store]);
307        }
308        // What is left after the ones a rule already reaches, which are the loads and the stores
309        // of a general purpose register, since those are the same instructions a program's own
310        // reads and writes of memory are.
311        written.retain(|opcode| !heads().contains(&format!("{PREFIX}{opcode}").as_str()));
312        assert_eq!(written, FRAME);
313    }
314
315    #[test]
316    fn every_instruction_exempt_from_a_rule_is_one_the_convention_really_writes() {
317        // An exemption list that nothing checks is a hole, since an opcode dropped into it stops
318        // being covered by either direction of the pinning. These are the ones `crate::abi` can
319        // name, at the four integer widths and the two float formats it has names for an
320        // argument in, and no others.
321        let strip = |head: &'static str| head.strip_prefix(PREFIX).expect("an x86-64 term");
322        let named = |ty| strip(crate::abi::head_of(ty).expect("every width the pseudos cover"));
323        // The second half of a pair at place one, which is the place a rule cannot name. The first
324        // half at place zero is `ret_val_*` and is reached by a rule, so it is not on this list.
325        let second = |ty| strip(crate::abi::ret_of(ty, 1).expect("every width the pseudos cover"));
326        let widths = || {
327            [8, 16, 32, 64]
328                .into_iter()
329                .map(rucc_ir::Type::int)
330                .chain([rucc_ir::Float::F32, rucc_ir::Float::F64].map(rucc_ir::Type::float))
331        };
332        let written: Vec<&str> = widths()
333            .map(named)
334            .chain(widths().map(second))
335            .chain([strip(crate::abi::CALL), strip(crate::abi::CALL_REG)])
336            .collect();
337        assert_eq!(written, CONVENTION);
338    }
339
340    #[test]
341    fn every_described_instruction_is_reachable_from_a_rule() {
342        let written = heads();
343        for &(opcode, _) in x86_64::INSTS {
344            if CONVENTION.contains(&opcode) || LAYOUT.contains(&opcode) || FRAME.contains(&opcode) {
345                continue;
346            }
347            if NARROW.contains(&opcode) || BARRIER.contains(&opcode) || X87.contains(&opcode) {
348                continue;
349            }
350            if ATOMIC.contains(&opcode) || PAYLOAD.contains(&opcode) {
351                continue;
352            }
353            let head = format!("{PREFIX}{opcode}");
354            assert!(
355                written.contains(&head.as_str()),
356                "{opcode} is described and no rule in {} selects it",
357                TABLE.source
358            );
359        }
360    }
361
362    /// The same claim about the barrier as the ones above make about the convention and the frame:
363    /// the list holds instructions this target really describes, and holds only the ones that have
364    /// no operands, since an instruction with an operand is one a rule could have been written for.
365    #[test]
366    fn every_instruction_exempt_from_a_rule_is_one_the_memory_model_really_writes() {
367        for &opcode in BARRIER {
368            let form = x86_64::form(opcode).expect("an instruction this target describes");
369            assert!(form.operands().is_empty(), "{opcode} has operands, so a rule could name it");
370        }
371    }
372
373    /// The same claim about the atomic list, read off the thing that put the entry there: an
374    /// instruction is exempt for this reason exactly when it writes more than one value, and an
375    /// instruction that writes one is one a rule could have been written for.
376    #[test]
377    fn every_instruction_exempt_from_a_rule_is_one_that_writes_more_than_one_value() {
378        let written = heads();
379        for &opcode in ATOMIC {
380            let form = x86_64::form(opcode).expect("an instruction this target describes");
381            let writes = form.operands().iter().filter(|desc| desc.role.is_def()).count();
382            assert!(writes > 1, "{opcode} writes one value, so a rule could name it");
383            assert!(
384                !written.contains(&format!("{PREFIX}{opcode}").as_str()),
385                "a rule in {} selects {opcode}, which `crate::lower` also writes by hand",
386                TABLE.source
387            );
388        }
389    }
390
391    /// The same claim about the payload list, read off the thing that puts an entry there.
392    ///
393    /// Two halves. Each of these writes one value, which is what says the reason above is not the
394    /// reason here, so a list that grew to cover an instruction the atomic list should have had
395    /// fails. And there really is more than one operation behind the one IR opcode, which is the
396    /// whole of why a pattern cannot name any of them, and is a fact about the IR that would stop
397    /// being true if the operations were ever given opcodes of their own.
398    #[test]
399    fn every_instruction_exempt_because_its_operation_is_beside_it_writes_one_value() {
400        assert!(
401            rucc_ir::RmwOp::all().count() > 1,
402            "one operation per opcode would be a head a rule could match"
403        );
404        let written = heads();
405        for &opcode in PAYLOAD {
406            let form = x86_64::form(opcode).expect("an instruction this target describes");
407            let writes = form.operands().iter().filter(|desc| desc.role.is_def()).count();
408            assert_eq!(writes, 1, "{opcode} writes more than one value, so it is the other list's");
409            assert!(
410                !written.contains(&format!("{PREFIX}{opcode}").as_str()),
411                "a rule in {} selects {opcode}, which `crate::lower` also writes by hand",
412                TABLE.source
413            );
414        }
415    }
416
417    /// The staleness rule every list in this project is kept under, on the one list here whose
418    /// entries are meant to leave. A rule that starts selecting one of these is `tamnd/rucc#375`
419    /// arriving, and the entry goes with it. An entry naming an instruction nothing describes is a
420    /// misspelling, and it would sit here exempting nothing.
421    #[test]
422    fn an_instruction_a_rule_now_selects_is_off_the_list_of_the_ones_left_for_later() {
423        let written = heads();
424        for &opcode in NARROW {
425            let head = format!("{PREFIX}{opcode}");
426            assert!(
427                !written.contains(&head.as_str()),
428                "a rule in {} selects {opcode} now, so it is not waiting on tamnd/rucc#375",
429                TABLE.source
430            );
431            assert!(
432                x86_64::INSTS.iter().any(|&(described, _)| described == opcode),
433                "{opcode} is not an instruction anything describes"
434            );
435        }
436    }
437
438    /// The same staleness rule on the x87 pair, and one thing more that is particular to them.
439    ///
440    /// They are a pair. An instruction that pushes onto the x87 stack and nothing that pops off it
441    /// again would leave the stack one deeper than the function found it, which is not a mistake
442    /// the allocator or the block layout could catch, since neither of them knows the stack is
443    /// there. So the two arrive together and leave together, and that is what this says.
444    #[test]
445    fn the_x87_stack_is_reached_by_a_pair_and_by_nothing_else() {
446        let written = heads();
447        for &opcode in X87 {
448            assert!(
449                x86_64::INSTS.iter().any(|&(described, _)| described == opcode),
450                "{opcode} is not an instruction anything describes"
451            );
452            assert!(
453                !written.contains(&format!("{PREFIX}{opcode}").as_str()),
454                "a rule in {} selects {opcode}, which `crate::lower` also writes by hand",
455                TABLE.source
456            );
457        }
458        // One way onto the stack per format a value can be read from, one way off it per format a
459        // value can be written to, the control word pair that is neither, and the arithmetic. The
460        // count is here as well as in the target description because this list is what says none
461        // of them is reachable, and a name that arrived here without its partner would be a format
462        // this target can convert in one direction and not the other.
463        assert_eq!(X87.len(), 30, "twelve that move a value and eighteen that work on one");
464    }
465}