rucc_codegen/lowering.rs
1//! The passes that run before selection, as a group with a name and a stated membership.
2//!
3//! Design: `spec/optimizer/36-lowering-and-isel.md` section 36.1.
4//!
5//! Section 36.1 reads the list of passes gcc runs immediately before `pass_expand` and draws one
6//! conclusion from it. Nine of them are lowerings, and each one turns a construct into a shape of
7//! control flow or a shape of arithmetic that the expander would otherwise have to invent. The
8//! expander is the wrong place to invent control flow, because by the time it runs the graph is
9//! being consumed rather than edited. That is spec 10.2's rule arrived at from the other side: a
10//! lowering rule replaces a term with a term and has nowhere to put a block, so any construct whose
11//! lowering is a new shape of control flow is rewritten before selection runs.
12//!
13//! Every one of these passes already existed and every one of them was already called from
14//! `crate::pipeline`, one line at a time, in this order. What did not exist was the thing the
15//! section asks for, which is that they are a group rather than a set of unrelated passes that
16//! happen to run next to each other. The reason gcc's list is nine passes long is that it grew one
17//! pass at a time over three decades, and a group with a written down membership is the thing that
18//! stops the same happening here.
19//!
20//! # The name
21//!
22//! The lowering group, which is what gcc calls its own and is what this module is named after. The
23//! longer and more honest description section 36.1 gives is everything the selector cannot express,
24//! and that is the test for whether something belongs here: not that it is a rewrite of the IR, but
25//! that the thing it rewrites is one no rule in the table can be written for.
26//!
27//! # What is in it
28//!
29//! [`Step::GROUP`], in the order it runs, and that list is the membership. A new lowering is a new
30//! variant of [`Step`] and a new line in that list, which is one place rather than whichever line
31//! of the pipeline looked convenient.
32//!
33//! # What the order is for
34//!
35//! Most of it does not matter and the parts that do are on the variants. The rule behind them is
36//! the same one every time: a pass is written about the constructs the machine has, so anything
37//! that produces a construct somebody below is written about has to run above them. An integer of
38//! forty bits is not a width this machine has, an ordered load is not a load any pass below is
39//! written about, and a quad float is not a float the pass that rewrites floats knows anything of.
40//!
41//! # What it is not
42//!
43//! Not the selector, and not a fixed point. Each step runs once, and a step that produces work for
44//! a step above it would be a bug in this order rather than a reason to run the group twice.
45//!
46//! Not a promise that the construct is gone either, and this is the part worth reading twice. Every
47//! step here has cases it walks away from: a copy too large to be a run of moves, an ordered access
48//! wider than the machine does in one go, a conversion the machine already has an instruction for
49//! and so has no reason to touch. Some of those are the machine having the construct after all and
50//! some of them are a refusal, and a refusal is left standing on purpose, because the selector is
51//! what names the construct it had no rule for and that is a better error than a rewrite that
52//! guessed.
53//!
54//! So what [`Ran`] records is what each step found and what it left, and reading one of those is
55//! how you tell the two apart. What the group promises is only that every construct in the list was
56//! put in front of the step that answers for it, which is the thing that stops being true when
57//! somebody adds a lowering to whichever line of the pipeline looked convenient.
58
59use rucc_base::Interner;
60use rucc_ir::{Func, Opcode};
61use rucc_target::CallRegs;
62
63use crate::{expand, quad, retry, switch, varargs, wide, widths};
64
65/// One member of the group.
66///
67/// The name of the variant is the name of the construct rather than the name of the function that
68/// takes it out, because the membership is a list of constructs. Which function answers for one is
69/// something this file knows and nothing outside it needs to.
70#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
71pub enum Step {
72 /// A `switch`, as the decision tree document 24 describes.
73 Switches,
74 /// A read modify write this machine has no single instruction for, as a loop around the compare
75 /// and exchange.
76 ///
77 /// Beside the switches rather than down with the rest of the rewriting, because both of them
78 /// make blocks and nothing in [`crate::expand`] may.
79 Retries,
80 /// An ordered load or store, as the plain access and a barrier.
81 ///
82 /// Above everything below it, since what an ordered access becomes here is a plain one and
83 /// every pass below is written about a plain one by name. It is also why this is above the
84 /// retries rather than below: the head of the loop they build reads with an ordered load.
85 Orderings,
86 /// An arithmetic operation that also says whether it overflowed, as the arithmetic and the test.
87 ///
88 /// Above the splitting rather than below it, because an overflow check is the one instruction
89 /// whose result is two things and the splitting has no answer for that, while the arithmetic it
90 /// becomes here is adds, multiplies and comparisons the splitting knows already. Nothing is
91 /// lost by running it this early: the widths it is written for are the widths the machine has,
92 /// so a check at any other width is refused by name either way round.
93 Overflows,
94 /// An integer wider than a register, as the two halves of one.
95 ///
96 /// Ahead of the width legalisation and not part of it, because the two go in opposite
97 /// directions: an integer of forty bits becomes one of sixty four down there and one of a
98 /// hundred and twenty eight becomes two of sixty four here. Doing this first means a function
99 /// holding both is one the step below still works on.
100 Halves,
101 /// An integer at a width the machine does not have, as the width it is held in.
102 ///
103 /// Before everything after it, because every pass after it is written about widths the machine
104 /// has and an integer of forty bits is not one of them.
105 Widths,
106 /// A byte reversal, as the halving run of swaps it is.
107 Bytes,
108 /// A leading zero, trailing zero or set bit count, as the arithmetic that answers it.
109 Counts,
110 /// Anything at all at the quad float format, as a call to the routine for it.
111 ///
112 /// Above the float rewriting rather than part of it, because the two are written about
113 /// different machines: every rewrite down there ends at an instruction this machine has, and
114 /// every operation up here ends at a call because this machine has no instruction at the format
115 /// at all. Running first means the step below never sees a quad.
116 Quads,
117 /// A float constant, a negation and the conversions, as the integer work spec 10.2 asks for.
118 Floats,
119 /// A `memcpy`, a `memset` or a `memmove`, as the moves it is or as the call it is too big for.
120 Bulk,
121 /// The size of a stack allocation, rounded up to what the stack pointer has to stay on.
122 ///
123 /// The one step here that takes nothing out. It rewrites an operand of the instruction and
124 /// leaves the instruction where it is, which is why [`Step::opcodes`] answers with nothing for
125 /// it.
126 Rounds,
127 /// A variable argument list, as spec 10.7's split describes.
128 Varargs,
129}
130
131impl Step {
132 /// The group, in the order it runs, which is the membership section 36.1 asks to see.
133 pub const GROUP: &'static [Self] = &[
134 Self::Switches,
135 Self::Retries,
136 Self::Orderings,
137 Self::Overflows,
138 Self::Halves,
139 Self::Widths,
140 Self::Bytes,
141 Self::Counts,
142 Self::Quads,
143 Self::Floats,
144 Self::Bulk,
145 Self::Rounds,
146 Self::Varargs,
147 ];
148
149 /// What it is called in a dump.
150 #[must_use]
151 pub const fn name(self) -> &'static str {
152 match self {
153 Self::Switches => "switches",
154 Self::Retries => "retries",
155 Self::Orderings => "orderings",
156 Self::Overflows => "overflows",
157 Self::Halves => "halves",
158 Self::Widths => "widths",
159 Self::Bytes => "bytes",
160 Self::Counts => "counts",
161 Self::Quads => "quads",
162 Self::Floats => "floats",
163 Self::Bulk => "bulk",
164 Self::Rounds => "rounds",
165 Self::Varargs => "varargs",
166 }
167 }
168
169 /// The construct it is the answer to, in the words section 36.1 uses for it.
170 #[must_use]
171 pub const fn construct(self) -> &'static str {
172 match self {
173 Self::Switches => "a switch",
174 Self::Retries => "a read modify write with no instruction behind it",
175 Self::Orderings => "an ordered load or store",
176 Self::Overflows => "arithmetic that reports whether it overflowed",
177 Self::Halves => "an integer wider than a register",
178 Self::Widths => "an integer at a width the machine does not have",
179 Self::Bytes => "a byte reversal",
180 Self::Counts => "a bit count",
181 Self::Quads => "the quad float format",
182 Self::Floats => "a float constant, a negation or a conversion",
183 Self::Bulk => "a bulk copy or fill",
184 Self::Rounds => "a stack allocation whose size is not a multiple of the alignment",
185 Self::Varargs => "a variable argument list",
186 }
187 }
188
189 /// The opcodes it is the answer to, which is what [`Did::found`] and [`Did::left`] count.
190 ///
191 /// Not a promise that none of them survive. Several of these steps have a case they leave where
192 /// it stands, either because the machine turns out to have the construct after all or because
193 /// this is a refusal being handed to the selector to name, and both of those show up here as a
194 /// count that did not reach zero. What the pair of numbers is for is telling somebody reading a
195 /// dump which of those happened.
196 ///
197 /// Empty for [`Step::Rounds`], which rewrites an operand rather than taking an instruction out,
198 /// and empty for the three that work by type rather than by opcode: an integer of forty bits,
199 /// one of a hundred and twenty eight and a quad float are all spelled with the same opcodes as
200 /// anything else, and what makes them the construct is the type on the values.
201 #[must_use]
202 pub const fn opcodes(self) -> &'static [Opcode] {
203 match self {
204 Self::Switches => &[Opcode::Switch],
205 Self::Retries => &[],
206 Self::Orderings => &[Opcode::AtomicLoad, Opcode::AtomicStore],
207 Self::Overflows => &[
208 Opcode::UAddOverflow,
209 Opcode::SAddOverflow,
210 Opcode::USubOverflow,
211 Opcode::SSubOverflow,
212 Opcode::UMulOverflow,
213 Opcode::SMulOverflow,
214 ],
215 Self::Halves | Self::Widths | Self::Rounds => &[],
216 Self::Bytes => &[Opcode::Bswap],
217 Self::Counts => &[Opcode::Ctlz, Opcode::Cttz, Opcode::Ctpop],
218 Self::Quads => &[],
219 Self::Floats => &[
220 Opcode::FConst,
221 Opcode::FNeg,
222 Opcode::SIToFP,
223 Opcode::UIToFP,
224 Opcode::FPToSI,
225 Opcode::FPToUI,
226 ],
227 Self::Bulk => &[Opcode::Memcpy, Opcode::Memset, Opcode::Memmove],
228 Self::Varargs => &[Opcode::VaArg, Opcode::VaObject, Opcode::VaCopy, Opcode::VaEnd],
229 }
230 }
231
232 /// Whether this step works on the whole function at once and says whether it rewrote it.
233 ///
234 /// Two of them do. Both retype every value of a width, so either the whole function can be
235 /// rewritten or none of it can, and they answer with a boolean for that reason. A `false` from
236 /// one covers two different things, a function with nothing at that width in it and a function
237 /// holding something the step did not understand, and neither is an error: the second leaves
238 /// the selector to refuse by naming the construct it had no rule for.
239 ///
240 /// Everything else here works instruction by instruction and has nothing to say at that scale,
241 /// which is why [`Did::untouched`] is only ever true for these two.
242 #[must_use]
243 pub const fn whole_function(self) -> bool {
244 matches!(self, Self::Halves | Self::Widths)
245 }
246
247 /// Runs this one step, answering whether it rewrote the function.
248 ///
249 /// Only the two that [`Step::whole_function`] names ever answer `false`, because they are the
250 /// only two that know. The rest work instruction by instruction and are not asked.
251 fn run(self, func: &mut Func, names: &mut Interner, conv: &CallRegs) -> bool {
252 match self {
253 Self::Switches => switch::switches(func),
254 Self::Retries => retry::loops(func),
255 Self::Orderings => expand::orderings(func, conv.word),
256 Self::Overflows => expand::overflows(func),
257 Self::Halves => return wide::halves(func, names, conv),
258 Self::Widths => return widths::integers(func),
259 Self::Bytes => expand::bytes(func),
260 Self::Counts => expand::counts(func),
261 Self::Quads => quad::calls(func, names),
262 Self::Floats => expand::floats(func),
263 Self::Bulk => expand::bulk(func, names, conv.word),
264 Self::Rounds => expand::rounds(func, conv.stack_align),
265 Self::Varargs => varargs::lists(func, conv),
266 }
267 true
268 }
269}
270
271/// What one step did to one function.
272#[derive(Debug, Clone, Copy, PartialEq, Eq)]
273pub struct Did {
274 /// Which step it was.
275 pub step: Step,
276 /// How many instructions of the kind it answers for were there when it started.
277 pub found: usize,
278 /// How many were still there when it finished, which is not always zero. See [`Step::opcodes`].
279 pub left: usize,
280 /// How many instructions the function had before it ran.
281 pub before: usize,
282 /// How many it had after.
283 pub after: usize,
284 /// Whether it said it left the function exactly as it was, which only the two that
285 /// [`Step::whole_function`] names ever say.
286 pub untouched: bool,
287}
288
289/// What the whole group did to one function.
290#[derive(Debug, Default, Clone, PartialEq, Eq)]
291pub struct Ran {
292 /// One entry per step, in the order they ran, including the ones that found nothing.
293 ///
294 /// Including them on purpose. A dump that lists only the steps that fired is a dump that cannot
295 /// tell a step that found nothing from a step somebody forgot to add to the group.
296 pub did: Vec<Did>,
297}
298
299impl Ran {
300 /// What one step of the group did, which every step has an entry for.
301 ///
302 /// # Panics
303 ///
304 /// Panics if this record did not come from [`group`], since that is the only way a step of
305 /// [`Step::GROUP`] can be missing from it.
306 #[must_use]
307 pub fn of(&self, step: Step) -> Did {
308 *self.did.iter().find(|did| did.step == step).expect("every step has an entry")
309 }
310
311 /// The dump, one line per step.
312 ///
313 /// Plain text with the name first, because the thing anybody reads this for is which step
314 /// changed the function, and a format that has to be parsed to answer that is the wrong format
315 /// for a debugging aid. `-Zlowering=` writes it.
316 #[must_use]
317 pub fn render(&self, func: &str) -> String {
318 use std::fmt::Write;
319
320 let mut out = format!("lowering {func}\n");
321 for did in &self.did {
322 let _ = write!(
323 out,
324 " {:<10} {:>4} -> {:>4} insts",
325 did.step.name(),
326 did.before,
327 did.after
328 );
329 // Said the rare way round on purpose. The two whole function steps answer `false` for
330 // every function with nothing at their width in it, which is nearly all of them, so a
331 // line per function saying so would bury the one that matters.
332 if did.step.whole_function() && !did.untouched {
333 let _ = write!(out, ", retyped every value at that width");
334 }
335 if did.found > 0 {
336 let _ = write!(out, ", found {}, left {}", did.found, did.left);
337 }
338 let _ = writeln!(out, " ({})", did.step.construct());
339 }
340 out
341 }
342}
343
344/// What the group did to every function a run lowered, in the order they came through.
345///
346/// The same shape [`crate::pressure::Pressure`] has and for the same reason: a caller collects one
347/// of these over a whole command line and asks for the listing once at the end.
348#[derive(Debug, Default, Clone, PartialEq, Eq)]
349pub struct Lowerings {
350 /// One per function, in the order they were lowered.
351 rows: Vec<(String, Ran)>,
352 /// Whether anything is going to read this, which is whether `-Zlowering` was given.
353 wanted: bool,
354}
355
356impl Lowerings {
357 /// Nothing recorded, and nothing counted either.
358 #[must_use]
359 pub fn new() -> Self {
360 Self::default()
361 }
362
363 /// The same, told whether to count, which is what `-Zlowering=FILE` decides.
364 #[must_use]
365 pub fn asked(wanted: bool) -> Self {
366 Self { rows: Vec::new(), wanted }
367 }
368
369 /// Whether the counting is worth doing, which is what [`group`] is passed.
370 ///
371 /// This is a question and not an assumption for a reason that showed up as soon as the numbers
372 /// were measured on something large. Counting is a walk of the function per step, and a
373 /// function's instructions are a linked list, so on the SQLite amalgamation the walks cost
374 /// about two seconds on top of nine, which is more than several of the passes they are
375 /// measuring. A debugging aid nobody asked for should cost nothing, so a run without the flag
376 /// runs the group and records no numbers at all.
377 #[must_use]
378 pub fn wanted(&self) -> bool {
379 self.wanted
380 }
381
382 /// Writes down what the group did to one function.
383 pub fn record(&mut self, name: &str, ran: Ran) {
384 self.rows.push((name.to_owned(), ran));
385 }
386
387 /// Takes in everything another one recorded, which is how one file's answer joins a run's.
388 pub fn merge(&mut self, other: &Self) {
389 self.rows.extend(other.rows.iter().cloned());
390 }
391
392 /// How many functions went through the group.
393 #[must_use]
394 pub fn functions(&self) -> usize {
395 self.rows.len()
396 }
397
398 /// What `-Zlowering=FILE` writes.
399 ///
400 /// A comment holding the count and then one block per function. Whoever reads one of these is
401 /// looking for which step changed a function they are surprised by, so the file is the same
402 /// text in the same order as the group ran, and every step is there whether it did anything or
403 /// not. A dump listing only the steps that fired could not tell a step that found nothing from
404 /// a step somebody forgot to put in the group, which is half of what this is read for.
405 #[must_use]
406 pub fn listing(&self) -> String {
407 let mut out = format!("# rucc lowering: {} functions\n", self.rows.len());
408 for (name, ran) in &self.rows {
409 out.push_str(&ran.render(name));
410 }
411 out
412 }
413}
414
415/// Runs the whole group over one function, in the order [`Step::GROUP`] gives.
416///
417/// This is the entry point section 36.1 asks for. Every caller wanting a function lowered calls
418/// this and nothing else, so adding a lowering is adding it to [`Step::GROUP`] rather than to
419/// whichever line of `crate::pipeline` looked convenient.
420///
421/// `counting` is whether to work out what each step found and left, which is what
422/// [`Lowerings::wanted`] answers and which costs what it says there. The steps run either way and
423/// the function comes out the same; what a `false` gives back is an empty [`Ran`].
424pub fn group(func: &mut Func, names: &mut Interner, conv: &CallRegs, counting: bool) -> Ran {
425 let mut ran = Ran::default();
426 for &step in Step::GROUP {
427 if !counting {
428 step.run(func, names, conv);
429 continue;
430 }
431 let (before, found) = tally(func, step);
432 let did = step.run(func, names, conv);
433 let (after, left) = tally(func, step);
434 ran.did.push(Did { step, found, left, before, after, untouched: !did });
435 }
436 ran
437}
438
439/// How many instructions the function has, and how many of them are the kind this step answers for.
440///
441/// Both in one walk rather than one walk each, since the walk is the expensive part.
442fn tally(func: &Func, step: Step) -> (usize, usize) {
443 let wanted = step.opcodes();
444 let (mut all, mut mine) = (0, 0);
445 for block in func.blocks() {
446 for inst in func.insts(block) {
447 all += 1;
448 if wanted.contains(&func[inst].opcode) {
449 mine += 1;
450 }
451 }
452 }
453 (all, mine)
454}
455
456#[cfg(test)]
457mod tests {
458 use rucc_base::Interner;
459 use rucc_ir::{
460 Builder, Extra, Flags, Float, Func, InstData, MemInfo, MemOrder, Opcode, Restrict,
461 Signature, Type, Value,
462 };
463 use rucc_target::x86_64;
464
465 use super::{Lowerings, Ran, Step, group};
466
467 /// A function with a body somebody else writes, which is the same helper the passes being
468 /// grouped are each tested with.
469 fn one(
470 params: &[Type],
471 returns: &[Type],
472 body: impl FnOnce(&mut Builder<'_>, &[Value]),
473 ) -> (Interner, Func) {
474 let mut names = Interner::new();
475 let mut func = Func::new(
476 names.intern("f"),
477 Signature::new().with_params(params).with_returns(returns),
478 );
479 let entry = func.create_block();
480 let args: Vec<_> = params.iter().map(|&ty| func.append_param(entry, ty)).collect();
481 let mut build = Builder::new(&mut func, entry);
482 body(&mut build, &args);
483 (names, func)
484 }
485
486 fn run(func: &mut Func, names: &mut Interner) -> Ran {
487 group(func, names, &x86_64::SYSV, true)
488 }
489
490 fn i32() -> Type {
491 Type::int(32)
492 }
493
494 #[test]
495 fn the_group_is_the_passes_the_pipeline_used_to_call_one_line_at_a_time() {
496 // The list rather than the length, because a list checked only for its length is a list
497 // anybody can reorder without noticing, and the order is half of what this file is for.
498 let names: Vec<&str> = Step::GROUP.iter().map(|step| step.name()).collect();
499 assert_eq!(
500 names,
501 [
502 "switches",
503 "retries",
504 "orderings",
505 "overflows",
506 "halves",
507 "widths",
508 "bytes",
509 "counts",
510 "quads",
511 "floats",
512 "bulk",
513 "rounds",
514 "varargs",
515 ]
516 );
517 }
518
519 #[test]
520 fn every_step_says_what_it_is_for_and_no_two_say_the_same_thing() {
521 let mut names: Vec<&str> = Step::GROUP.iter().map(|step| step.name()).collect();
522 let mut constructs: Vec<&str> = Step::GROUP.iter().map(|step| step.construct()).collect();
523 assert!(constructs.iter().all(|construct| !construct.is_empty()));
524 for list in [&mut names, &mut constructs] {
525 let was = list.len();
526 list.sort_unstable();
527 list.dedup();
528 assert_eq!(list.len(), was, "two steps say the same thing");
529 }
530 }
531
532 #[test]
533 fn a_function_with_nothing_in_it_leaves_every_step_with_nothing_to_say() {
534 let (mut names, mut func) = one(&[], &[], |build, _| {
535 build.ret(&[]);
536 });
537 let ran = run(&mut func, &mut names);
538 assert_eq!(ran.did.len(), Step::GROUP.len());
539 assert!(ran.did.iter().all(|did| did.found == 0 && did.before == did.after));
540 }
541
542 #[test]
543 fn nothing_in_the_group_is_left_out_of_the_record() {
544 let (mut names, mut func) = one(&[], &[], |build, _| {
545 build.ret(&[]);
546 });
547 let ran = run(&mut func, &mut names);
548 let ordered: Vec<Step> = ran.did.iter().map(|did| did.step).collect();
549 assert_eq!(ordered, Step::GROUP);
550 }
551
552 /// `unsigned b(unsigned x) { return __builtin_bswap32(x); }`, which is one of the constructs
553 /// in the list and therefore one the group owes an answer for.
554 #[test]
555 fn a_byte_reversal_does_not_survive_the_group() {
556 let (mut names, mut func) = one(&[i32()], &[i32()], |build, args| {
557 let swapped = build.unary(Opcode::Bswap, args[0], i32());
558 build.ret(&[swapped]);
559 });
560 let ran = run(&mut func, &mut names);
561 let did = ran.of(Step::Bytes);
562 assert_eq!(did.found, 1);
563 assert_eq!(did.left, 0);
564 assert!(did.after > did.before, "one instruction became several");
565 }
566
567 /// `int c(unsigned x) { return __builtin_popcount(x); }`.
568 #[test]
569 fn a_bit_count_does_not_survive_the_group() {
570 let (mut names, mut func) = one(&[i32()], &[i32()], |build, args| {
571 let ones = build.unary(Opcode::Ctpop, args[0], i32());
572 build.ret(&[ones]);
573 });
574 let ran = run(&mut func, &mut names);
575 assert_eq!(ran.of(Step::Counts).found, 1);
576 assert_eq!(ran.of(Step::Counts).left, 0);
577 }
578
579 /// `double n(double x) { return -x; }`, which is a float rather than an integer and so reaches
580 /// a different member of the group.
581 #[test]
582 fn a_float_negation_does_not_survive_the_group() {
583 let f64 = Type::float(Float::F64);
584 let (mut names, mut func) = one(&[f64], &[f64], |build, args| {
585 let negated = build.unary(Opcode::FNeg, args[0], f64);
586 build.ret(&[negated]);
587 });
588 let ran = run(&mut func, &mut names);
589 assert_eq!(ran.of(Step::Floats).found, 1);
590 assert_eq!(ran.of(Step::Floats).left, 0);
591 }
592
593 /// `long a(long *p) { return __atomic_load_n(p, __ATOMIC_SEQ_CST); }`, which on this machine is
594 /// the same `mov` an ordinary read is, and which nothing below this step in the group knows the
595 /// name of.
596 #[test]
597 fn an_ordered_load_does_not_survive_the_group() {
598 let i64 = Type::int(64);
599 let (mut names, mut func) = one(&[Type::PTR], &[i64], |build, args| {
600 let info = MemInfo {
601 size: 8,
602 align: 8,
603 order: MemOrder::SeqCst,
604 tbaa: None,
605 owns: 0,
606 restrict: Restrict::NONE,
607 };
608 let value = build.atomic_load(i64, args[0], info, Flags::NONE);
609 build.ret(&[value]);
610 });
611 let ran = run(&mut func, &mut names);
612 assert_eq!(ran.of(Step::Orderings).found, 1);
613 assert_eq!(ran.of(Step::Orderings).left, 0);
614 }
615
616 /// Every construct with an opcode behind it, checked the same way in one loop, so that a
617 /// thirteenth member added to the group without an answer is a failure here rather than
618 /// something noticed later by the selector refusing it by name.
619 #[test]
620 fn nothing_the_group_names_an_opcode_for_is_still_there_afterwards() {
621 for step in Step::GROUP {
622 let Some((mut names, mut func)) = holding(*step) else {
623 continue;
624 };
625 let ran = run(&mut func, &mut names);
626 let did = ran.of(*step);
627 assert_eq!(did.found, 1, "{}: the construct was not built", step.name());
628 assert_eq!(did.left, 0, "{}: the construct survived the group", step.name());
629 }
630 }
631
632 /// One small function holding exactly one of the construct that step answers for, for the
633 /// steps whose construct is an opcode. The rest answer `None`: three of them are about a type
634 /// rather than an opcode, one rewrites an operand and takes nothing out, and the variable
635 /// argument list needs a whole calling convention around it to be worth building here.
636 fn holding(step: Step) -> Option<(Interner, Func)> {
637 let i32 = i32();
638 let i64 = Type::int(64);
639 let f64 = Type::float(Float::F64);
640 Some(match step {
641 Step::Bytes => one(&[i32], &[i32], |build, args| {
642 let swapped = build.unary(Opcode::Bswap, args[0], i32);
643 build.ret(&[swapped]);
644 }),
645 Step::Counts => one(&[i32], &[i32], |build, args| {
646 let ones = build.unary(Opcode::Ctlz, args[0], i32);
647 build.ret(&[ones]);
648 }),
649 Step::Floats => one(&[], &[f64], |build, _| {
650 let k = build.fconst(f64, 0x3ff8_0000_0000_0000);
651 build.ret(&[k]);
652 }),
653 Step::Orderings => one(&[Type::PTR], &[i64], |build, args| {
654 let info = MemInfo {
655 size: 8,
656 align: 8,
657 order: MemOrder::SeqCst,
658 tbaa: None,
659 owns: 0,
660 restrict: Restrict::NONE,
661 };
662 let value = build.atomic_load(i64, args[0], info, Flags::NONE);
663 build.ret(&[value]);
664 }),
665 Step::Overflows => one(&[i32, i32], &[i32], |build, args| {
666 let (sum, _) = build.checked(Opcode::UAddOverflow, args[0], args[1]);
667 build.ret(&[sum]);
668 }),
669 // `struct point { int x, y; } a, b; a = b;`, where the size and the alignment are on
670 // the access rather than in an operand, which is the shape the front end writes.
671 Step::Bulk => one(&[Type::PTR, Type::PTR], &[], |build, args| {
672 let info = MemInfo {
673 size: 16,
674 align: 8,
675 order: MemOrder::NotAtomic,
676 tbaa: None,
677 owns: 0,
678 restrict: Restrict::NONE,
679 };
680 let mem = build.func().add_mem(info);
681 let operands = build.func().push_values(&[args[0], args[1]]);
682 build.inst(
683 InstData {
684 args: operands,
685 extra: Extra::Mem(mem),
686 ..InstData::new(Opcode::Memcpy)
687 },
688 &[],
689 );
690 build.ret(&[]);
691 }),
692 _ => return None,
693 })
694 }
695
696 /// The cheap path, which is what a build that did not ask for the dump takes. The steps still
697 /// run and the function still comes out lowered, and what is skipped is a walk of the function
698 /// per step, which is not free on anything the size of a real translation unit.
699 #[test]
700 fn a_run_that_did_not_ask_for_the_dump_still_lowers_and_counts_nothing() {
701 let build = |build: &mut Builder<'_>, args: &[Value]| {
702 let swapped = build.unary(Opcode::Bswap, args[0], i32());
703 build.ret(&[swapped]);
704 };
705 let (mut names, mut func) = one(&[i32()], &[i32()], build);
706 let quiet = group(&mut func, &mut names, &x86_64::SYSV, false);
707 assert!(quiet.did.is_empty(), "nothing was counted");
708 assert_eq!(super::tally(&func, Step::Bytes), (super::tally(&func, Step::Bytes).0, 0));
709
710 // The same function through the counting path comes out the same size, so what the flag
711 // changes is what was written down and not what was done.
712 let (mut names, mut func) = one(&[i32()], &[i32()], build);
713 let loud = group(&mut func, &mut names, &x86_64::SYSV, true);
714 assert_eq!(loud.of(Step::Bytes).left, 0);
715 assert_eq!(
716 loud.did.last().expect("thirteen of them").after,
717 super::tally(&func, Step::Bytes).0
718 );
719 }
720
721 #[test]
722 fn nothing_is_recorded_for_a_run_that_did_not_ask() {
723 let mut quiet = Lowerings::new();
724 assert!(!quiet.wanted());
725 quiet.record("f", Ran::default());
726 assert_eq!(quiet.functions(), 1, "recording still works if somebody does it anyway");
727
728 let asked = Lowerings::asked(true);
729 assert!(asked.wanted());
730 assert_eq!(asked.listing(), "# rucc lowering: 0 functions\n");
731 }
732
733 #[test]
734 fn the_dump_names_every_step_whether_it_fired_or_not() {
735 // A dump listing only the steps that fired cannot tell a step that found nothing from a
736 // step somebody forgot to put in the group, which is the one thing it is read for.
737 let (mut names, mut func) = one(&[i32()], &[i32()], |build, args| {
738 let swapped = build.unary(Opcode::Bswap, args[0], i32());
739 build.ret(&[swapped]);
740 });
741 let ran = run(&mut func, &mut names);
742 let text = ran.render("f");
743 assert!(text.starts_with("lowering f\n"), "{text}");
744 for step in Step::GROUP {
745 assert!(text.contains(step.name()), "{} is missing from {text}", step.name());
746 }
747 assert!(text.contains("found 1, left 0"), "{text}");
748 assert_eq!(text.lines().count(), Step::GROUP.len() + 1);
749 }
750
751 #[test]
752 fn only_the_two_steps_that_retype_a_whole_function_ever_say_they_touched_nothing() {
753 // The rest work instruction by instruction and are never asked, so a `true` from one of
754 // them is not evidence of anything and the dump does not print it.
755 assert_eq!(
756 Step::GROUP.iter().filter(|step| step.whole_function()).copied().collect::<Vec<_>>(),
757 [Step::Halves, Step::Widths]
758 );
759 for step in Step::GROUP {
760 if step.whole_function() {
761 // Both of them are about the width on a value rather than about an opcode, so
762 // there is nothing for `found` and `left` to count.
763 assert!(step.opcodes().is_empty(), "{} counts opcodes", step.name());
764 }
765 }
766 }
767
768 #[test]
769 fn an_instruction_nothing_in_the_group_is_about_is_left_exactly_where_it_was() {
770 let (mut names, mut func) = one(&[i32()], &[i32()], |build, args| {
771 let seven = build.iconst(i32(), 7);
772 let sum = build.binary(Opcode::Add, args[0], seven, Flags::NONE);
773 build.ret(&[sum]);
774 });
775 let before = super::tally(&func, Step::Rounds).0;
776 let ran = run(&mut func, &mut names);
777 assert_eq!(super::tally(&func, Step::Rounds).0, before);
778 assert!(ran.did.iter().all(|did| did.found == 0));
779 }
780}