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