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/// What the lowering asks of x86-64.
21pub static SELECTOR: super::Selector = super::Selector {
22    table: &TABLE,
23    shapes: &rucc_target::x86_64::MACHINE,
24    address: rucc_target::x86_64::address,
25    frame: &rucc_target::x86_64::FRAME,
26    branch: &rucc_target::x86_64::BRANCH,
27    gpr: rucc_target::x86_64::GPR,
28    fence: "mfence",
29    trap: "ud2",
30    abi: &crate::abi::X86_64,
31    scratch: &crate::pipeline::SCRATCH,
32    symbols: &super::Symbols {
33        near: super::Reach::Mode("lea_64"),
34        far: super::Reach::Mode("mov_rm_64"),
35        slot: super::Reach::Mode("mov_rm_64"),
36        // The relocation a thread-local variable's slot takes is only legal on a `mov` with a REX
37        // prefix, so the width here is part of the requirement rather than a choice.
38        thread: super::Reach::Mode("mov_rm_64"),
39        pointer: super::Pointer::Segment("mov_rm_64", rucc_target::Segment::Fs),
40        indexed: Some(super::Indexed {
41            index: "mov_rm_32",
42            load: "mov_rm_64",
43            segment: rucc_target::Segment::Gs,
44            at: 0x58,
45            add: "lea_64",
46        }),
47        teb: None,
48    },
49    jumps: &super::Jumps {
50        near: "lea_64",
51        cell: "movsxd_rm_32_64",
52        add: "add_rr_64",
53        two_address: true,
54    },
55};
56
57#[cfg(test)]
58mod tests {
59    use rucc_target::x86_64;
60
61    use super::TABLE;
62    use crate::select::Piece;
63
64    /// The prefix a rule file puts in front of a machine term, which is how it says which target
65    /// the term belongs to. It is not part of the opcode.
66    const PREFIX: &str = "x64.";
67
68    /// The two address constructors, which are not instructions. An addressing mode is an
69    /// argument to `lea` and to every memory operand after it, so it is written as a term in the
70    /// rule file and built by the selector into the instruction that takes it.
71    const AMODES: &[&str] =
72        &["amode_base_index_scale", "amode_index_scale", "amode_base", "amode_base_offset"];
73
74    /// Every head this table can write, in and under the replacements.
75    fn heads() -> Vec<&'static str> {
76        let mut found: Vec<&'static str> = TABLE
77            .rules
78            .iter()
79            .flat_map(|rule| rule.replacement.iter())
80            .filter_map(|piece| match piece {
81                Piece::App { head, .. } => Some(*head),
82                _ => None,
83            })
84            .collect();
85        found.sort_unstable();
86        found.dedup();
87        found
88    }
89
90    #[test]
91    fn every_instruction_the_table_writes_is_described() {
92        for head in heads() {
93            if AMODES.contains(&head) {
94                continue;
95            }
96            let opcode = head.strip_prefix(PREFIX).unwrap_or_else(|| {
97                panic!("{head} is neither an x86-64 term nor an addressing mode")
98            });
99            assert!(
100                x86_64::form(opcode).is_some(),
101                "{head} is selected by a rule and `rucc_target::x86_64` does not say what it \
102                 does with its operands"
103            );
104        }
105    }
106
107    /// The order the operands of a store are written in, which is the IR's and not a choice this
108    /// file makes.
109    ///
110    /// A pattern is matched against an instruction's operand list by position, so a rule that
111    /// names the address where the IR holds the value is a rule that stores to the value and
112    /// writes the address into memory. Nothing in a proof would catch it, because a proof is
113    /// about the rule file agreeing with itself, and both halves would be wrong in the same way.
114    /// `rucc_ir::Builder::store` takes the value first and the machine instruction takes it last,
115    /// which is why the two halves of one of these rules read in opposite orders.
116    #[test]
117    fn a_store_is_written_with_the_value_first_because_that_is_where_the_ir_keeps_it() {
118        let mut seen = 0;
119        for rule in TABLE.rules {
120            let Some(rest) = rule.pattern.strip_prefix("(store.") else { continue };
121            let (width, operands) = rest.split_once(' ').expect("a store takes operands");
122            assert!(
123                operands.starts_with(&format!("(value.{width} ")),
124                "line {}: {} binds something other than the value it is storing first",
125                rule.line,
126                rule.pattern
127            );
128            assert!(
129                operands.contains("(value.i64 "),
130                "line {}: {} reaches no address",
131                rule.line,
132                rule.pattern
133            );
134            seen += 1;
135        }
136        assert_eq!(seen, 16, "the store rules moved and this test did not follow them");
137    }
138
139    /// Every comparison can be made against a constant as well as against a register.
140    ///
141    /// Four comparisons in five in the corpus are against a constant, and without a rule for one
142    /// the constant is loaded into a register first, which is an instruction and a register the
143    /// machine never needed. A missing width or a missing condition would not fail anything else:
144    /// the register rule still matches, the output is still correct, and the only sign is code
145    /// that is one instruction longer in a place nobody is looking. So the two lists are counted
146    /// against each other here.
147    ///
148    /// What this cannot check is that the condition on the immediate rule is the right one, since
149    /// both halves of a wrong pair would be a consistent pair. That is what the `spec` clause is
150    /// for, and `rucc-verify` is what reads it.
151    #[test]
152    fn a_comparison_against_a_constant_is_written_for_every_one_against_a_register() {
153        let mut against_register = Vec::new();
154        let mut against_constant = Vec::new();
155        for rule in TABLE.rules {
156            let Some(rest) = rule.pattern.strip_prefix("(icmp_") else { continue };
157            let (condition, operands) = rest.split_once(".i1 ").expect("a comparison takes two");
158            let width = operands
159                .strip_prefix("(value.")
160                .and_then(|rest| rest.split_once(' '))
161                .map(|(width, _)| width)
162                .expect("a comparison reads a value first");
163            let named = format!("{condition}.{width}");
164            if operands.contains("(iconst.") {
165                // The constant is the second operand and never the first, because a comparison is
166                // not symmetric and the same condition on the other side means the opposite.
167                assert!(
168                    !operands.starts_with("(iconst."),
169                    "line {}: {} compares a constant against a value",
170                    rule.line,
171                    rule.pattern
172                );
173                against_constant.push(named);
174            } else {
175                against_register.push(named);
176            }
177        }
178        against_register.sort_unstable();
179        against_constant.sort_unstable();
180        assert_eq!(against_register, against_constant);
181        assert_eq!(against_register.len(), 40, "ten conditions at four widths");
182    }
183
184    /// The instructions the calling convention writes rather than a rule.
185    ///
186    /// Three kinds of them. Naming the register an argument arrived in, where an argument is
187    /// depends on its position in the signature and on the classification of every argument before
188    /// it, and a rule pattern sees one term and has no way to say any of that, so `crate::abi`
189    /// builds these from the convention instead. Calling a name is the same the other way round:
190    /// what its operands are is whatever the signature made them, and a call through an address is
191    /// the same instruction with one operand more.
192    ///
193    /// The second half of a value that comes back in two registers is the third. A return of one
194    /// value is a rule, because where that value goes depends on nothing but the value, which is
195    /// exactly what a rule can say. A return of two is not, because which register the second half
196    /// is in depends on the first half: the two register files are counted separately, so a
197    /// `double` and a `long` both come back at place zero and two `long`s do not.
198    const CONVENTION: &[&str] = &[
199        "arg_val_8",
200        "arg_val_16",
201        "arg_val_32",
202        "arg_val_64",
203        "arg_val_f16",
204        "arg_val_f32",
205        "arg_val_f64",
206        "arg_val_f128",
207        "ret_val2_8",
208        "ret_val2_16",
209        "ret_val2_32",
210        "ret_val2_64",
211        "ret_val2_f16",
212        "ret_val2_f32",
213        "ret_val2_f64",
214        "ret_val2_f128",
215        "call",
216        "call_reg",
217    ];
218
219    /// The instructions the block layout writes rather than a rule.
220    ///
221    /// A rule sees one branch and the layout is about the order of every block in the function, so
222    /// which arm falls through is not something any pattern could say. That answer is what decides
223    /// whether the jump goes to the arm the condition is true for or the other one, and whether
224    /// there is a second jump after it, so all of these are written where the answer is.
225    ///
226    /// The comparisons are here for a second reason on top of that one. A branch on a comparison
227    /// is a comparison and a jump on the flags it set, and the flags are not a value: no pattern
228    /// could bind one and no `spec` clause could say anything about one. So the pair is put
229    /// together by the layout, out of a comparison a rule did select and the branch behind it,
230    /// which is the same argument `rucc_target::x86_64::Form::CmpSet` is one form rather than two
231    /// under.
232    /// The instructions the size directed peephole writes rather than a rule.
233    ///
234    /// [`crate::shorten`] turns a comparison of a register against zero into a test of the register
235    /// against itself, which asks the machine the same thing in one byte less, and an addition of
236    /// one into the instruction that adds one and says so in its opcode, which is another byte less.
237    /// No rule could select either. Whether the first says the same thing depends on the constant
238    /// the comparison carries and a pattern binds a value rather than reads a number out of one, and
239    /// whether the second does depends on what reads the carry behind it, which is not something a
240    /// pattern sees at all. The eight bit test is not here because the layout writes that one as
241    /// well and it is on the list below.
242    const PEEPHOLE: &[&str] = &[
243        "test_rr_16",
244        "test_rr_32",
245        "test_rr_64",
246        "inc_r_8",
247        "inc_r_16",
248        "inc_r_32",
249        "inc_r_64",
250        "dec_r_8",
251        "dec_r_16",
252        "dec_r_32",
253        "dec_r_64",
254    ];
255
256    const LAYOUT: &[&str] = &[
257        "test_rr_8",
258        "cmp_rr_8",
259        "cmp_rr_16",
260        "cmp_rr_32",
261        "cmp_rr_64",
262        "cmp_ri_8",
263        "cmp_ri_16",
264        "cmp_ri_32",
265        "cmp_ri_64",
266        "cmp_rm_8",
267        "cmp_rm_16",
268        "cmp_rm_32",
269        "cmp_rm_64",
270        "cmp_mi_8",
271        "cmp_mi_16",
272        "cmp_mi_32",
273        "cmp_mi_64",
274        "jcc_e",
275        "jcc_ne",
276        "jcc_l",
277        "jcc_le",
278        "jcc_g",
279        "jcc_ge",
280        "jcc_b",
281        "jcc_be",
282        "jcc_a",
283        "jcc_ae",
284        "jmp",
285    ];
286
287    /// The instructions the compare pass writes rather than a rule.
288    ///
289    /// The other half of the argument the comparisons above are here under. A rule selects a
290    /// comparison that keeps its answer in a byte, because that is the shape a value has. What is
291    /// left of one when the machine has already made the comparison is the byte with no comparison
292    /// in front of it, and there is no pattern for that: the term it would compute is the same term
293    /// the full comparison computes, and what makes the short one right is the instruction three
294    /// places back rather than anything about the value. So `crate::compare` writes them by name,
295    /// in place of a comparison it found was already made.
296    const COMPARE: &[&str] = &[
297        "set_e", "set_ne", "set_l", "set_le", "set_g", "set_ge", "set_b", "set_be", "set_a",
298        "set_ae",
299    ];
300
301    /// The instruction a computed `goto` is written as rather than a rule.
302    ///
303    /// The one branch `crate::lower` writes by name, and the one the block layout does not write
304    /// either. What it reads is the address, which a pattern could have bound, so it is not
305    /// exempt for the reason the branches above are. What no pattern can say is the rest of it:
306    /// how many arms the block has, which is every label of the function the program took the
307    /// address of, and a rule says what an instruction reads rather than where a block goes.
308    const LABELS: &[&str] = &["jmp_reg"];
309
310    /// The load a jump table is read with, which `crate::lower` writes by name next to the jump
311    /// above. The address it reads is a table of this function rather than a value in the IR,
312    /// and no IR instruction loads from a place that is not a value, so there is nothing a rule
313    /// could match it from.
314    const CELL: &[&str] = &["movsxd_rm_32_64"];
315
316    /// The instruction the memory model writes rather than a rule.
317    ///
318    /// A barrier computes nothing, so there is no equality for the solver to discharge and no
319    /// pattern for a rule to be written as. What makes it the right answer is what the machine
320    /// promises about the order two other instructions become visible in, which is a claim about
321    /// the program around it rather than about any value. `crate::lower` writes it by name, at the
322    /// strongest ordering and nowhere else, and `crate::expand` says why the strongest is the only
323    /// one that costs anything here.
324    const BARRIER: &[&str] = &["mfence"];
325
326    /// The instruction a program stops on, which `crate::lower` writes rather than a rule.
327    ///
328    /// The first half of the barrier's reason and not the second. It computes nothing, so there is
329    /// no equality for the solver and no pattern for a rule. What makes it right is not a claim
330    /// about the order anything becomes visible in either: it is what the operating system does
331    /// with the fault, which is a fact about neither the values nor the program around it.
332    const STOP: &[&str] = &["ud2"];
333
334    /// The instructions that are a hint rather than a computation.
335    ///
336    /// The same shape of exemption the barrier gets and for a reason one step further out. A
337    /// barrier computes nothing and still has to be where it is, so there is at least a claim about
338    /// the program around it. A prefetch does not even have that: a machine that drops the whole
339    /// instruction runs the program correctly, because the only thing it can change is how long the
340    /// program takes.
341    ///
342    /// So there is no equality for the solver and no pattern for a rule, and which of the four a
343    /// program gets is decided by a number in the builtin's own arguments rather than by anything
344    /// about the value being prefetched. `crate::lower` writes them by name, out of the hint the IR
345    /// carries beside the instruction.
346    const HINT: &[&str] = &["prefetch_nta", "prefetch_t0", "prefetch_t1", "prefetch_t2"];
347
348    /// The instructions nothing but an `asm` statement asks for.
349    ///
350    /// One step further out again. A prefetch is a hint and is still something the compiler decides
351    /// to write, out of a builtin the program called. These are instructions the program wrote down
352    /// itself, by name, in a template, and nothing else in the language reaches them: there is no
353    /// builtin for either, no rule could match a term that produces one, and `crate::lower` writes
354    /// them only because [`rucc_target::x86_64::read`] found the name in a template and said which
355    /// opcode that is.
356    ///
357    /// `pause` is the hint a spin lock writes between two tries at the lock. `cpuid` is how a
358    /// program asks the processor what it can do, which there is no other way to ask, so every
359    /// program that takes a faster path on some machines than on others has one of these in it.
360    ///
361    /// The alignment is the third, and it is on this list rather than one of its own because it
362    /// meets the claim below outright: an instruction is exempt for this reason exactly when there
363    /// is nothing about it for a rule to name, and an opcode with no operands and no addressing mode
364    /// has nothing. It is not an instruction at all, which is more than the test asks and is the
365    /// reason no rule could have been written for it however the rule language grew.
366    ///
367    /// A byte out of a template is the fourth and is there for the same reason as the alignment,
368    /// one step further still: it is not an instruction, and what it holds is a byte the program
369    /// wrote out itself because its assembler was older than the instruction it wanted. There is
370    /// nothing for a rule to have said about a number a program handed the processor directly.
371    ///
372    /// A template kept as text is the fifth, and is further again: it is not even one instruction,
373    /// it is whatever the program wrote that could not be read as instructions.
374    const TEMPLATE: &[&str] = &["cpuid", "pause", "align", "byte", "template"];
375
376    /// The rotates and the test against a constant, which a template writes and nothing else does.
377    ///
378    /// A rotate is a term the IR could have, and does not yet: C spells one as two shifts and an or,
379    /// and nothing puts those back together. A test against a constant is an and whose answer is
380    /// thrown away, and the layout writes a comparison for that rather than this. A store of a
381    /// constant goes through a register when the compiler writes it. So what reaches one of these
382    /// is a program that wrote the name, which is what tcc's byte swap, its copy of `memcpy` and
383    /// its test of `"m"` operands do.
384    const TEMPLATED: &[&str] = &[
385        "rol_ri_8",
386        "rol_ri_16",
387        "rol_ri_32",
388        "rol_ri_64",
389        "rol_rcl_8",
390        "rol_rcl_16",
391        "rol_rcl_32",
392        "rol_rcl_64",
393        "ror_ri_8",
394        "ror_ri_16",
395        "ror_ri_32",
396        "ror_ri_64",
397        "ror_rcl_8",
398        "ror_rcl_16",
399        "ror_rcl_32",
400        "ror_rcl_64",
401        "test_ri_8",
402        "test_ri_16",
403        "test_ri_32",
404        "test_ri_64",
405        "mov_mi_8",
406        "mov_mi_16",
407        "mov_mi_32",
408        "mov_mi_64",
409    ];
410
411    /// The instructions a template asks for that are right because of the line above them.
412    ///
413    /// These are exempt for the reason the ten bytes in [`COMPARE`] are, one step further out. A
414    /// rule selects a conditional move with its comparison in front of it, because that pair is the
415    /// shape a select has. The move on its own computes the same term and what makes it right is the
416    /// comparison somewhere behind it rather than anything about its own operands, so no pattern
417    /// could say what it means. The compare pass does not write one either, because it replaces a
418    /// comparison it found was already made and there is no earlier move here to replace. What
419    /// writes one is a program that put the comparison on one line of a template and the move on the
420    /// next, which is what zstd does to keep a bounds check from becoming a branch, and
421    /// [`crate::choice`] after the layout, out of a select a rule did write and the comparison its
422    /// byte came from.
423    ///
424    /// So these have operands a rule could have named, unlike everything in [`TEMPLATE`], and they
425    /// are still not instructions a rule could have been written for.
426    ///
427    /// The jumps on the sign, the overflow and the parity are here for the same reason. The layout
428    /// writes the other ten behind a comparison it chose, and nothing chooses one of these: a C
429    /// condition never asks about one bit on its own, so the only line above one is a line in a
430    /// template, which is what a loop in tcc's tests that counts down with `dec` and stops on `js`
431    /// is.
432    /// The add with carry and the subtract with borrow, which read a bit off the instruction in
433    /// front of them.
434    ///
435    /// Exempt one step further out again than [`CONDITIONAL`]. A conditional move reads the
436    /// condition state and leaves it alone, so what is missing from a rule that named one is the
437    /// comparison. These read it and write it both, and what is missing is worse than a comparison:
438    /// the bit they read is the carry out of an addition, and an addition in the IR is an addition
439    /// of a width with no carry out at all, so there is no term a rule could match that the bit is
440    /// a part of. A program gets one by writing both halves itself in a template, which is what
441    /// `add_ssaaaa` and `sub_ddmmss` in libgmp's `longlong.h` are. The form against a constant is
442    /// here for the same reason and is the same instruction with a zero where the second source is,
443    /// which `add_sssaaaa` writes for the top word of a number three words wide.
444    ///
445    /// What keeps the two halves together once they are two instructions in a block is not here. It
446    /// is `rucc_target::FlagInsts`, which the scheduler reads for exactly this, and the test below
447    /// checks the entry is there rather than trusting that somebody remembered.
448    const CARRY: &[&str] = &[
449        "adc_rr_8",
450        "adc_rr_16",
451        "adc_rr_32",
452        "adc_rr_64",
453        "sbb_rr_8",
454        "sbb_rr_16",
455        "sbb_rr_32",
456        "sbb_rr_64",
457        "adc_ri_8",
458        "adc_ri_16",
459        "adc_ri_32",
460        "adc_ri_64",
461        "sbb_ri_8",
462        "sbb_ri_16",
463        "sbb_ri_32",
464        "sbb_ri_64",
465    ];
466
467    const CONDITIONAL: &[&str] = &[
468        "cmov_e_16",
469        "cmov_e_32",
470        "cmov_e_64",
471        "cmov_ne_16",
472        "cmov_ne_32",
473        "cmov_ne_64",
474        "cmov_l_16",
475        "cmov_l_32",
476        "cmov_l_64",
477        "cmov_le_16",
478        "cmov_le_32",
479        "cmov_le_64",
480        "cmov_g_16",
481        "cmov_g_32",
482        "cmov_g_64",
483        "cmov_ge_16",
484        "cmov_ge_32",
485        "cmov_ge_64",
486        "cmov_b_16",
487        "cmov_b_32",
488        "cmov_b_64",
489        "cmov_be_16",
490        "cmov_be_32",
491        "cmov_be_64",
492        "cmov_a_16",
493        "cmov_a_32",
494        "cmov_a_64",
495        "cmov_ae_16",
496        "cmov_ae_32",
497        "cmov_ae_64",
498        "jcc_s",
499        "jcc_ns",
500        "jcc_o",
501        "jcc_no",
502        "jcc_p",
503        "jcc_np",
504    ];
505
506    /// The instructions that look for a set bit, which a template asks for and nothing else does.
507    ///
508    /// These have a source and a destination a rule could have named, the way the conditional moves
509    /// above do, and the reason no rule names them is a different one again. It is not that their
510    /// meaning comes from the line in front of them: each of these says on its own exactly what it
511    /// computes. It is that [`crate::expand`] already answers the question they answer, out of
512    /// arithmetic every machine has, and it does that because what these do when the source is zero
513    /// is four different things on four families of processor. A rule that selected one would be a
514    /// rule whose answer depends on which machine ran it.
515    ///
516    /// So the only thing that reaches one is a program that wrote the name in a template, which is
517    /// what the libraries that were counting bits before there was a builtin for it all do.
518    /// `crate::lower` writes them for the reason it writes the three in [`TEMPLATE`], and they are
519    /// not on that list because they are not bare: a rule could have named these operands and the
520    /// claim that list makes would be false of them.
521    const SEARCH: &[&str] = &[
522        "bsf_16", "bsf_32", "bsf_64", "bsr_16", "bsr_32", "bsr_64", "lzcnt_32", "lzcnt_64",
523        "tzcnt_32", "tzcnt_64",
524    ];
525
526    /// The instruction that turns a register round, which a template asks for and nothing else does.
527    ///
528    /// The list above, one step simpler. A search is unselected because what it does with a source
529    /// of zero is not the same on every processor, so a rule that chose one would depend on what ran
530    /// it. A byte reversal has no such case: it means exactly one thing everywhere. What keeps it
531    /// off the rule set is a choice made once, in [`crate::expand`], which builds a reversal out of
532    /// shifts and masks so that the answer is the same on every target this compiler has rather than
533    /// good on the one that happens to have the instruction. tamnd/rucc#310 is where that trade is
534    /// written down, and the day a target grows its own reversal is the day to reopen it.
535    ///
536    /// So the only thing that reaches one is a program that wrote the name in a template, which is
537    /// what libgmp does in `gmp-impl.h` to put a limb the other way round.
538    ///
539    /// The third is the same thing at a width `bswap` does not reach. Turning a sixteen bit number
540    /// round is exchanging its two bytes with each other, and this machine says that by naming the
541    /// high byte of a register, which only the first four registers have. femtolisp writes one in
542    /// `llt/utils.h`, which is how a C library older than `__builtin_bswap16` said it, and that
543    /// header is the one every other file of the library includes.
544    const SWAP: &[&str] = &["bswap_32", "bswap_64", "xchg_high_16"];
545
546    /// The jump out of the function a template may end with, which a template asks for and nothing
547    /// else could.
548    ///
549    /// Unselected for a reason none of the lists above give, and the plainest reason of the lot:
550    /// there is no term in the IR for it to be the answer to. A tail jump is not a computation and
551    /// it is not a branch between this function's blocks either, it is the function ending
552    /// somewhere other than at its own `ret`, and the only thing that says a function ends that way
553    /// is a program writing `jmp` at the end of a template in a function that is `naked`. See
554    /// [`rucc_target::x86_64::Step::Away`].
555    const AWAY: &[&str] = &["jmp_away"];
556
557    /// The instructions that change an object where it lives, which a template asks for and
558    /// nothing else does.
559    ///
560    /// Each of these is a load, one operation and a store in one line. The rules select the three
561    /// on their own and never the one that is all of them, because what a rule sees is a value in a
562    /// register and the store is a separate term further on. What asks for one is a program that
563    /// gave an `asm` operand the constraint `m` and then named it in an instruction, which is how a
564    /// C library sets a bit in a `sigset_t` and how tcc's `tests/tcctest.c` counts a static local up.
565    const MEMORY: &[&str] = &[
566        "neg_m_8",
567        "neg_m_16",
568        "neg_m_32",
569        "neg_m_64",
570        "not_m_8",
571        "not_m_16",
572        "not_m_32",
573        "not_m_64",
574        "inc_m_8",
575        "inc_m_16",
576        "inc_m_32",
577        "inc_m_64",
578        "dec_m_8",
579        "dec_m_16",
580        "dec_m_32",
581        "dec_m_64",
582        "bts_mr_16",
583        "bts_mr_32",
584        "bts_mr_64",
585        "btr_mr_16",
586        "btr_mr_32",
587        "btr_mr_64",
588        "btc_mr_16",
589        "btc_mr_32",
590        "btc_mr_64",
591        "bts_mi_16",
592        "bts_mi_32",
593        "bts_mi_64",
594        "btr_mi_16",
595        "btr_mi_32",
596        "btr_mi_64",
597        "btc_mi_16",
598        "btc_mi_32",
599        "btc_mi_64",
600    ];
601
602    /// The multiply that keeps both halves of its product and the division that reads both halves
603    /// of its dividend, which a template asks for and nothing else does.
604    ///
605    /// A third reason again, and the plainest of the three. A search is unselected because its
606    /// answer depends on the processor and a reversal because a choice was made to build one out of
607    /// arithmetic. This one is unselected because there is nothing in the IR to select it from: a
608    /// multiply in C takes two values of a type and produces a value of that type, so the term a
609    /// rule would match on is the narrow product, and the wide product is not a term at all. A rule
610    /// that fired on the narrow one and wrote this would be writing an instruction that computes
611    /// twice as much as was asked for and leaves the rest in a register nobody asked about.
612    ///
613    /// So the only thing that reaches one is a program that wrote the name in a template, which is
614    /// what `umul_ppmm` in libgmp's `longlong.h` does, and what every library that is building
615    /// arithmetic out of limbs does somewhere.
616    ///
617    /// The division is the same claim upside down and is on this list because the reason is the same
618    /// one. A division in C divides a number by a number of its own width, so the term a rule would
619    /// match is the narrow one, and this compiler already has two opcodes for that: each of them
620    /// fills the high half of the dividend itself and then throws one of the two answers away. A
621    /// dividend the program filled both halves of is not a term the IR has, and `udiv_qrnnd` beside
622    /// the multiply in the same header is how long division a limb at a time is written.
623    const WIDE: &[&str] = &[
624        "mul_wide_16",
625        "mul_wide_32",
626        "mul_wide_64",
627        "imul_wide_16",
628        "imul_wide_32",
629        "imul_wide_64",
630        "div_wide_16",
631        "div_wide_32",
632        "div_wide_64",
633        "idiv_wide_16",
634        "idiv_wide_32",
635        "idiv_wide_64",
636    ];
637
638    /// The string instructions, which a template writes and nothing else does.
639    ///
640    /// Exempt for the reason `cpuid` is in [`TEMPLATE`]: every register one of them reaches is one
641    /// the instruction names for itself, so there is nothing about one for a rule to name. A copy
642    /// or a fill the compiler writes is a loop it can schedule or a call to the library, and never
643    /// one of these.
644    const STRING: &[&str] = &[
645        "movs_8",
646        "movs_16",
647        "movs_32",
648        "movs_64",
649        "rep_movs_8",
650        "rep_movs_16",
651        "rep_movs_32",
652        "rep_movs_64",
653        "stos_8",
654        "stos_16",
655        "stos_32",
656        "stos_64",
657        "rep_stos_8",
658        "rep_stos_16",
659        "rep_stos_32",
660        "rep_stos_64",
661        "lods_8",
662        "lods_16",
663        "lods_32",
664        "lods_64",
665        "scas_8",
666        "scas_16",
667        "scas_32",
668        "scas_64",
669        "repe_scas_8",
670        "repe_scas_16",
671        "repe_scas_32",
672        "repe_scas_64",
673        "repne_scas_8",
674        "repne_scas_16",
675        "repne_scas_32",
676        "repne_scas_64",
677        "cmps_8",
678        "cmps_16",
679        "cmps_32",
680        "cmps_64",
681        "repe_cmps_8",
682        "repe_cmps_16",
683        "repe_cmps_32",
684        "repe_cmps_64",
685        "repne_cmps_8",
686        "repne_cmps_16",
687        "repne_cmps_32",
688        "repne_cmps_64",
689    ];
690
691    /// The instructions that produce two values, which is one more than a rule can name.
692    ///
693    /// A rule replaces a term with a term, and a term is the value one instruction computes. A
694    /// compare and exchange computes two: what it found at the address, and whether what it found
695    /// was what the program expected. There is no way to write the second one down in the rule
696    /// language, and inventing one would be inventing a language for a single instruction.
697    ///
698    /// So `crate::lower` writes it by name, the way it writes the barrier by name, and for a reason
699    /// that is about the rule language rather than about the machine. What the solver would have
700    /// been asked to prove about it is the easy half in any case: the arithmetic is a comparison
701    /// and a select, and what is hard is that the whole of it happens at once, which is the same
702    /// claim about the program around it that a barrier makes.
703    const ATOMIC: &[&str] = &["cmpxchg_8", "cmpxchg_16", "cmpxchg_32", "cmpxchg_64"];
704
705    /// The instructions whose operation is in the payload rather than in the head.
706    ///
707    /// A different exemption from the one above, on instructions that produce one value each and so
708    /// could be named by a rule if the rule had anything to match on. The head a pattern matches is
709    /// an opcode and a type, and every read modify write in the IR is the one opcode `atomic_rmw`.
710    /// Which of the thirteen operations it performs is carried beside the instruction rather than in
711    /// its name, so a pattern written for the exchange would match the add and the nand as well, and
712    /// the rule language has no way to look at what a rule matched to tell them apart.
713    ///
714    /// Giving each operation its own opcode is the other way out and is a worse trade: it is
715    /// thirteen opcodes at four widths where the IR wants one, and every pass that treats a read
716    /// modify write as one thing would then have a list of fifty two.
717    ///
718    /// So `crate::lower` writes these by name too. Three operations here, out of the thirteen: the
719    /// bitwise ones need a loop around a compare and exchange, which is control flow and so is built
720    /// before selection rather than during it, and they are the rest of `tamnd/rucc#311`.
721    const PAYLOAD: &[&str] =
722        &["xchg_8", "xchg_16", "xchg_32", "xchg_64", "xadd_8", "xadd_16", "xadd_32", "xadd_64"];
723
724    /// The instructions a frame writes rather than a rule.
725    ///
726    /// A prologue, an epilogue, a copy, a spill and a reload are not in the program. They are what
727    /// the allocator's answer costs, so they are written after it, by `crate::finish` reading
728    /// `x86_64::FRAME`. Six of the names that describes are already reachable from a rule, since a
729    /// prologue taking its frame is a subtraction and a spill is a store, and those are not here:
730    /// this is only the ones nothing else can reach.
731    const FRAME: &[&str] = &[
732        "push_64",
733        "pop_64",
734        "ret",
735        "mov_rr_64",
736        "movaps_rr",
737        // The touch a probing prologue puts on each page as it reaches it, the landing pad a
738        // prologue opens with, and the byte that does nothing which one reserves room with. All
739        // three are written by a frame and none on a command line that did not ask for it.
740        "or_mi_8",
741        "endbr64",
742        "nop",
743    ];
744
745    /// The instructions that reach the x87 stack, which are selected but not from here.
746    ///
747    /// A third kind of exemption, and the same reason all the way down the list.
748    ///
749    /// Every one of these is written by `crate::lower`, as part of a group rather than on its own.
750    /// What one of them leaves behind and the next picks up is the top of the x87 stack, which is
751    /// not a register anything allocates from and not a value a pattern could bind, so a rule
752    /// could neither match the middle of a group nor name what its replacement produced. And an
753    /// add here reads two addresses and writes a third, where one machine IR instruction carries
754    /// one addressing mode, so the group cannot be folded into a single opcode the way
755    /// `ucomisd_set_e` folds a comparison and a `setcc` either.
756    ///
757    /// So these are exempt for the reason `FRAME` is exempt rather than for the reason the list
758    /// below is, and they will stay exempt. Two of them are not reached by anything yet all the
759    /// same: `fsub_p` and `fdiv_p` are the other direction of the subtraction and the division,
760    /// which a code generator that pushed its operands the other way round would need and this one
761    /// does not. `fabs` is a third, since C spells that as a call to a library function.
762    const X87: &[&str] = &[
763        "fld_t",
764        "fstp_t",
765        "fld_s",
766        "fld_l",
767        "fild_l",
768        "fild_ll",
769        "fstp_s",
770        "fstp_l",
771        "fistp_l",
772        "fistp_ll",
773        "fnstcw",
774        "fldcw",
775        "fadd_p",
776        "fsub_p",
777        "fsubr_p",
778        "fmul_p",
779        "fdiv_p",
780        "fdivr_p",
781        "fchs",
782        "fabs",
783        "fucomip_set_a",
784        "fucomip_set_ae",
785        "fucomip_set_b",
786        "fucomip_set_be",
787        "fucomip_set_e",
788        "fucomip_set_ne",
789        "fucomip_set_p",
790        "fucomip_set_np",
791        "fucomip_set_e_and_np",
792        "fucomip_set_ne_or_p",
793    ];
794
795    /// The instructions no rule selects yet, because the rules that selected them were taken out.
796    ///
797    /// A different kind of exemption from the three above. Those say an instruction is written
798    /// somewhere a rule cannot reach and always will be. These say nobody reaches one at all right
799    /// now, and name the work that puts the rules back.
800    ///
801    /// The rules went out under `tamnd/rucc#368`. C promotes the operands of an arithmetic
802    /// operator to `int`, so a byte add and a two byte compare are things no C program asks the
803    /// back end for, and the rules at those widths sat proved and never selected over the whole
804    /// torture corpus at every optimization level. The width narrowing pass in `tamnd/rucc#375` is
805    /// what asks for them, and the rules come back with it.
806    ///
807    /// The descriptions stayed. A description says what an x86-64 instruction is, how long it is
808    /// and how it encodes, and that is true whether or not anything selects it. Taking them out
809    /// would be deleting a correct account of the machine to make a list shorter, and putting them
810    /// back is then a second thing to get right rather than a line of a rule file.
811    const NARROW: &[&str] = &[
812        // The multiply against an immediate at the narrow widths. The `narrow` pass writes the
813        // shape, since `char c = a * 3;` narrows to a byte multiply by a byte constant, and the
814        // constant goes into a register and the register with register rule takes it.
815        "imul_ri_8",
816        "imul_ri_16",
817        // The shifts by a value, whose count is in `cl` whatever the width being shifted is. The
818        // same refusal for the same kind of reason: a count of twenty is a defined shift to zero
819        // at four bytes and is poison at one, so only a count that is a constant below the narrow
820        // width narrows, and that one selects the immediate forms which do have rules.
821        "shl_rcl_8",
822        "shl_rcl_16",
823        "shr_rcl_8",
824        "shr_rcl_16",
825        "sar_rcl_8",
826        "sar_rcl_16",
827    ];
828
829    /// The arithmetic that reaches memory, which [`crate::combine`] writes: the forms that read a
830    /// source out of it and the forms that leave the answer in it.
831    ///
832    /// A function rather than a list, for the reason the compare pass's exemption is taken from the
833    /// flag description rather than typed out: the pass already writes down which instructions it
834    /// can produce, and a second copy of that here would be a second opinion about one pass.
835    ///
836    /// No rule selects one of these because a rule matches a term and one of these is two terms, a
837    /// load and an arithmetic operation, put together, or three where the answer goes back to
838    /// memory. Whether they may be put together depends on what is written between them and on
839    /// whether anything else wants what the load read, and neither is a fact about any of the
840    /// terms. That is the whole reason the pass exists and the module documentation there says it
841    /// at length.
842    fn combine() -> Vec<&'static str> {
843        let loads = crate::combine::FOLDS.iter().map(|fold| fold.into);
844        // And the instruction a load on the other side comes to, which for most rows is the one
845        // above and for a comparison is the condition the other way round.
846        let swapped = crate::combine::FOLDS.iter().filter_map(|fold| fold.swapped);
847        let stores = crate::combine::UPDATES.iter().map(|update| update.into);
848        let constants = crate::combine::BUMPS.iter().map(|bump| bump.into);
849        // And the load that widens on the way in, which only a load that a widening reads becomes.
850        let widened = crate::combine::WIDENINGS.iter().map(|fold| fold.into);
851        loads.chain(swapped).chain(stores).chain(constants).chain(widened).collect()
852    }
853
854    #[test]
855    fn every_instruction_exempt_from_a_rule_is_one_a_frame_really_writes() {
856        // The same claim as the one about the convention, so that this list cannot grow an opcode
857        // that no frame asks for. In the order `x86_64::FRAME` names them, the copies after the
858        // return because there is one set of them per class the allocator may spill.
859        let frame = &x86_64::FRAME;
860        let mut written = vec![frame.push, frame.pop, frame.ret];
861        for class in frame.classes {
862            written.extend([class.mov, class.load, class.store]);
863        }
864        // And the touch a probing prologue puts on a page, which the target names as an option
865        // because a target with no instruction that writes an address without changing it takes
866        // every frame in one subtraction and has nothing to exempt.
867        written.extend(frame.probe.map(|probe| probe.inst));
868        // And the landing pad and the byte that does nothing, which are options for the same
869        // reason.
870        written.extend(frame.landing);
871        written.extend(frame.pad);
872        // What is left after the ones a rule already reaches, which are the loads and the stores of
873        // both register files, since those are the same instructions a program's own reads and
874        // writes of memory are. The vector pair joined them with the rules for a quad float, and a
875        // spill of one is now the same instruction as a program reading a `_Float128` variable.
876        written.retain(|opcode| !heads().contains(&format!("{PREFIX}{opcode}").as_str()));
877        assert_eq!(written, FRAME);
878    }
879
880    #[test]
881    fn every_instruction_exempt_from_a_rule_is_one_the_convention_really_writes() {
882        // An exemption list that nothing checks is a hole, since an opcode dropped into it stops
883        // being covered by either direction of the pinning. These are the ones `crate::abi` can
884        // name, at the four integer widths and the four float formats it has names for an
885        // argument in, and no others.
886        let strip = |head: &'static str| head.strip_prefix(PREFIX).expect("an x86-64 term");
887        let named = |ty| strip(crate::abi::head_of(ty).expect("every width the pseudos cover"));
888        // The second half of a pair at place one, which is the place a rule cannot name. The first
889        // half at place zero is `ret_val_*` and is reached by a rule, so it is not on this list.
890        let second = |ty| strip(crate::abi::ret_of(ty, 1).expect("every width the pseudos cover"));
891        let widths = || {
892            [8, 16, 32, 64].into_iter().map(rucc_ir::Type::int).chain(
893                [
894                    rucc_ir::Float::F16,
895                    rucc_ir::Float::F32,
896                    rucc_ir::Float::F64,
897                    rucc_ir::Float::F128,
898                ]
899                .map(rucc_ir::Type::float),
900            )
901        };
902        let written: Vec<&str> = widths()
903            .map(named)
904            .chain(widths().map(second))
905            .chain([strip(crate::abi::CALL), strip(crate::abi::CALL_REG)])
906            .collect();
907        assert_eq!(written, CONVENTION);
908    }
909
910    /// The same claim about the block layout's list, which is longer than it looks.
911    ///
912    /// A name here that the layout does not write is an opcode exempted from needing a rule and
913    /// reached by nothing, and a name the layout writes that is not here is a failing test in
914    /// `every_described_instruction_is_reachable_from_a_rule` with a misleading message. Both are
915    /// avoided by taking the list from `rucc_target::x86_64::BRANCH` rather than believing it.
916    #[test]
917    fn every_instruction_exempt_from_a_rule_is_one_the_block_layout_really_writes() {
918        let branch = &x86_64::BRANCH;
919        // Eighty entries name sixteen instructions between them, so this is a set rather than a
920        // list and both sides are sorted before they are held against each other. What the order
921        // of the list itself is for is reading it.
922        let mut written: Vec<&str> = vec![branch.test, branch.jump];
923        written.extend(branch.fused.iter().map(|fusion| fusion.cmp));
924        written.extend(branch.fused.iter().flat_map(|fusion| [fusion.if_true, fusion.if_false]));
925        written.sort_unstable();
926        written.dedup();
927        let mut exempt = LAYOUT.to_vec();
928        exempt.sort_unstable();
929        assert_eq!(written, exempt);
930    }
931
932    /// The same claim about the compare pass. What it writes is what the flag description says is
933    /// left of a comparison, so the exemption is taken from that rather than typed out twice, and
934    /// an entry added there without a rule to go with it shows up here rather than in a build that
935    /// fails somewhere else.
936    #[test]
937    fn every_instruction_exempt_from_a_rule_is_one_the_compare_pass_really_writes() {
938        let mut written: Vec<&str> =
939            x86_64::FLAGS.compares.iter().filter_map(|entry| entry.kept).collect();
940        written.sort_unstable();
941        written.dedup();
942        let mut exempt = COMPARE.to_vec();
943        exempt.sort_unstable();
944        assert_eq!(written, exempt);
945    }
946
947    /// And the same claim about the one the lowering writes, held against the name the target gave
948    /// it rather than against the spelling written above.
949    #[test]
950    fn the_instruction_a_computed_goto_is_exempt_for_is_the_one_the_target_names() {
951        assert_eq!(LABELS, [x86_64::BRANCH.indirect]);
952    }
953
954    /// Every row of the constant table is an instruction some rule selects.
955    ///
956    /// `crate::combine::BUMPS` has a row per instruction this machine has, which is the whole five
957    /// operations at the whole four widths. The narrow inclusive and exclusive or were the last
958    /// four to take nothing, and came back with the width narrowing in `tamnd/rucc#375`, so a row
959    /// that takes nothing now is a rule that went missing.
960    #[test]
961    fn every_constant_run_is_one_a_rule_selects() {
962        let written = heads();
963        for bump in crate::combine::BUMPS {
964            let head = format!("{PREFIX}{}", bump.from);
965            assert!(written.contains(&head.as_str()), "no rule selects {}", bump.from);
966            assert!(!NARROW.contains(&bump.from), "{} is still on the list", bump.from);
967        }
968    }
969
970    #[test]
971    fn every_described_instruction_is_reachable_from_a_rule() {
972        let written = heads();
973        let combine = combine();
974        for &(opcode, _) in x86_64::INSTS {
975            if combine.contains(&opcode) {
976                continue;
977            }
978            if CONVENTION.contains(&opcode) || LAYOUT.contains(&opcode) || FRAME.contains(&opcode) {
979                continue;
980            }
981            if PEEPHOLE.contains(&opcode) {
982                continue;
983            }
984            if NARROW.contains(&opcode) || BARRIER.contains(&opcode) || X87.contains(&opcode) {
985                continue;
986            }
987            if ATOMIC.contains(&opcode) || PAYLOAD.contains(&opcode) || HINT.contains(&opcode) {
988                continue;
989            }
990            if CONDITIONAL.contains(&opcode) {
991                continue;
992            }
993            if CARRY.contains(&opcode) {
994                continue;
995            }
996            if COMPARE.contains(&opcode) || TEMPLATE.contains(&opcode) {
997                continue;
998            }
999            if SEARCH.contains(&opcode) || SWAP.contains(&opcode) || WIDE.contains(&opcode) {
1000                continue;
1001            }
1002            if AWAY.contains(&opcode) || MEMORY.contains(&opcode) || STRING.contains(&opcode) {
1003                continue;
1004            }
1005            if TEMPLATED.contains(&opcode) {
1006                continue;
1007            }
1008            if LABELS.contains(&opcode) || STOP.contains(&opcode) || CELL.contains(&opcode) {
1009                continue;
1010            }
1011            let head = format!("{PREFIX}{opcode}");
1012            assert!(
1013                written.contains(&head.as_str()),
1014                "{opcode} is described and no rule in {} selects it",
1015                TABLE.source
1016            );
1017        }
1018    }
1019
1020    /// The same claim about the peephole's list, which is a claim about the target's description
1021    /// rather than about this crate: every name on it is one the target really has, and every one
1022    /// of them is a shorter spelling the description names, which is what says the peephole is
1023    /// where it comes from. A name on the list that the peephole could never write would be an
1024    /// instruction nothing writes at all, and this test is what stops that sitting there unnoticed.
1025    #[test]
1026    fn every_instruction_exempt_from_a_rule_is_one_the_peephole_really_writes() {
1027        let tests = x86_64::SHORT.testing.iter().map(|entry| entry.into);
1028        let steps = x86_64::SHORT.stepping.iter().map(|entry| entry.into);
1029        let shorter: Vec<&str> = tests.chain(steps).collect();
1030        for &opcode in PEEPHOLE {
1031            assert!(
1032                x86_64::form(opcode).is_some(),
1033                "{opcode} is not an instruction this describes"
1034            );
1035            assert!(shorter.contains(&opcode), "{opcode} is not one the peephole writes");
1036        }
1037    }
1038
1039    /// The same claim about the barrier as the ones above make about the convention and the frame:
1040    /// the list holds instructions this target really describes, and holds only the ones that have
1041    /// no operands, since an instruction with an operand is one a rule could have been written for.
1042    #[test]
1043    fn every_instruction_exempt_from_a_rule_is_one_the_memory_model_really_writes() {
1044        for &opcode in BARRIER {
1045            let form = x86_64::form(opcode).expect("an instruction this target describes");
1046            assert!(form.operands().is_empty(), "{opcode} has operands, so a rule could name it");
1047        }
1048    }
1049
1050    /// The same claim about the instruction a program stops on, which is the barrier's shape
1051    /// exactly: no operands, because an instruction with one is an instruction a rule could have
1052    /// been written for, and no addressing mode either, because it is given nothing at all.
1053    #[test]
1054    fn the_instruction_exempt_from_a_rule_because_it_stops_the_program_is_bare() {
1055        for &opcode in STOP {
1056            let form = x86_64::form(opcode).expect("an instruction this target describes");
1057            assert!(form.operands().is_empty(), "{opcode} has operands, so a rule could name it");
1058            assert!(!form.takes_mem(), "{opcode} is given an address and stopping needs none");
1059        }
1060    }
1061
1062    /// The same claim about the hints, with the one difference between them written down. A hint is
1063    /// given an address and nothing else, so it has no operands for the reason a barrier has none
1064    /// and it does carry an addressing mode, which is what a rule would have had to match on.
1065    #[test]
1066    fn every_instruction_exempt_from_a_rule_because_it_is_a_hint_is_given_only_an_address() {
1067        for &opcode in HINT {
1068            let form = x86_64::form(opcode).expect("an instruction this target describes");
1069            assert!(form.operands().is_empty(), "{opcode} has operands, so a rule could name it");
1070            assert!(form.takes_mem(), "{opcode} is a hint about an address and is given none");
1071        }
1072    }
1073
1074    /// The same claim about the template list. An instruction is exempt for this reason exactly
1075    /// when there is nothing about it for a rule to name, and there are two ways to have nothing.
1076    /// No operands and no address, which is the hint. Or every operand fixed to one register by the
1077    /// description, which is the question put to the processor: a rule names the operands of a term
1078    /// and binds them to the values underneath it, and an operand that can be nothing but `rax` is
1079    /// not a place a value goes. Either way the whole of the claim holds, which is that there was
1080    /// nowhere else for the instruction to come from.
1081    #[test]
1082    fn every_instruction_exempt_from_a_rule_because_only_a_template_asks_for_it_is_bare() {
1083        for &opcode in TEMPLATE {
1084            let form = x86_64::form(opcode).expect("an instruction this target describes");
1085            let fixed = form
1086                .operands()
1087                .iter()
1088                .all(|desc| matches!(desc.constraint, rucc_target::Constraint::Fixed(_)));
1089            assert!(fixed, "{opcode} has an operand a rule could name");
1090            assert!(!form.takes_mem(), "{opcode} is given an address, so a rule could name it");
1091        }
1092    }
1093
1094    /// The same claim about the bit searches, read off the description that put them there and read
1095    /// both ways round. An instruction is exempt for this reason exactly when the machine describes
1096    /// it as a search, so the list cannot grow an opcode that is something else, and a search this
1097    /// target grows later cannot be left off the list and quietly go unselected with nobody saying
1098    /// why. Nothing in the rule set selects one, which is the other half of the reason and is what
1099    /// the check above would have caught in any case.
1100    #[test]
1101    fn every_instruction_exempt_from_a_rule_because_only_a_template_searches_for_a_bit_is_one() {
1102        let written = heads();
1103        for &opcode in SEARCH {
1104            let form = x86_64::form(opcode).expect("an instruction this target describes");
1105            assert_eq!(form, x86_64::Form::Search, "{opcode} is not a search");
1106            assert!(
1107                !written.contains(&format!("{PREFIX}{opcode}").as_str()),
1108                "a rule in {} selects {opcode}, which only a template asks for",
1109                TABLE.source
1110            );
1111        }
1112        for &(opcode, form) in x86_64::INSTS {
1113            if form == x86_64::Form::Search {
1114                assert!(SEARCH.contains(&opcode), "{opcode} is a search and is not on the list");
1115            }
1116        }
1117    }
1118
1119    /// The same claim about the byte reversal, read both ways round the way the searches are, and
1120    /// with the one thing that is different about it checked as well: this is the instruction of its
1121    /// shape that leaves the condition state alone, which is the whole reason it has a form rather
1122    /// than being a unary operation, so a description that stopped saying that would stop being the
1123    /// reason this list exists.
1124    #[test]
1125    fn every_instruction_exempt_from_a_rule_because_only_a_template_turns_a_register_round_is_one()
1126    {
1127        let written = heads();
1128        for &opcode in SWAP {
1129            let form = x86_64::form(opcode).expect("an instruction this target describes");
1130            // Two forms and one job. The wide reversals are one shape and the sixteen bit one is
1131            // another, because the narrow one is an exchange between the halves of a register and
1132            // has to say which register, so what they share is the answer they compute rather than
1133            // the operands they compute it from.
1134            assert!(
1135                matches!(form, x86_64::Form::Swap | x86_64::Form::SwapHalves),
1136                "{opcode} is not a byte reversal"
1137            );
1138            assert!(
1139                !(x86_64::FLAGS.writes)(opcode),
1140                "{opcode} writes the condition state, so it is a unary operation after all"
1141            );
1142            assert!(
1143                !written.contains(&format!("{PREFIX}{opcode}").as_str()),
1144                "a rule in {} selects {opcode}, which only a template asks for",
1145                TABLE.source
1146            );
1147        }
1148        for &(opcode, form) in x86_64::INSTS {
1149            if matches!(form, x86_64::Form::Swap | x86_64::Form::SwapHalves) {
1150                assert!(SWAP.contains(&opcode), "{opcode} is a reversal and is not on the list");
1151            }
1152        }
1153    }
1154
1155    /// The same claim about the two that work on a pair of registers, read both ways round and with
1156    /// the thing that puts them out of reach of a rule checked rather than asserted in prose: each
1157    /// writes two registers, and a rule replaces a term with a term, so there is no way to say the
1158    /// second answer in the rule language at all. That is the same bar the compare and exchange is
1159    /// exempt at, and this list is separate from that one because the reason it is nobody's to select
1160    /// is different: an atomic is written by name where it is needed, and nothing in this compiler
1161    /// needs one of these.
1162    #[test]
1163    fn every_instruction_exempt_from_a_rule_because_only_a_template_wants_both_halves_writes_two() {
1164        let written = heads();
1165        let both = [x86_64::Form::MulWide, x86_64::Form::DivWide];
1166        for &opcode in WIDE {
1167            let form = x86_64::form(opcode).expect("an instruction this target describes");
1168            assert!(both.contains(&form), "{opcode} works on one register rather than on a pair");
1169            let defs = form.operands().iter().filter(|desc| desc.role.is_def()).count();
1170            assert_eq!(defs, 2, "{opcode} writes {defs} registers and a pair takes two");
1171            assert!(
1172                !written.contains(&format!("{PREFIX}{opcode}").as_str()),
1173                "a rule in {} selects {opcode}, which only a template asks for",
1174                TABLE.source
1175            );
1176        }
1177        for &(opcode, form) in x86_64::INSTS {
1178            if both.contains(&form) {
1179                assert!(WIDE.contains(&opcode), "{opcode} works on a pair and is not on the list");
1180            }
1181        }
1182    }
1183
1184    /// The same claim about the carry pair, and the one thing that has to be true of them that is
1185    /// not true of anything else on any of these lists. An instruction here reads the condition
1186    /// state and writes it, which is what makes it half of a pair and not a rewrite of its own, and
1187    /// the scheduler will only keep it behind the instruction that set the bit if the target says
1188    /// it reads one.
1189    #[test]
1190    fn every_instruction_exempt_from_a_rule_because_it_reads_a_carry_says_it_reads_the_state() {
1191        let written = heads();
1192        for &opcode in CARRY {
1193            let form = x86_64::form(opcode).expect("an instruction this target describes");
1194            let pair = matches!(form, x86_64::Form::AluCarry | x86_64::Form::AluCarryI);
1195            assert!(pair, "{opcode} is not one of the pair");
1196            assert_eq!(
1197                x86_64::FLAGS.reads(opcode),
1198                Some(rucc_target::Reads::Carry),
1199                "{opcode} does not say it reads the carry, so the scheduler may move it"
1200            );
1201            assert!(
1202                (x86_64::FLAGS.writes)(opcode),
1203                "{opcode} is said to leave the condition state alone"
1204            );
1205            assert!(
1206                !written.contains(&format!("{PREFIX}{opcode}").as_str()),
1207                "a rule in {} selects {opcode}, which only a template asks for",
1208                TABLE.source
1209            );
1210        }
1211        for &(opcode, form) in x86_64::INSTS {
1212            if matches!(form, x86_64::Form::AluCarry | x86_64::Form::AluCarryI) {
1213                assert!(CARRY.contains(&opcode), "{opcode} reads a carry and is not on the list");
1214            }
1215        }
1216    }
1217
1218    /// The same claim about the conditional moves, read off the flag description the way the compare
1219    /// pass's list is taken from it rather than typed out twice. An instruction is exempt for this
1220    /// reason exactly when it reads the condition state and leaves it as it found it, which is what
1221    /// says the instruction in front of it is where its meaning comes from. One that wrote the state
1222    /// as well would be one a pattern could match on its own.
1223    #[test]
1224    fn every_instruction_exempt_from_a_rule_because_a_comparison_gives_it_its_meaning_reads_one() {
1225        for &opcode in CONDITIONAL {
1226            x86_64::form(opcode).expect("an instruction this target describes");
1227            assert!(
1228                x86_64::FLAGS.reads(opcode).is_some(),
1229                "{opcode} reads no comparison, so a rule could name it"
1230            );
1231            assert!(
1232                !(x86_64::FLAGS.writes)(opcode),
1233                "{opcode} writes the condition state, so a rule could name it"
1234            );
1235        }
1236    }
1237
1238    /// The same claim about the atomic list, read off the thing that put the entry there: an
1239    /// instruction is exempt for this reason exactly when it writes more than one value, and an
1240    /// instruction that writes one is one a rule could have been written for.
1241    #[test]
1242    fn every_instruction_exempt_from_a_rule_is_one_that_writes_more_than_one_value() {
1243        let written = heads();
1244        for &opcode in ATOMIC {
1245            let form = x86_64::form(opcode).expect("an instruction this target describes");
1246            let writes = form.operands().iter().filter(|desc| desc.role.is_def()).count();
1247            assert!(writes > 1, "{opcode} writes one value, so a rule could name it");
1248            assert!(
1249                !written.contains(&format!("{PREFIX}{opcode}").as_str()),
1250                "a rule in {} selects {opcode}, which `crate::lower` also writes by hand",
1251                TABLE.source
1252            );
1253        }
1254    }
1255
1256    /// The same claim about the payload list, read off the thing that puts an entry there.
1257    ///
1258    /// Two halves. Each of these writes one value, which is what says the reason above is not the
1259    /// reason here, so a list that grew to cover an instruction the atomic list should have had
1260    /// fails. And there really is more than one operation behind the one IR opcode, which is the
1261    /// whole of why a pattern cannot name any of them, and is a fact about the IR that would stop
1262    /// being true if the operations were ever given opcodes of their own.
1263    #[test]
1264    fn every_instruction_exempt_because_its_operation_is_beside_it_writes_one_value() {
1265        assert!(
1266            rucc_ir::RmwOp::all().count() > 1,
1267            "one operation per opcode would be a head a rule could match"
1268        );
1269        let written = heads();
1270        for &opcode in PAYLOAD {
1271            let form = x86_64::form(opcode).expect("an instruction this target describes");
1272            let writes = form.operands().iter().filter(|desc| desc.role.is_def()).count();
1273            assert_eq!(writes, 1, "{opcode} writes more than one value, so it is the other list's");
1274            assert!(
1275                !written.contains(&format!("{PREFIX}{opcode}").as_str()),
1276                "a rule in {} selects {opcode}, which `crate::lower` also writes by hand",
1277                TABLE.source
1278            );
1279        }
1280    }
1281
1282    /// The staleness rule every list in this project is kept under, on the one list here whose
1283    /// entries are meant to leave. A rule that starts selecting one of these is `tamnd/rucc#375`
1284    /// arriving, and the entry goes with it. An entry naming an instruction nothing describes is a
1285    /// misspelling, and it would sit here exempting nothing.
1286    #[test]
1287    fn an_instruction_a_rule_now_selects_is_off_the_list_of_the_ones_left_for_later() {
1288        let written = heads();
1289        for &opcode in NARROW {
1290            let head = format!("{PREFIX}{opcode}");
1291            assert!(
1292                !written.contains(&head.as_str()),
1293                "a rule in {} selects {opcode} now, so it is not waiting on tamnd/rucc#375",
1294                TABLE.source
1295            );
1296            assert!(
1297                x86_64::INSTS.iter().any(|&(described, _)| described == opcode),
1298                "{opcode} is not an instruction anything describes"
1299            );
1300        }
1301    }
1302
1303    /// The same staleness rule on the x87 pair, and one thing more that is particular to them.
1304    ///
1305    /// They are a pair. An instruction that pushes onto the x87 stack and nothing that pops off it
1306    /// again would leave the stack one deeper than the function found it, which is not a mistake
1307    /// the allocator or the block layout could catch, since neither of them knows the stack is
1308    /// there. So the two arrive together and leave together, and that is what this says.
1309    #[test]
1310    fn the_x87_stack_is_reached_by_a_pair_and_by_nothing_else() {
1311        let written = heads();
1312        for &opcode in X87 {
1313            assert!(
1314                x86_64::INSTS.iter().any(|&(described, _)| described == opcode),
1315                "{opcode} is not an instruction anything describes"
1316            );
1317            assert!(
1318                !written.contains(&format!("{PREFIX}{opcode}").as_str()),
1319                "a rule in {} selects {opcode}, which `crate::lower` also writes by hand",
1320                TABLE.source
1321            );
1322        }
1323        // One way onto the stack per format a value can be read from, one way off it per format a
1324        // value can be written to, the control word pair that is neither, and the arithmetic. The
1325        // count is here as well as in the target description because this list is what says none
1326        // of them is reachable, and a name that arrived here without its partner would be a format
1327        // this target can convert in one direction and not the other.
1328        assert_eq!(X87.len(), 30, "twelve that move a value and eighteen that work on one");
1329    }
1330}