Skip to main content

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