rucc_codegen/select/x86_64.rs
1//! The x86-64 lowering table.
2//!
3//! Everything below the module comment is generated from `rules/x86-64.rules` by `rucc-rules`
4//! when this crate is built, and none of it is in the repository. The rule file is the only
5//! place the rules are written, which is what makes the table that is matched with and the
6//! table `rucc-verify` proves things about the same table.
7//!
8//! To read the rules, read the rule file. To read the automaton they compile into, build the
9//! crate and read `x86-64.rs` under the build directory, which is a file worth looking at once
10//! for the shape of it and never again.
11
12// A guard is emitted as the comparison the rule writes, so a rule saying a shift count is at
13// least zero and less than the width comes out as two comparisons rather than as a range. That
14// is deliberate: the generated line and the rule it came from should read the same, and the
15// suggestion to write it another way is advice for somebody editing code, which nobody here is.
16#![allow(clippy::manual_range_contains)]
17
18include!(concat!(env!("OUT_DIR"), "/x86-64.rs"));
19
20#[cfg(test)]
21mod tests {
22 use rucc_target::x86_64;
23
24 use super::TABLE;
25 use crate::select::Piece;
26
27 /// The prefix a rule file puts in front of a machine term, which is how it says which target
28 /// the term belongs to. It is not part of the opcode.
29 const PREFIX: &str = "x64.";
30
31 /// The two address constructors, which are not instructions. An addressing mode is an
32 /// argument to `lea` and to every memory operand after it, so it is written as a term in the
33 /// rule file and built by the selector into the instruction that takes it.
34 const AMODES: &[&str] =
35 &["amode_base_index_scale", "amode_index_scale", "amode_base", "amode_base_offset"];
36
37 /// Every head this table can write, in and under the replacements.
38 fn heads() -> Vec<&'static str> {
39 let mut found: Vec<&'static str> = TABLE
40 .rules
41 .iter()
42 .flat_map(|rule| rule.replacement.iter())
43 .filter_map(|piece| match piece {
44 Piece::App { head, .. } => Some(*head),
45 _ => None,
46 })
47 .collect();
48 found.sort_unstable();
49 found.dedup();
50 found
51 }
52
53 #[test]
54 fn every_instruction_the_table_writes_is_described() {
55 for head in heads() {
56 if AMODES.contains(&head) {
57 continue;
58 }
59 let opcode = head.strip_prefix(PREFIX).unwrap_or_else(|| {
60 panic!("{head} is neither an x86-64 term nor an addressing mode")
61 });
62 assert!(
63 x86_64::form(opcode).is_some(),
64 "{head} is selected by a rule and `rucc_target::x86_64` does not say what it \
65 does with its operands"
66 );
67 }
68 }
69
70 /// The order the operands of a store are written in, which is the IR's and not a choice this
71 /// file makes.
72 ///
73 /// A pattern is matched against an instruction's operand list by position, so a rule that
74 /// names the address where the IR holds the value is a rule that stores to the value and
75 /// writes the address into memory. Nothing in a proof would catch it, because a proof is
76 /// about the rule file agreeing with itself, and both halves would be wrong in the same way.
77 /// `rucc_ir::Builder::store` takes the value first and the machine instruction takes it last,
78 /// which is why the two halves of one of these rules read in opposite orders.
79 #[test]
80 fn a_store_is_written_with_the_value_first_because_that_is_where_the_ir_keeps_it() {
81 let mut seen = 0;
82 for rule in TABLE.rules {
83 let Some(rest) = rule.pattern.strip_prefix("(store.") else { continue };
84 let (width, operands) = rest.split_once(' ').expect("a store takes operands");
85 assert!(
86 operands.starts_with(&format!("(value.{width} ")),
87 "line {}: {} binds something other than the value it is storing first",
88 rule.line,
89 rule.pattern
90 );
91 assert!(
92 operands.contains("(value.i64 "),
93 "line {}: {} reaches no address",
94 rule.line,
95 rule.pattern
96 );
97 seen += 1;
98 }
99 assert_eq!(seen, 12, "the store rules moved and this test did not follow them");
100 }
101
102 /// The instructions the calling convention writes rather than a rule.
103 ///
104 /// Three kinds of them. Naming the register an argument arrived in, where an argument is
105 /// depends on its position in the signature and on the classification of every argument before
106 /// it, and a rule pattern sees one term and has no way to say any of that, so `crate::abi`
107 /// builds these from the convention instead. Calling a name is the same the other way round:
108 /// what its operands are is whatever the signature made them, and a call through an address is
109 /// the same instruction with one operand more.
110 ///
111 /// The second half of a value that comes back in two registers is the third. A return of one
112 /// value is a rule, because where that value goes depends on nothing but the value, which is
113 /// exactly what a rule can say. A return of two is not, because which register the second half
114 /// is in depends on the first half: the two register files are counted separately, so a
115 /// `double` and a `long` both come back at place zero and two `long`s do not.
116 const CONVENTION: &[&str] = &[
117 "arg_val_8",
118 "arg_val_16",
119 "arg_val_32",
120 "arg_val_64",
121 "arg_val_f32",
122 "arg_val_f64",
123 "ret_val2_8",
124 "ret_val2_16",
125 "ret_val2_32",
126 "ret_val2_64",
127 "ret_val2_f32",
128 "ret_val2_f64",
129 "call",
130 "call_reg",
131 ];
132
133 /// The instructions the block layout writes rather than a rule.
134 ///
135 /// A rule sees one branch and the layout is about the order of every block in the function, so
136 /// which arm falls through is not something any pattern could say. That answer is what decides
137 /// whether the jump goes to the arm the condition is true for or the other one, and whether
138 /// there is a second jump after it, so all four of these are written where the answer is.
139 const LAYOUT: &[&str] = &["test_rr_8", "jcc_e", "jcc_ne", "jmp"];
140
141 /// The 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 a frame writes rather than a rule.
152 ///
153 /// A prologue, an epilogue, a copy, a spill and a reload are not in the program. They are what
154 /// the allocator's answer costs, so they are written after it, by `crate::finish` reading
155 /// `x86_64::FRAME`. Six of the names that describes are already reachable from a rule, since a
156 /// prologue taking its frame is a subtraction and a spill is a store, and those are not here:
157 /// this is only the ones nothing else can reach.
158 const FRAME: &[&str] =
159 &["push_64", "pop_64", "ret", "mov_rr_64", "movaps_rr", "movaps_rm", "movaps_mr"];
160
161 /// The instructions that reach the x87 stack, which are selected but not from here.
162 ///
163 /// A third kind of exemption, and the same reason all the way down the list.
164 ///
165 /// Every one of these is written by `crate::lower`, as part of a group rather than on its own.
166 /// What one of them leaves behind and the next picks up is the top of the x87 stack, which is
167 /// not a register anything allocates from and not a value a pattern could bind, so a rule
168 /// could neither match the middle of a group nor name what its replacement produced. And an
169 /// add here reads two addresses and writes a third, where one machine IR instruction carries
170 /// one addressing mode, so the group cannot be folded into a single opcode the way
171 /// `ucomisd_set_e` folds a comparison and a `setcc` either.
172 ///
173 /// So these are exempt for the reason `FRAME` is exempt rather than for the reason the list
174 /// below is, and they will stay exempt. Two of them are not reached by anything yet all the
175 /// same: `fsub_p` and `fdiv_p` are the other direction of the subtraction and the division,
176 /// which a code generator that pushed its operands the other way round would need and this one
177 /// does not. `fabs` is a third, since C spells that as a call to a library function.
178 const X87: &[&str] = &[
179 "fld_t",
180 "fstp_t",
181 "fld_s",
182 "fld_l",
183 "fild_l",
184 "fild_ll",
185 "fstp_s",
186 "fstp_l",
187 "fistp_l",
188 "fistp_ll",
189 "fnstcw",
190 "fldcw",
191 "fadd_p",
192 "fsub_p",
193 "fsubr_p",
194 "fmul_p",
195 "fdiv_p",
196 "fdivr_p",
197 "fchs",
198 "fabs",
199 "fucomip_set_a",
200 "fucomip_set_ae",
201 "fucomip_set_b",
202 "fucomip_set_be",
203 "fucomip_set_e",
204 "fucomip_set_ne",
205 "fucomip_set_p",
206 "fucomip_set_np",
207 "fucomip_set_e_and_np",
208 "fucomip_set_ne_or_p",
209 ];
210
211 /// The instructions no rule selects yet, because the rules that selected them were taken out.
212 ///
213 /// A different kind of exemption from the three above. Those say an instruction is written
214 /// somewhere a rule cannot reach and always will be. These say nobody reaches one at all right
215 /// now, and name the work that puts the rules back.
216 ///
217 /// The rules went out under `tamnd/rucc#368`. C promotes the operands of an arithmetic
218 /// operator to `int`, so a byte add and a two byte compare are things no C program asks the
219 /// back end for, and the rules at those widths sat proved and never selected over the whole
220 /// torture corpus at every optimization level. The width narrowing pass in `tamnd/rucc#375` is
221 /// what asks for them, and the rules come back with it.
222 ///
223 /// The descriptions stayed. A description says what an x86-64 instruction is, how long it is
224 /// and how it encodes, and that is true whether or not anything selects it. Taking them out
225 /// would be deleting a correct account of the machine to make a list shorter, and putting them
226 /// back is then a second thing to get right rather than a line of a rule file.
227 const NARROW: &[&str] = &[
228 // Three of the two address forms against an immediate. The `narrow` pass does write the
229 // shape, since `char c = a | 1;` narrows to a byte `or` against a byte constant, and no
230 // rule selects these yet: the constant goes into a register and the register with
231 // register rule takes it. Their `add`, `sub` and `and` siblings do have rules and are
232 // reached by the bitfield lowering, so this is six rules missing rather than a shape
233 // nothing writes.
234 "or_ri_8",
235 "or_ri_16",
236 "xor_ri_8",
237 "xor_ri_16",
238 "imul_ri_8",
239 "imul_ri_16",
240 // The divides, which are four instructions per width because the quotient and the
241 // remainder come out of one division in two different registers. `narrow` refuses these
242 // on purpose: the most negative byte over minus one is a defined hundred and twenty eight
243 // at four bytes and is the overflow that raises at one, so narrowing a division wants a
244 // range that rules the pair out and there is no range analysis yet.
245 "idiv_quo_8",
246 "idiv_quo_16",
247 "idiv_rem_8",
248 "idiv_rem_16",
249 "div_quo_8",
250 "div_quo_16",
251 "div_rem_8",
252 "div_rem_16",
253 // The shifts by a value, whose count is in `cl` whatever the width being shifted is. The
254 // same refusal for the same kind of reason: a count of twenty is a defined shift to zero
255 // at four bytes and is poison at one, so only a count that is a constant below the narrow
256 // width narrows, and that one selects the immediate forms which do have rules.
257 "shl_rcl_8",
258 "shl_rcl_16",
259 "shr_rcl_8",
260 "shr_rcl_16",
261 "sar_rcl_8",
262 "sar_rcl_16",
263 // A one bit value widened to a byte or to two bytes. The four byte and eight byte forms
264 // are what a `_Bool` read turns into, and these two want the one shape `narrow` does not
265 // have: a truncation of an extension, where the extension came from something narrower
266 // than the truncation goes to, which is what `char c = a < b;` is.
267 "bit_to_8",
268 "bit_to_16",
269 ];
270
271 #[test]
272 fn every_instruction_exempt_from_a_rule_is_one_a_frame_really_writes() {
273 // The same claim as the one about the convention, so that this list cannot grow an opcode
274 // that no frame asks for. In the order `x86_64::FRAME` names them, the moves last because
275 // there is one set of them per class the allocator may spill.
276 let frame = &x86_64::FRAME;
277 let mut written = vec![frame.push, frame.pop, frame.ret];
278 for class in frame.classes {
279 written.extend([class.mov, class.load, class.store]);
280 }
281 // What is left after the ones a rule already reaches, which are the loads and the stores
282 // of a general purpose register, since those are the same instructions a program's own
283 // reads and writes of memory are.
284 written.retain(|opcode| !heads().contains(&format!("{PREFIX}{opcode}").as_str()));
285 assert_eq!(written, FRAME);
286 }
287
288 #[test]
289 fn every_instruction_exempt_from_a_rule_is_one_the_convention_really_writes() {
290 // An exemption list that nothing checks is a hole, since an opcode dropped into it stops
291 // being covered by either direction of the pinning. These are the ones `crate::abi` can
292 // name, at the four integer widths and the two float formats it has names for an
293 // argument in, and no others.
294 let strip = |head: &'static str| head.strip_prefix(PREFIX).expect("an x86-64 term");
295 let named = |ty| strip(crate::abi::head_of(ty).expect("every width the pseudos cover"));
296 // The second half of a pair at place one, which is the place a rule cannot name. The first
297 // half at place zero is `ret_val_*` and is reached by a rule, so it is not on this list.
298 let second = |ty| strip(crate::abi::ret_of(ty, 1).expect("every width the pseudos cover"));
299 let widths = || {
300 [8, 16, 32, 64]
301 .into_iter()
302 .map(rucc_ir::Type::int)
303 .chain([rucc_ir::Float::F32, rucc_ir::Float::F64].map(rucc_ir::Type::float))
304 };
305 let written: Vec<&str> = widths()
306 .map(named)
307 .chain(widths().map(second))
308 .chain([strip(crate::abi::CALL), strip(crate::abi::CALL_REG)])
309 .collect();
310 assert_eq!(written, CONVENTION);
311 }
312
313 #[test]
314 fn every_described_instruction_is_reachable_from_a_rule() {
315 let written = heads();
316 for &(opcode, _) in x86_64::INSTS {
317 if CONVENTION.contains(&opcode) || LAYOUT.contains(&opcode) || FRAME.contains(&opcode) {
318 continue;
319 }
320 if NARROW.contains(&opcode) || BARRIER.contains(&opcode) || X87.contains(&opcode) {
321 continue;
322 }
323 let head = format!("{PREFIX}{opcode}");
324 assert!(
325 written.contains(&head.as_str()),
326 "{opcode} is described and no rule in {} selects it",
327 TABLE.source
328 );
329 }
330 }
331
332 /// The same claim about the barrier as the ones above make about the convention and the frame:
333 /// the list holds instructions this target really describes, and holds only the ones that have
334 /// no operands, since an instruction with an operand is one a rule could have been written for.
335 #[test]
336 fn every_instruction_exempt_from_a_rule_is_one_the_memory_model_really_writes() {
337 for &opcode in BARRIER {
338 let form = x86_64::form(opcode).expect("an instruction this target describes");
339 assert!(form.operands().is_empty(), "{opcode} has operands, so a rule could name it");
340 }
341 }
342
343 /// The staleness rule every list in this project is kept under, on the one list here whose
344 /// entries are meant to leave. A rule that starts selecting one of these is `tamnd/rucc#375`
345 /// arriving, and the entry goes with it. An entry naming an instruction nothing describes is a
346 /// misspelling, and it would sit here exempting nothing.
347 #[test]
348 fn an_instruction_a_rule_now_selects_is_off_the_list_of_the_ones_left_for_later() {
349 let written = heads();
350 for &opcode in NARROW {
351 let head = format!("{PREFIX}{opcode}");
352 assert!(
353 !written.contains(&head.as_str()),
354 "a rule in {} selects {opcode} now, so it is not waiting on tamnd/rucc#375",
355 TABLE.source
356 );
357 assert!(
358 x86_64::INSTS.iter().any(|&(described, _)| described == opcode),
359 "{opcode} is not an instruction anything describes"
360 );
361 }
362 }
363
364 /// The same staleness rule on the x87 pair, and one thing more that is particular to them.
365 ///
366 /// They are a pair. An instruction that pushes onto the x87 stack and nothing that pops off it
367 /// again would leave the stack one deeper than the function found it, which is not a mistake
368 /// the allocator or the block layout could catch, since neither of them knows the stack is
369 /// there. So the two arrive together and leave together, and that is what this says.
370 #[test]
371 fn the_x87_stack_is_reached_by_a_pair_and_by_nothing_else() {
372 let written = heads();
373 for &opcode in X87 {
374 assert!(
375 x86_64::INSTS.iter().any(|&(described, _)| described == opcode),
376 "{opcode} is not an instruction anything describes"
377 );
378 assert!(
379 !written.contains(&format!("{PREFIX}{opcode}").as_str()),
380 "a rule in {} selects {opcode}, which `crate::lower` also writes by hand",
381 TABLE.source
382 );
383 }
384 // One way onto the stack per format a value can be read from, one way off it per format a
385 // value can be written to, the control word pair that is neither, and the arithmetic. The
386 // count is here as well as in the target description because this list is what says none
387 // of them is reachable, and a name that arrived here without its partner would be a format
388 // this target can convert in one direction and not the other.
389 assert_eq!(X87.len(), 30, "twelve that move a value and eighteen that work on one");
390 }
391}