Skip to main content

rucc_opt/
pipeline.rs

1//! The pipelines, one per optimization level, and the manager that runs one.
2//!
3//! Section 9.1 of `spec/09-optimizer.md` says the pipelines are written out rather than assembled
4//! from flags, and gives the reason: the prior art ran the same pipeline at every level and named
5//! that as a limitation. A level here is a list of pass names, and the list is the definition of
6//! the level rather than something that emerges from which flags happen to be set.
7//!
8//! Section 9.10 says the manager is deliberately boring. There is no adaptive ordering and no
9//! scheduling heuristic, because document 03's determinism rule needs the same input to produce
10//! the same output on every host and predictability is worth more than the last percent.
11//!
12//! What the manager does beyond running the list is the four things that make a pass debuggable:
13//! it counts each pass's transformations against its fuel, it collects what each pass said it did
14//! and did not do, it dumps the IR around whichever passes were asked for, and it verifies any
15//! function a pass changed.
16//!
17//! That last one is section 41.4 of `spec/optimizer/41-correctness.md`, which reads GCC's
18//! `execute_function_todo` and takes six things from it. Three of them are already true here by
19//! construction and are worth naming so that nobody looks for them. GCC verifies what the IR
20//! currently is, by consulting `curr_properties`, because its IR passes through GENERIC, GIMPLE
21//! with and without a CFG, GIMPLE in SSA, and RTL. rucc has one IR, it is in SSA from the moment
22//! the lowering walk builds it, and it always has a CFG, so the applicable set never varies and a
23//! bitmask saying so would have nothing to say. GCC guards the verifiers with `!seen_error()`,
24//! because after a user error the IR is legitimately malformed and an internal error raised over
25//! it hides the real diagnostic. Here the optimizer is not reached at all after a parse, check or
26//! lowering error, which is the same guard placed one level up where it cannot be forgotten. And
27//! GCC asserts that a verifier did not change the dominator state. Here a verifier takes the
28//! module by shared reference, so that is a type error rather than an assertion.
29//!
30//! What is left of the six is the part below: verify what changed, not everything, and say which
31//! function it was.
32
33use std::collections::HashMap;
34use std::fmt::Write as _;
35
36use rucc_base::{Interner, Symbol};
37use rucc_ir::{FuncId, Module};
38use rucc_session::OptLevel;
39
40use crate::{Analyses, Fuel, Gates, Pass, Preserved, Stats, nofree, pass};
41
42/// The passes that read a summary [`nofree::annotate`] writes onto the IR.
43///
44/// A list rather than one name because there will be more of them: section 7.5 asks for three more
45/// summary fields and section 7.3's lifetime elimination is the next thing to want this one. A pass
46/// that reads a summary and is not named here reads whatever the last build left, which is nothing,
47/// so the cost of forgetting to add a name is a missed optimization.
48const READS_SUMMARIES: &[&str] = &["discharge"];
49
50/// `-O0`. One pass, and it is not an optimization. Section 9.1 gives this level SSA
51/// construction, which the lowering walk in `spec/08-ir.md` already does, and mem2reg for the
52/// allocas that are left, which is the next pass to be written.
53///
54/// `simplify-cfg` is here because a branch on a condition that is a constant is not a missed
55/// optimization, it is a call to a function the program never calls, and a program that calls a
56/// function it never calls is one that does not link. That is issue 359, gcc removes the code at
57/// every level including this one, and a `-O0` that emitted it would be a `-O0` some correct
58/// programs cannot be built at. Nothing else runs, and no analysis beyond the graph the pass
59/// reads reachability out of is computed.
60const O0: &[&str] = &["simplify-cfg"];
61
62/// `-O1`. Section 9.1 asks for one e-graph round, conservative inlining, simplify-CFG, SROA,
63/// GVN, DCE, LICM and the loop canonicalizations. Folding, control flow simplification and dead
64/// code elimination are the part of that which exists, with the peephole among them. They run in
65/// that order because folding and the peephole are what make most of the dead code there is to
66/// eliminate, because a constant a fold produced is a branch condition the control flow pass can
67/// then read, and because the comparison that branch was on is dead once it has.
68///
69/// The peephole runs on both sides of `narrow`, which is the one place in this list where a pass
70/// is named twice, so the reason is worth stating. The rewrite table is written at a width, and
71/// the widths below `int` are unreachable from C source: the integer promotions mean an addition
72/// of two `char` values arrives here as an `add.i32`, so a rule about `add.i8` matches nothing
73/// that a front end can produce. `narrow` is what puts the width back, and it is therefore the
74/// only producer the narrow half of the table has. Running the peephole only before it left
75/// sixty nine of the first hundred and twenty five rules unable to fire on any program, which is
76/// issue 505 and is what the corpus measured. Running it only after it would give up the smaller
77/// trees the peephole hands `narrow`, since a subtree `narrow` redoes has to have one reader and
78/// an identity left standing is a second one. Both sides costs one more walk over each function
79/// and is what the pass is for.
80///
81/// `phiopt` comes after `thread` and the order between them is not arbitrary. Both look at a
82/// diamond whose arms carry a value to a join. Where the join then branches on that value,
83/// threading removes a branch and costs nothing, and if-conversion would have turned the same
84/// shape into a `select` the join branches on instead, which is strictly worse. Threading first
85/// leaves if-conversion the diamonds whose value is used rather than tested, which are the ones it
86/// is for.
87///
88/// `prune` is between `phiopt` and `simplify-cfg` and both sides of that are load bearing. It reads
89/// document 10's ranges off the graph to find a branch that can only go one way and a switch case
90/// nothing can reach, so it has to run after the two passes that change the graph most. What it
91/// leaves is a jump where a branch was and a block nothing reaches, and `simplify-cfg` is the pass
92/// that takes those out, so it has to run before it rather than after.
93///
94/// `canon` is where document 26's loop pipeline opens, so it goes after the value level passes and
95/// before the cleanup. It gives every loop a preheader, one latch, exits of its own and loop closed
96/// form, which is what lets the loop passes that follow it write `insert at the end of the
97/// preheader` rather than each making one. On its own it generates nothing: the blocks it adds are
98/// empty and the parameters it adds have one argument each, and `simplify-cfg` runs straight after
99/// it and takes both back out to a fixed point. That is section 26.7's arrangement, and it is why
100/// the position matters more than the pass does until the loop passes land on top of it.
101///
102/// `header-copy` is section 26.7's third step and `canon` runs again after it, which is the same
103/// section's instruction to re-canonicalize the loops it changed. It has to: what the copy leaves
104/// is a loop entered from a block that branches two ways, and a block that branches two ways is not
105/// a preheader. Nothing between the two needs the properties, so the second run is bookkeeping
106/// against the loop passes that come later rather than something this level's output depends on,
107/// and `simplify-cfg` after it takes out the blocks and parameters both runs added that nothing
108/// used.
109///
110/// `licm` comes after the copy and the canonicalization behind it, and section 27.1 says why it has
111/// to. What it may move in front of a loop depends on what runs on every entry to the loop, and
112/// after that pair that is the whole body rather than the header alone. Running it before the
113/// copy would leave it the header, which is most of the pass's value gone. It is also the reason
114/// the copy exists, so the two are one arrangement read from either end.
115///
116/// It is in the three speed levels and not in `-Os` or `-Oz`. Moving a computation out of a loop
117/// does not remove one, so there are no bytes in it for a level whose cost model is size, and the
118/// one thing it can cost is a spill inside the loop, which is bytes. That trade is worth making for
119/// time and there is nothing on the other side of it for space.
120///
121/// `unroll` runs after `licm` and only at the two speed levels. After, because what it does is copy
122/// the body, and a computation licm has already moved in front of the loop is one the copies do not
123/// each get their own of. It needs the same shape licm does and for the same reason, a loop that
124/// tests at the bottom with a preheader in front of it, so it sits at the end of the same run of
125/// loop passes rather than anywhere of its own. `simplify-cfg` straight after it is what turns the
126/// chain of copies into one block, since each copy now ends in a jump to the next and a block with
127/// one way in and one way out is a block that goes away.
128///
129/// `hoist` is the first of the two check passes and it runs where it does because of what is above
130/// it. It needs a loop that tests at the bottom, which is what `header-copy` makes, and it needs a
131/// preheader to put a check in, which is what the `canon` after it puts back. Running it before
132/// `discharge` rather than after is deliberate as well: what it leaves in the preheader is a check
133/// over the whole range the loop sweeps, and that is a fact `discharge` can then use on anything
134/// else in front of the loop that is about the same bytes.
135///
136/// `discharge` is second to last, between `hoist` and `dce`, and both neighbours are the reason. It
137/// reads the dominator tree to find a safety check whose bytes an earlier check already covered, so
138/// it wants the graph after the block merging rather than before, when a straight run of code is
139/// still several blocks and a fact does not reach the check it would cover. What it leaves behind
140/// is the `cap_of` the check it removed was reading, which nothing now reads, so `dce` after it is
141/// what makes the function smaller rather than shorter by one instruction. It is in every level
142/// except `-O0`, which keeps every check on purpose: document 14 measures against a build where
143/// nothing was discharged, and that build is `-O0`.
144const O1: &[&str] = &[
145    "fold",
146    "simplify",
147    "narrow",
148    "simplify",
149    "thread",
150    "phiopt",
151    "prune",
152    "canon",
153    "header-copy",
154    "canon",
155    "licm",
156    "simplify-cfg",
157    "hoist",
158    "discharge",
159    "dce",
160];
161
162/// `-O2`. The level the code quality claim is about. Section 9.1 asks for two e-graph rounds
163/// around the loop pipeline, the full inlining cost model, Memory SSA and the full alias
164/// analysis stack, and then the scalar and machine passes on top.
165///
166/// `short-circuit` is the one pass here that `-O1` does not have, and section 22.5 is where the
167/// level comes from. It folds the two branches of an `a && b` into one, which costs the right
168/// operand's work on the path that was skipping it and buys a branch the machine no longer has to
169/// guess. That is a trade worth making when the aim is speed and the branch is hard to call, and
170/// it is not one to make by default, which is what `-O1` is.
171///
172/// It runs before `thread` and `phiopt` rather than after, and the order is not arbitrary. Both of
173/// those look at edges, and the collapse removes a block and turns two edges into one, so running
174/// it first hands them a smaller graph with nothing lost. The other way round, threading is free
175/// to give the second branch's block another predecessor, and a block two edges reach is one the
176/// collapse will not touch, so a chain that was foldable stops being foldable.
177const O2: &[&str] = &[
178    "fold",
179    "simplify",
180    "narrow",
181    "simplify",
182    "short-circuit",
183    "thread",
184    "phiopt",
185    "prune",
186    "canon",
187    "header-copy",
188    "canon",
189    "licm",
190    "unroll",
191    "simplify-cfg",
192    "hoist",
193    "discharge",
194    "dce",
195];
196
197/// `-O3`. `-O2` plus loop vectorization, larger inlining and unrolling thresholds, interchange
198/// and distribution where the dependence analysis is confident, and function specialization.
199const O3: &[&str] = &[
200    "fold",
201    "simplify",
202    "narrow",
203    "simplify",
204    "short-circuit",
205    "thread",
206    "phiopt",
207    "prune",
208    "canon",
209    "header-copy",
210    "canon",
211    "licm",
212    "unroll",
213    "simplify-cfg",
214    "hoist",
215    "discharge",
216    "dce",
217];
218
219/// `-Os`. `-O2`'s passes under a size cost model: inlining only where it shrinks, no unrolling
220/// and no vectorization.
221///
222/// The second peephole is here rather than cut for size, because every rule it can fire replaces
223/// a term with a strictly smaller one. Tier one of `spec/optimizer/13-rewrite-rules.md` is
224/// defined that way, so a level that wants smaller code wants more of it and not less.
225///
226/// `short-circuit` is the pass this level drops from `-O2`, for the mirror of that reason. What it
227/// removes is a branch, which is time, and what it adds is the right operand's instructions on a
228/// path that did not run them and an and on top. The code comes out no smaller and usually a byte
229/// or two larger, so a level whose cost model is size has nothing to gain from it.
230///
231/// `hoist` is dropped here as well, and the reason is the same trade read the other way.
232/// It takes a check out of a loop body and puts one in the preheader, plus the address arithmetic
233/// the new check needs, so the loop runs faster and the function is a few instructions larger. That
234/// is a speed transformation with a size cost, which is what `-Os` and `-Oz` are for declining.
235///
236/// `header-copy-small` is the same pass `-O1` and above run under section 26.6's smaller budget.
237/// The copy is code growth and this level pays for it once per loop, so five instructions is what
238/// it will pay. What it gets back is a body that is one region and an exit test at the bottom,
239/// which is slightly smaller in the steady state, so the trade is worth making at a limit that
240/// keeps the header small and not at one that copies twenty instructions to save two.
241const OS: &[&str] = &[
242    "fold",
243    "simplify",
244    "narrow",
245    "simplify",
246    "thread",
247    "phiopt",
248    "prune",
249    "canon",
250    "header-copy-small",
251    "canon",
252    "simplify-cfg",
253    "discharge",
254    "dce",
255];
256
257/// `-Oz`. `-Os` and additionally the outliner, with instruction selection preferring the smaller
258/// encoding wherever there is a choice.
259///
260/// Header copying is the pass this level drops from `-Os`, which section 26.6 asks for by name. It
261/// is the one loop canonicalization that makes the function bigger, `-Oz` is the level that would
262/// rather have the branch than the bytes, and every reason to want the do-while form here is a
263/// speed reason.
264const OZ: &[&str] = &[
265    "fold",
266    "simplify",
267    "narrow",
268    "simplify",
269    "thread",
270    "phiopt",
271    "prune",
272    "canon",
273    "simplify-cfg",
274    "discharge",
275    "dce",
276];
277
278/// The passes this level runs, before the command line adds to or removes from them.
279#[must_use]
280pub const fn for_level(level: OptLevel) -> &'static [&'static str] {
281    match level {
282        OptLevel::O0 => O0,
283        OptLevel::O1 => O1,
284        OptLevel::O2 => O2,
285        OptLevel::O3 => O3,
286        OptLevel::Os => OS,
287        OptLevel::Oz => OZ,
288    }
289}
290
291/// Which passes the IR is written out around.
292///
293/// Empty by default, which is the whole point: a dump is a debugging aid and writing files
294/// nobody asked for is not one.
295#[derive(Debug, Clone, Default, PartialEq, Eq)]
296pub struct Dumps {
297    /// Every pass, on both sides.
298    all: bool,
299    /// The passes to write out before.
300    before: Vec<String>,
301    /// The passes to write out after.
302    after: Vec<String>,
303}
304
305impl Dumps {
306    /// Adds one `-fdump-ir=` argument.
307    ///
308    /// # Errors
309    ///
310    /// When the argument is not `all`, `before-<pass>` or `after-<pass>`, or when it names a
311    /// pass this compiler does not have. A misspelled pass name that quietly dumped nothing
312    /// would look exactly like a pass that did not run.
313    pub fn add(&mut self, spec: &str) -> Result<(), String> {
314        if spec == "all" {
315            self.all = true;
316            return Ok(());
317        }
318        let (side, name) = match spec.split_once('-') {
319            Some(("before", name)) => (&mut self.before, name),
320            Some(("after", name)) => (&mut self.after, name),
321            _ => {
322                return Err(format!(
323                    "`{spec}` is not a dump this compiler makes, which are `all`, \
324                     `before-<pass>` and `after-<pass>`"
325                ));
326            }
327        };
328        if pass::find(name).is_none() {
329            return Err(format!("`{name}` is not a pass this compiler has, see --print-pipeline"));
330        }
331        side.push(name.to_owned());
332        Ok(())
333    }
334
335    /// Whether anything is dumped at all.
336    #[must_use]
337    pub fn is_empty(&self) -> bool {
338        !self.all && self.before.is_empty() && self.after.is_empty()
339    }
340
341    /// Whether the IR is written out before this pass runs.
342    #[must_use]
343    pub fn wants_before(&self, name: &str) -> bool {
344        self.all || self.before.iter().any(|it| it == name)
345    }
346
347    /// Whether the IR is written out after this pass runs.
348    #[must_use]
349    pub fn wants_after(&self, name: &str) -> bool {
350        self.all || self.after.iter().any(|it| it == name)
351    }
352}
353
354/// What the command line asked the optimizer for.
355#[derive(Debug, Clone, PartialEq, Eq)]
356pub struct Options {
357    /// Which pipeline to start from.
358    pub level: OptLevel,
359    /// The passes `-f<name>` added and `-fno-<name>` removed, in the order they were given, so
360    /// that the last mention of a pass is the one that decides.
361    pub toggles: Vec<(String, bool)>,
362    /// What `-fpass-fuel=<pass>=<n>` limited, by pass name.
363    pub fuel: HashMap<String, u32>,
364    /// What `-fpass-fuel-global=<n>` limited the whole pipeline to, across every pass.
365    ///
366    /// This is the outer search of the two in section 4.5 of
367    /// `spec/optimizer/04-pass-manager.md`. Halving this finds the pass, and halving
368    /// `-fpass-fuel` for that pass finds the rewrite inside it. Two searches of twenty
369    /// compilations each beat one search over a space nobody knows the shape of.
370    pub global_fuel: Option<u32>,
371    /// What `-fdisable-<pass>` and `-fenable-<pass>` said about which functions a pass runs on.
372    pub gates: Gates,
373    /// What `-fdump-ir=` asked to see.
374    pub dumps: Dumps,
375    /// Whether the verifier runs after every pass that changed anything.
376    pub verify: bool,
377}
378
379impl Default for Options {
380    /// The default level with nothing added to it, and the verifier on in a debug build, which
381    /// is what section 9.10 asks for.
382    fn default() -> Self {
383        Self {
384            level: OptLevel::default(),
385            toggles: Vec::new(),
386            fuel: HashMap::new(),
387            global_fuel: None,
388            gates: Gates::default(),
389            dumps: Dumps::default(),
390            verify: cfg!(debug_assertions),
391        }
392    }
393}
394
395impl Options {
396    /// The options a level asks for on its own.
397    #[must_use]
398    pub fn for_level(level: OptLevel) -> Self {
399        Self { level, ..Self::default() }
400    }
401
402    /// The passes the level and the `-f` flags chose, in order, before the gates are consulted.
403    ///
404    /// A pass named by `-f<name>` that the level did not choose is appended, because the only
405    /// place it could go that does not need an ordering rule nobody wrote down is the end.
406    #[must_use]
407    pub fn chosen(&self) -> Vec<&'static str> {
408        let mut names: Vec<&str> = for_level(self.level).to_vec();
409        for (name, on) in &self.toggles {
410            let name = name.as_str();
411            match *on {
412                true if !names.contains(&name) => names.push(name),
413                true => {}
414                false => names.retain(|it| *it != name),
415            }
416        }
417        names.into_iter().filter_map(pass::find).map(Pass::name).collect()
418    }
419
420    /// The passes that will run, in order, over at least one function.
421    ///
422    /// A pass `-fenable-<name>` reached that the level did not choose is appended after them,
423    /// for the same reason and in the same place. It runs only over the functions the gate names,
424    /// which is the whole point of the flag: a pass being in this list is not the same question as
425    /// a pass running on the function somebody is looking at.
426    #[must_use]
427    pub fn passes(&self) -> Vec<&'static dyn Pass> {
428        let mut names = self.chosen();
429        for name in self.gates.enabled() {
430            // Through the pass list rather than straight from the gate, because the name the
431            // pass holds outlives this call and the one the gate holds does not.
432            let Some(found) = pass::find(name) else { continue };
433            if !names.contains(&found.name()) {
434                names.push(found.name());
435            }
436        }
437        names.into_iter().filter_map(pass::find).collect()
438    }
439}
440
441/// One written out copy of the IR.
442#[derive(Debug, Clone, PartialEq, Eq)]
443pub struct Dump {
444    /// What to call it, which is a number, a side and a pass name, as in `01-after-fold`. The
445    /// number is there so that a directory listing is in the order the passes ran.
446    pub name: String,
447    /// The module, in the textual form from `spec/08-ir.md`.
448    pub text: String,
449}
450
451/// What one pass had to say about one function.
452///
453/// One of these per pass per function with a body, whether or not the pass said anything, because
454/// a pass that reports nothing being visible as a pass that reports nothing is the point of the
455/// record. Section 42.2 of `spec/optimizer/42-measurement.md` has the argument.
456#[derive(Debug, Clone, PartialEq, Eq)]
457pub struct Remark {
458    /// Which pass, by the name a `-f` flag spells.
459    pub pass: &'static str,
460    /// Which function, by the name in the source.
461    pub func: Symbol,
462    /// What it said.
463    pub stats: Stats,
464}
465
466/// What running the pipeline produced beyond the changed module.
467#[derive(Debug, Clone, Default, PartialEq, Eq)]
468pub struct Report {
469    /// The dumps asked for, in the order they were taken. The manager does not write files,
470    /// because nothing below the driver in `spec/18-package-layout.md` knows what a file is.
471    pub dumps: Vec<Dump>,
472    /// A pass that left the IR in a state the verifier refuses, named, with what it said.
473    pub broke: Vec<String>,
474    /// How much fuel each pass spent, which is the number a bisection halves.
475    pub spent: Vec<(&'static str, u32)>,
476    /// What every pass said about every function, in the order the passes ran and then in the
477    /// order the module holds its functions. This is what `-fopt-info` prints.
478    pub remarks: Vec<Remark>,
479}
480
481impl Report {
482    /// Everything one pass said across the whole module, added up.
483    ///
484    /// The counts of an event are addable across functions because an event names a site in a
485    /// pass rather than a fact about a program, which is the reason [`crate::stats::Event::what`]
486    /// is a fixed string.
487    #[must_use]
488    pub fn totals(&self, pass: &str) -> Stats {
489        let mut total = Stats::new();
490        for remark in self.remarks.iter().filter(|it| it.pass == pass) {
491            total.merge(&remark.stats);
492        }
493        total
494    }
495}
496
497/// Runs the pipeline over the module.
498///
499/// Every pass sees every function with a body, one at a time, and a pass runs over the whole
500/// module before the next one starts. That order is what makes the dumps readable: a dump is
501/// the state of the program between two passes rather than between two functions.
502pub fn run(module: &mut Module, names: &Interner, opts: &Options) -> Report {
503    let mut report = Report::default();
504    let chosen = opts.chosen();
505    // One cache per function, kept across passes because a pass runs over the whole module
506    // before the next one starts. A cache that lived only as long as one function would be
507    // thrown away between every pass and would never answer a second question. Section 4.2 of
508    // `spec/optimizer/04-pass-manager.md` is the plan for turning the loop inside out, and the
509    // day that happens this map becomes a local in the inner loop.
510    let mut cached: HashMap<FuncId, Analyses> = HashMap::new();
511    // What the whole pipeline has left, which every pass draws its own allowance out of and
512    // gives the unspent part of back. A pass past the end of it is given nothing rather than
513    // skipped, so it still runs, still reports, and still transforms nothing.
514    let mut budget = opts.global_fuel;
515    // What each pass has left of what `-fpass-fuel` gave it. One allowance across every place
516    // the list names that pass, rather than one allowance each, because the number in the flag
517    // is meant to be the number of rewrites that happened. A peephole that runs twice under
518    // `-fpass-fuel=simplify=5` and rewrites ten things would make the bisection in section 4.5
519    // of `spec/optimizer/04-pass-manager.md` step over the rewrite it was looking for.
520    let mut allowance = opts.fuel.clone();
521    let passes = opts.passes();
522    // Before anything runs, because it is a fact about the module and every pass after this sees
523    // one function. Only when a pass in this run reads it: a flag nothing looks at would show up
524    // in every `-O0` dump and mean nothing to anybody reading one.
525    if passes.iter().any(|pass| READS_SUMMARIES.contains(&pass.name())) {
526        nofree::annotate(module, names);
527    }
528    for (index, pass) in passes.into_iter().enumerate() {
529        let name = pass.name();
530        if opts.dumps.wants_before(name) {
531            report.dumps.push(dump(index, "before", name, module, names));
532        }
533        let mut fuel = match (allowance.get(name).copied(), budget) {
534            // Whichever limit is tighter, because two limits that disagree mean the one that
535            // stops first, and a bisection that started with the global one has to stay inside
536            // it while the per pass one is halved.
537            (Some(count), Some(left)) => Fuel::of(count.min(left)),
538            (Some(count), None) => Fuel::of(count),
539            (None, Some(left)) => Fuel::of(left),
540            (None, None) => Fuel::unlimited(),
541        };
542        // What the level and the `-f` flags decided, which is what a gate overrides for the
543        // functions it names and leaves alone for the ones it does not.
544        let default = chosen.contains(&name);
545        for id in module.funcs() {
546            if module[id].is_declaration() {
547                continue;
548            }
549            if !opts.gates.allows(name, default, id.raw(), names.resolve(module[id].name)) {
550                // No remark either. A pass that did not run on a function has nothing to say
551                // about it, and a record saying it found nothing would read as a pass that
552                // looked.
553                continue;
554            }
555            let an = cached.entry(id).or_default();
556            let stats = pass.run(&mut module[id], an, &mut fuel);
557            // A pass that changed nothing preserved everything, whatever it says about itself,
558            // so the cheap case does not need every pass to have a second opinion about it.
559            // A pass that did change something is taken at its word, and in a checked build the
560            // word is checked.
561            let keeps = if stats.changed() { pass.preserves() } else { Preserved::ALL };
562            for broken in an.settle(&module[id], keeps, opts.verify) {
563                let func = names.resolve(module[id].name);
564                report.broke.push(format!(
565                    "the {name} pass said it preserved {} of {func} and did not",
566                    broken.name()
567                ));
568            }
569            // Here rather than after the pass, and this function rather than the module. A pass
570            // is a function pass, so the only thing it can have broken is the function it was
571            // given, and walking the other ones again after every one of them is the quadratic
572            // walk `rucc_ir::verify_func` exists to avoid. Doing it here is also what lets the
573            // message name the function, which the module walk could not, and it puts the
574            // failure next to the pass that caused it rather than at the end of the module.
575            if stats.changed() && opts.verify {
576                if let Err(errors) = rucc_ir::verify_func(module, &module[id], names) {
577                    let func = names.resolve(module[id].name);
578                    for error in errors {
579                        report
580                            .broke
581                            .push(format!("the {name} pass left invalid IR in {func}, {error}"));
582                    }
583                }
584            }
585            // The record is the only place the manager learns that anything happened, which is
586            // why the pass cannot leave recording until later. See `crate::stats`.
587            report.remarks.push(Remark { pass: name, func: module[id].name, stats });
588        }
589        // Added to rather than pushed, so a pass the list names twice is one line here with what
590        // both of its runs spent. That is the number a bisection halves, and two lines under one
591        // name would be two numbers where the flag takes one.
592        match report.spent.iter_mut().find(|(it, _)| *it == name) {
593            Some((_, total)) => *total += fuel.spent(),
594            None => report.spent.push((name, fuel.spent())),
595        }
596        if let Some(left) = &mut budget {
597            // Never below zero, because the allowance the pass was given was at most this.
598            *left -= fuel.spent();
599        }
600        if let Some(left) = allowance.get_mut(name) {
601            // Same, and for the same reason.
602            *left -= fuel.spent();
603        }
604        if opts.dumps.wants_after(name) {
605            report.dumps.push(dump(index, "after", name, module, names));
606        }
607    }
608    report
609}
610
611/// The module written out, under a name that sorts in the order the passes ran.
612fn dump(index: usize, side: &str, name: &str, module: &Module, names: &Interner) -> Dump {
613    Dump { name: format!("{index:02}-{side}-{name}"), text: rucc_ir::print(module, names) }
614}
615
616/// Renders what `--print-pipeline` prints.
617///
618/// One line per pass, numbered from one, with what the pass does after it. A level that runs
619/// nothing says so rather than printing an empty list, because an empty answer and a broken
620/// command look the same.
621#[must_use]
622pub fn print(opts: &Options) -> String {
623    let mut out = String::new();
624    let _ = writeln!(out, "level: {}", opts.level);
625    // Only when it was asked for, so the listing of a compilation nobody is bisecting is the
626    // same listing it has always been. A run under a budget is a run whose output is not the
627    // one the level asked for, and the listing is where that has to be visible.
628    if let Some(count) = opts.global_fuel {
629        let _ = writeln!(out, "global fuel: {count}");
630    }
631    let passes = opts.passes();
632    if passes.is_empty() {
633        let _ = writeln!(out, "no passes");
634        return out;
635    }
636    for (index, pass) in passes.iter().enumerate() {
637        let _ = write!(out, "{}: {}, {}", index + 1, pass.name(), pass.describe());
638        // Only when a gate mentions the pass, so the listing of a compilation nobody is
639        // debugging is the same listing it has always been.
640        if let Some(note) = opts.gates.note(pass.name()) {
641            let _ = write!(out, " [{note}]");
642        }
643        out.push('\n');
644    }
645    out
646}
647
648#[cfg(test)]
649mod tests {
650    use rucc_base::Interner;
651    use rucc_ir::{Builder, Flags, Func, Module, Opcode, Signature, Type};
652    use rucc_session::OptLevel;
653    use rucc_target::{Arch, Env, Os, TargetInfo, Triple};
654
655    use super::{Dumps, Options, for_level};
656    use crate::stats::Kind;
657    use crate::{Pass, pass};
658
659    /// A module with one function whose body has something to fold in it.
660    fn module() -> (Interner, Module) {
661        let mut names = Interner::new();
662        let target = TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu));
663        let mut module = Module::new(names.intern("test.c"), &target);
664        let func = foldable(&mut names, "f");
665        module.add_func(func);
666        (names, module)
667    }
668
669    /// A module with two of them, called `f` and `g`, in that order, so `f` is function 0.
670    fn two_functions() -> (Interner, Module) {
671        let mut names = Interner::new();
672        let target = TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu));
673        let mut module = Module::new(names.intern("test.c"), &target);
674        for name in ["f", "g"] {
675            let func = foldable(&mut names, name);
676            module.add_func(func);
677        }
678        (names, module)
679    }
680
681    /// A module with one function holding two identities the peephole takes, on a value that
682    /// arrives as a parameter so that folding cannot get to them first.
683    fn identities() -> (Interner, Module) {
684        let mut names = Interner::new();
685        let target = TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu));
686        let mut module = Module::new(names.intern("test.c"), &target);
687        let i32_ = Type::int(32);
688        let mut func = Func::new(
689            names.intern("h"),
690            Signature::new().with_params(&[i32_]).with_returns(&[i32_]),
691        );
692        let entry = func.create_block();
693        let x = func.append_param(entry, i32_);
694        let mut build = Builder::new(&mut func, entry);
695        let zero = build.iconst(i32_, 0);
696        let one = build.iconst(i32_, 1);
697        let sum = build.binary(Opcode::Add, x, zero, Flags::NONE);
698        let product = build.binary(Opcode::Mul, sum, one, Flags::NONE);
699        build.ret(&[product]);
700        module.add_func(func);
701        (names, module)
702    }
703
704    /// A function that returns a sign extension of a constant, which folding rewrites.
705    fn foldable(names: &mut Interner, name: &str) -> Func {
706        let mut func =
707            Func::new(names.intern(name), Signature::new().with_returns(&[Type::int(64)]));
708        let block = func.create_block();
709        let mut build = Builder::new(&mut func, block);
710        let narrow = build.iconst(Type::int(32), 7);
711        let wide = build.unary(Opcode::SExt, narrow, Type::int(64));
712        build.ret(&[wide]);
713        func
714    }
715
716    /// Whether the pass said anything about the function, which it only does when it ran on it.
717    fn spoke_about(report: &super::Report, pass: &str, func: &str, names: &Interner) -> bool {
718        report.remarks.iter().any(|it| it.pass == pass && names.resolve(it.func) == func)
719    }
720
721    #[test]
722    fn every_pass_a_pipeline_names_is_a_pass_that_exists() {
723        for level in
724            [OptLevel::O0, OptLevel::O1, OptLevel::O2, OptLevel::O3, OptLevel::Os, OptLevel::Oz]
725        {
726            for name in for_level(level) {
727                assert!(
728                    pass::find(name).is_some(),
729                    "{level} names `{name}` and no pass answers to it"
730                );
731            }
732        }
733    }
734
735    #[test]
736    fn a_pass_a_pipeline_names_twice_is_never_named_twice_in_a_row() {
737        // Running a pass again after another pass has been through is the point of naming it
738        // twice, and `simplify` around `narrow` is why the rule that used to be here, which was
739        // that no level names a pass twice at all, is not the rule any more. Two runs with
740        // nothing between them is still a mistake: the second one sees exactly what the first
741        // one finished with, so it can only report that it found nothing.
742        for level in
743            [OptLevel::O0, OptLevel::O1, OptLevel::O2, OptLevel::O3, OptLevel::Os, OptLevel::Oz]
744        {
745            for pair in for_level(level).windows(2) {
746                assert_ne!(pair[0], pair[1], "{level} runs `{}` twice in a row", pair[0]);
747            }
748        }
749    }
750
751    #[test]
752    fn a_pass_the_pipeline_runs_twice_gets_one_allowance_and_reports_one_number() {
753        // `-fpass-fuel=<pass>=<n>` is halved to find one rewrite, so the number in the flag has
754        // to be the number of rewrites that happened however many times the list names the pass.
755        // The peephole is named twice from `-O1` up and the function below holds two identities
756        // it takes, so a cap of one has to stop after one rather than after one per occurrence.
757        assert_eq!(for_level(OptLevel::O2).iter().filter(|it| **it == "simplify").count(), 2);
758
759        let (names, mut module) = identities();
760        let free = super::run(&mut module, &names, &Options::for_level(OptLevel::O2));
761        assert_eq!(spent(&free, "simplify"), Some(2), "{:?}", free.spent);
762
763        let (names, mut module) = identities();
764        let mut opts = Options::for_level(OptLevel::O2);
765        opts.fuel.insert("simplify".to_owned(), 1);
766        let capped = super::run(&mut module, &names, &opts);
767        assert_eq!(capped.spent.iter().filter(|(name, _)| *name == "simplify").count(), 1);
768        assert_eq!(spent(&capped, "simplify"), Some(1), "{:?}", capped.spent);
769    }
770
771    #[test]
772    fn an_identity_only_the_narrow_pass_can_produce_is_still_taken() {
773        // Issue 505, and the reason the peephole is named on both sides of `narrow`. C promotes
774        // before it operates, so `unsigned char x; (unsigned char)(x & 255)` arrives here as a
775        // thirty two bit `and` of a zero extension, and the rule that says `and` with every bit
776        // set is the value has nothing at eight bits to match. `narrow` is the only producer that
777        // width has. Before this ran twice the `and.i8` below reached the back end untouched.
778        let mut names = Interner::new();
779        let target = TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu));
780        let mut module = Module::new(names.intern("test.c"), &target);
781        let (i8_, i32_) = (Type::int(8), Type::int(32));
782        let mut func =
783            Func::new(names.intern("f"), Signature::new().with_params(&[i8_]).with_returns(&[i8_]));
784        let entry = func.create_block();
785        let x = func.append_param(entry, i8_);
786        let mut build = Builder::new(&mut func, entry);
787        let wide = build.unary(Opcode::ZExt, x, i32_);
788        let mask = build.iconst(i32_, 255);
789        let kept = build.binary(Opcode::And, wide, mask, Flags::NONE);
790        let back = build.unary(Opcode::Trunc, kept, i8_);
791        build.ret(&[back]);
792        module.add_func(func);
793
794        let report = super::run(&mut module, &names, &Options::for_level(OptLevel::O2));
795        assert!(report.broke.is_empty(), "{:?}", report.broke);
796        let text = rucc_ir::print(&module, &names);
797        assert!(!text.contains("and."), "the masking survived the pipeline\n{text}");
798    }
799
800    /// What a pass spent, or `None` if it did not run.
801    fn spent(report: &super::Report, pass: &str) -> Option<u32> {
802        report.spent.iter().find(|(name, _)| *name == pass).map(|&(_, count)| count)
803    }
804
805    /// The names of the passes a set of options would run, in order.
806    fn names(opts: &Options) -> Vec<&'static str> {
807        opts.passes().into_iter().map(Pass::name).collect()
808    }
809
810    #[test]
811    fn the_level_that_optimizes_nothing_still_removes_what_nothing_reaches() {
812        // One pass at `-O0`, and it is the one that is not an optimization. See the comment on
813        // the level itself, and issue 359.
814        assert_eq!(names(&Options::for_level(OptLevel::O0)), ["simplify-cfg"]);
815        assert!(names(&Options::for_level(OptLevel::O2)).len() > 1);
816    }
817
818    #[test]
819    fn a_pass_is_removed_by_no_and_added_by_the_bare_name_and_the_last_word_wins() {
820        let mut opts = Options::for_level(OptLevel::O2);
821        opts.toggles.push(("fold".to_owned(), false));
822        assert!(!names(&opts).contains(&"fold"), "{:?}", names(&opts));
823        opts.toggles.push(("fold".to_owned(), true));
824        assert!(names(&opts).contains(&"fold"), "{:?}", names(&opts));
825
826        let mut off = Options::for_level(OptLevel::O0);
827        off.toggles.push(("fold".to_owned(), true));
828        assert_eq!(
829            names(&off),
830            ["simplify-cfg", "fold"],
831            "a pass the level did not choose is still reachable"
832        );
833    }
834
835    #[test]
836    fn asking_for_a_pass_twice_does_not_run_it_twice() {
837        let mut opts = Options::for_level(OptLevel::O2);
838        let before = names(&opts);
839        opts.toggles.push(("fold".to_owned(), true));
840        assert_eq!(names(&opts), before);
841    }
842
843    #[test]
844    fn the_pipeline_listing_names_the_level_and_every_pass_in_order() {
845        let text = super::print(&Options::for_level(OptLevel::O2));
846        assert!(text.starts_with("level: -O2\n"), "{text}");
847        assert!(text.contains("1: fold, "), "{text}");
848        let mut none = Options::for_level(OptLevel::O0);
849        none.toggles.push(("simplify-cfg".to_owned(), false));
850        let none = super::print(&none);
851        assert!(none.contains("no passes"), "{none}");
852    }
853
854    #[test]
855    fn running_the_pipeline_changes_the_module_and_reports_what_it_spent() {
856        let (names, mut module) = module();
857        let report = super::run(&mut module, &names, &Options::for_level(OptLevel::O2));
858        // Folding rewrites the sign extension into a constant, and then the constant it was
859        // extending is read by nothing and dead code elimination takes it out. One
860        // transformation each, which is what the two of them together are for. Asserted by
861        // name rather than as the whole vector, so a pass added later does not fail this.
862        assert_eq!(spent(&report, "fold"), Some(1));
863        assert_eq!(spent(&report, "dce"), Some(1));
864        assert!(report.broke.is_empty(), "{:?}", report.broke);
865        assert!(report.dumps.is_empty(), "nothing asked for a dump");
866        assert!(rucc_ir::print(&module, &names).contains("iconst.i64 7"));
867    }
868
869    #[test]
870    fn the_analyses_survive_a_pass_that_keeps_them_and_not_one_that_does_not() {
871        // The pipeline half of the analysis manager. A branch on a constant, so `simplify-cfg`
872        // has something to do and says it preserved nothing, and the whole run comes out with
873        // the verifier and the manager both satisfied. What a pass that lied would produce is in
874        // `crate::analysis`, where a lie can be told on purpose.
875        let mut names = Interner::new();
876        let target = TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu));
877        let mut module = Module::new(names.intern("test.c"), &target);
878        let mut func = Func::new(names.intern("f"), Signature::new());
879        let entry = func.create_block();
880        let dead = func.create_block();
881        let exit = func.create_block();
882        let mut build = Builder::new(&mut func, entry);
883        let never = build.iconst(Type::int(1), 0);
884        build.br_if(never, dead, &[], exit, &[]);
885        for block in [dead, exit] {
886            let mut build = Builder::new(&mut func, block);
887            build.ret(&[]);
888        }
889        module.add_func(func);
890        let report = super::run(&mut module, &names, &Options::for_level(OptLevel::O2));
891        // The fold, and then the merge of the arm it left with one way into it.
892        assert_eq!(spent(&report, "simplify-cfg"), Some(2));
893        assert!(report.broke.is_empty(), "{:?}", report.broke);
894        let text = rucc_ir::print(&module, &names);
895        // The labels, which start a line, and not the mentions of one, which are indented. One
896        // left: the arm nothing reaches went, and the arm that is always taken came up into the
897        // entry, which is what is left of the branch.
898        assert_eq!(text.matches("\nblock").count(), 1, "there is more than one block:\n{text}");
899    }
900
901    #[test]
902    fn no_pass_that_optimizes_runs_at_no_optimization_however_much_there_is_to_do() {
903        let (names, mut module) = module();
904        let before = rucc_ir::print(&module, &names);
905        let report = super::run(&mut module, &names, &Options::for_level(OptLevel::O0));
906        // The one pass the level runs looked, found no branch it could read and no block nothing
907        // reaches, and spent nothing. The constant arithmetic the fixture is full of is still
908        // there, which is the part of `-O0` that has not changed.
909        assert_eq!(report.spent, vec![("simplify-cfg", 0)]);
910        assert_eq!(rucc_ir::print(&module, &names), before);
911    }
912
913    #[test]
914    fn a_gate_takes_a_pass_away_from_one_function_and_leaves_the_other_alone() {
915        let (names, mut module) = two_functions();
916        let mut opts = Options::for_level(OptLevel::O2);
917        opts.gates.add(false, "fold=g").expect("g is a function and fold is a pass");
918        let report = super::run(&mut module, &names, &opts);
919        assert!(spoke_about(&report, "fold", "f", &names));
920        assert!(!spoke_about(&report, "fold", "g", &names), "fold ran where it was gated off");
921        assert!(spoke_about(&report, "dce", "g", &names), "one pass gated off is not all of them");
922        // What the gate is for: the two functions came out different, and the difference is one
923        // pass on one function rather than a level on a file.
924        let text = rucc_ir::print(&module, &names);
925        assert_eq!(text.matches("sext.i64").count(), 1, "{text}");
926    }
927
928    #[test]
929    fn a_function_can_be_gated_by_the_number_it_has_in_the_module() {
930        let (names, mut module) = two_functions();
931        let mut opts = Options::for_level(OptLevel::O2);
932        opts.gates.add(false, "fold=0").expect("0 is a function and fold is a pass");
933        let report = super::run(&mut module, &names, &opts);
934        assert!(!spoke_about(&report, "fold", "f", &names), "function 0 is the first one");
935        assert!(spoke_about(&report, "fold", "g", &names));
936    }
937
938    #[test]
939    fn enabling_a_pass_reaches_one_function_at_a_level_that_did_not_ask_for_it() {
940        let (names, mut module) = two_functions();
941        let mut opts = Options::for_level(OptLevel::O0);
942        opts.gates.add(true, "fold=1").expect("1 is a function and fold is a pass");
943        let running: Vec<&str> = opts.passes().into_iter().map(Pass::name).collect();
944        assert_eq!(
945            running,
946            ["simplify-cfg", "fold"],
947            "the flag has to put the pass in the pipeline"
948        );
949        let report = super::run(&mut module, &names, &opts);
950        assert!(!spoke_about(&report, "fold", "f", &names), "nothing asked for f");
951        assert!(spoke_about(&report, "fold", "g", &names));
952        let text = rucc_ir::print(&module, &names);
953        assert_eq!(text.matches("sext.i64").count(), 1, "{text}");
954    }
955
956    #[test]
957    fn a_pass_gated_off_everywhere_runs_on_nothing_and_still_says_so() {
958        let (names, mut module) = two_functions();
959        let before = rucc_ir::print(&module, &names);
960        let mut opts = Options::for_level(OptLevel::O2);
961        for pass in pass::PASSES {
962            opts.gates.add(false, pass.name()).expect("a pass in the list is a pass that exists");
963        }
964        let report = super::run(&mut module, &names, &opts);
965        assert!(report.remarks.is_empty(), "a pass that did not run has nothing to report");
966        assert_eq!(spent(&report, "fold"), Some(0), "the pass is still in the pipeline");
967        assert_eq!(rucc_ir::print(&module, &names), before);
968    }
969
970    #[test]
971    fn the_pipeline_listing_says_which_passes_a_gate_touched() {
972        let mut opts = Options::for_level(OptLevel::O2);
973        opts.gates.add(false, "fold=2-4").expect("fold is a pass");
974        let text = super::print(&opts);
975        assert!(text.contains("1: fold, "), "{text}");
976        assert!(text.contains("[off for 2-4]"), "{text}");
977        assert_eq!(text.matches('[').count(), 1, "a pass no gate mentions says nothing extra");
978    }
979
980    #[test]
981    fn every_pass_at_no_fuel_leaves_the_module_exactly_as_it_found_it() {
982        // The check section 9.10 asks for by name, and the reason it is here rather than in each
983        // pass is that it has to hold for every pass that is ever added.
984        for pass in pass::PASSES {
985            let (names, mut module) = module();
986            let before = rucc_ir::print(&module, &names);
987            let mut opts = Options::for_level(OptLevel::O0);
988            // The level's own pass out of the way first, so that what this measures is the one
989            // pass under test. A pass turned off and then on again is on, so this is right for
990            // that pass as well as for the others.
991            opts.toggles.push(("simplify-cfg".to_owned(), false));
992            opts.toggles.push((pass.name().to_owned(), true));
993            opts.fuel.insert(pass.name().to_owned(), 0);
994            let report = super::run(&mut module, &names, &opts);
995            assert_eq!(
996                report.spent,
997                vec![(pass.name(), 0)],
998                "{} spent fuel it had none of",
999                pass.name()
1000            );
1001            assert_eq!(
1002                rucc_ir::print(&module, &names),
1003                before,
1004                "{} transformed the module at fuel zero",
1005                pass.name()
1006            );
1007        }
1008    }
1009
1010    #[test]
1011    fn fuel_is_shared_across_the_functions_of_a_module() {
1012        let mut names = Interner::new();
1013        let target = TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu));
1014        let mut module = Module::new(names.intern("test.c"), &target);
1015        for which in ["f", "g"] {
1016            let mut func =
1017                Func::new(names.intern(which), Signature::new().with_returns(&[Type::int(64)]));
1018            let block = func.create_block();
1019            let mut build = Builder::new(&mut func, block);
1020            let narrow = build.iconst(Type::int(32), 7);
1021            let wide = build.unary(Opcode::SExt, narrow, Type::int(64));
1022            build.ret(&[wide]);
1023            module.add_func(func);
1024        }
1025        let mut opts = Options::for_level(OptLevel::O2);
1026        opts.fuel.insert("fold".to_owned(), 1);
1027        let report = super::run(&mut module, &names, &opts);
1028        // One fold across both functions, because fuel is per pass and per compilation. Dead
1029        // code elimination has its own and spends it on the constant the one fold orphaned.
1030        assert_eq!(spent(&report, "fold"), Some(1));
1031        assert_eq!(spent(&report, "dce"), Some(1));
1032        let text = rucc_ir::print(&module, &names);
1033        assert_eq!(text.matches("sext.i64").count(), 1, "{text}");
1034    }
1035
1036    #[test]
1037    fn global_fuel_is_spent_by_the_passes_in_order_and_the_rest_get_none() {
1038        let (names, mut module) = module();
1039        let mut opts = Options::for_level(OptLevel::O2);
1040        opts.global_fuel = Some(1);
1041        let report = super::run(&mut module, &names, &opts);
1042        // Folding is first and there is one thing to fold, so it takes the one unit and dead
1043        // code elimination gets nothing. Without the budget it would have taken the constant
1044        // that fold orphaned, which is what the other test measures.
1045        assert_eq!(spent(&report, "fold"), Some(1));
1046        assert_eq!(spent(&report, "dce"), Some(0));
1047        let text = rucc_ir::print(&module, &names);
1048        assert!(text.contains("iconst.i64 7"), "{text}");
1049        assert!(text.contains("iconst.i32 7"), "the orphaned constant is still there, {text}");
1050    }
1051
1052    #[test]
1053    fn a_budget_of_nothing_leaves_the_module_alone_and_still_runs_every_pass() {
1054        let (names, mut module) = module();
1055        let before = rucc_ir::print(&module, &names);
1056        let mut opts = Options::for_level(OptLevel::O2);
1057        opts.global_fuel = Some(0);
1058        let report = super::run(&mut module, &names, &opts);
1059        assert_eq!(rucc_ir::print(&module, &names), before);
1060        assert!(report.spent.iter().all(|(_, spent)| *spent == 0), "{:?}", report.spent);
1061        // Every pass, because a pass out of fuel is a pass that ran and did nothing rather than
1062        // a pass that was skipped, and a bisection that skipped passes would be searching a
1063        // different pipeline at every step. One line per name rather than one per place the list
1064        // names it, because what a name was given is one allowance across all of them.
1065        let mut want: Vec<&str> = opts.passes().into_iter().map(Pass::name).collect();
1066        want.sort_unstable();
1067        want.dedup();
1068        let mut got: Vec<&str> = report.spent.iter().map(|&(name, _)| name).collect();
1069        got.sort_unstable();
1070        assert_eq!(got, want);
1071    }
1072
1073    #[test]
1074    fn the_tighter_of_the_two_limits_is_the_one_that_stops_the_pass() {
1075        // A pass allowed more than the budget gets the budget.
1076        let (names, mut under) = module();
1077        let mut opts = Options::for_level(OptLevel::O2);
1078        opts.global_fuel = Some(0);
1079        opts.fuel.insert("fold".to_owned(), 9);
1080        assert_eq!(spent(&super::run(&mut under, &names, &opts), "fold"), Some(0));
1081
1082        // And a pass allowed less than the budget keeps its own limit, with the budget left
1083        // over for whatever comes after it.
1084        let (names, mut over) = module();
1085        let mut opts = Options::for_level(OptLevel::O2);
1086        opts.global_fuel = Some(9);
1087        opts.fuel.insert("fold".to_owned(), 0);
1088        let report = super::run(&mut over, &names, &opts);
1089        assert_eq!(spent(&report, "fold"), Some(0));
1090        assert_eq!(spent(&report, "dce"), Some(0), "nothing was orphaned for it to remove");
1091    }
1092
1093    #[test]
1094    fn the_pipeline_listing_says_when_there_is_a_budget_and_says_nothing_when_there_is_not() {
1095        let opts = Options::for_level(OptLevel::O2);
1096        assert!(!super::print(&opts).contains("global fuel"));
1097        let with = Options { global_fuel: Some(12), ..Options::for_level(OptLevel::O2) };
1098        assert!(super::print(&with).contains("global fuel: 12"), "{}", super::print(&with));
1099    }
1100
1101    #[test]
1102    fn a_dump_is_taken_on_the_side_that_asked_for_it_and_not_the_other() {
1103        let (names, mut module) = module();
1104        let mut opts = Options::for_level(OptLevel::O2);
1105        opts.dumps.add("after-fold").expect("a pass that exists");
1106        let report = super::run(&mut module, &names, &opts);
1107        assert_eq!(report.dumps.len(), 1);
1108        assert_eq!(report.dumps[0].name, "00-after-fold");
1109        assert!(report.dumps[0].text.contains("iconst.i64 7"));
1110    }
1111
1112    #[test]
1113    fn asking_for_all_dumps_gives_both_sides_of_every_pass() {
1114        let (interner, mut module) = module();
1115        let opts = {
1116            let mut opts = Options::for_level(OptLevel::O2);
1117            opts.dumps.add("all").expect("all is always a dump");
1118            opts
1119        };
1120        let report = super::run(&mut module, &interner, &opts);
1121        // Both sides of every pass in the level, numbered by position, whatever the level
1122        // holds. Written out of the pipeline rather than as a literal, because the point of
1123        // the test is the pairing and the numbering and not which passes exist this month.
1124        let taken: Vec<&str> = report.dumps.iter().map(|d| d.name.as_str()).collect();
1125        let expected: Vec<String> = names(&opts)
1126            .into_iter()
1127            .enumerate()
1128            .flat_map(|(at, name)| {
1129                [format!("{at:02}-before-{name}"), format!("{at:02}-after-{name}")]
1130            })
1131            .collect();
1132        assert_eq!(taken, expected);
1133        assert!(report.dumps[0].text.contains("sext.i64"));
1134        assert!(!report.dumps[1].text.contains("sext.i64"));
1135    }
1136
1137    #[test]
1138    fn every_pass_leaves_a_record_for_every_function_whether_or_not_it_had_anything_to_say() {
1139        let (names, mut module) = module();
1140        let opts = Options::for_level(OptLevel::O2);
1141        let report = super::run(&mut module, &names, &opts);
1142        let ran: Vec<&'static str> = opts.passes().into_iter().map(Pass::name).collect();
1143        // One function in the fixture, so one record per pass, and the passes in the order they
1144        // ran. A pass that found nothing is in here with an empty record, which is the point:
1145        // a pass that fires on nothing is either dead code or a bug, and output that leaves it
1146        // out cannot say which.
1147        let seen: Vec<&'static str> = report.remarks.iter().map(|it| it.pass).collect();
1148        assert_eq!(seen, ran);
1149        assert!(report.remarks.iter().all(|it| names.resolve(it.func) == "f"));
1150        assert!(
1151            report.remarks.iter().any(|it| it.pass == "simplify" && it.stats.is_empty()),
1152            "there is nothing in the fixture for the peephole to do"
1153        );
1154    }
1155
1156    #[test]
1157    fn a_pass_spends_one_unit_of_fuel_for_each_rewrite_it_reports() {
1158        // The invariant that keeps the record honest, checked over every pass rather than
1159        // written into each one. Fuel is taken immediately before a transformation and a
1160        // rewrite is recorded immediately after it, so the two counts are the same number
1161        // arrived at from two directions. A pass where they disagree either transformed without
1162        // asking, which breaks bisection, or rewrote without recording, which means the manager
1163        // did not run the verifier over what it produced.
1164        let (names, mut module) = module();
1165        let report = super::run(&mut module, &names, &Options::for_level(OptLevel::O2));
1166        for (pass, spent) in &report.spent {
1167            assert_eq!(
1168                report.totals(pass).total(Kind::Optimized),
1169                *spent,
1170                "{pass} spent {spent} units of fuel and did not say on what"
1171            );
1172        }
1173        assert!(report.spent.iter().any(|(_, spent)| *spent > 0), "nothing happened at all");
1174    }
1175
1176    #[test]
1177    fn what_the_passes_said_is_what_opt_info_prints() {
1178        let (names, mut module) = module();
1179        let report = super::run(&mut module, &names, &Options::for_level(OptLevel::O2));
1180        let text = crate::optinfo::render("t.c", &report, &names, crate::Wants::all());
1181        assert!(
1182            text.contains("t.c: f: optimized: integer instruction folded to a constant (1) [fold]"),
1183            "{text}"
1184        );
1185        assert!(
1186            text.contains(
1187                "t.c: f: optimized: instruction with no effects and no users removed (1) [dce]"
1188            ),
1189            "{text}"
1190        );
1191        // Nothing in the fixture is a miss, so asking only for the misses gets nothing back,
1192        // and that is different from the flag having been left off.
1193        let mut misses = crate::Wants::none();
1194        misses.add("missed").expect("that kind exists");
1195        assert_eq!(crate::optinfo::render("t.c", &report, &names, misses), "");
1196    }
1197
1198    #[test]
1199    fn the_verifier_says_which_function_it_refused_and_leaves_the_others_out_of_it() {
1200        // Two functions with the same foldable body, and a block in the second one that nothing
1201        // reaches, which the verifier refuses. The pass is not what put it there, and the
1202        // complaint says the pass anyway, because a pass that hands back a function the
1203        // verifier will not take is where the search has to start whoever wrote the block.
1204        let mut names = Interner::new();
1205        let target = TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu));
1206        let mut module = Module::new(names.intern("test.c"), &target);
1207        module.add_func(foldable(&mut names, "f"));
1208        let mut g = foldable(&mut names, "g");
1209        let stranded = g.create_block();
1210        let mut build = Builder::new(&mut g, stranded);
1211        let seven = build.iconst(Type::int(64), 7);
1212        build.ret(&[seven]);
1213        module.add_func(g);
1214
1215        // Folding on its own, because simplify-CFG would take the stranded block out and there
1216        // would be nothing left to complain about.
1217        let mut opts = Options::for_level(OptLevel::O0);
1218        opts.toggles.push(("simplify-cfg".to_owned(), false));
1219        opts.toggles.push(("fold".to_owned(), true));
1220        opts.verify = true;
1221        let report = super::run(&mut module, &names, &opts);
1222
1223        assert_eq!(report.broke.len(), 1, "{:?}", report.broke);
1224        let complaint = &report.broke[0];
1225        assert!(complaint.starts_with("the fold pass left invalid IR in g,"), "{complaint}");
1226        assert!(complaint.contains("this block is not reachable"), "{complaint}");
1227    }
1228
1229    #[test]
1230    fn a_function_a_pass_did_not_change_is_not_verified_after_it() {
1231        // The stranded block is in `f` this time and `f` has nothing to fold, so the pass runs
1232        // over an invalid function, changes nothing, and says nothing. That is the whole trade:
1233        // the verifier answers for the rewrite that just happened, and a function no rewrite
1234        // touched was already answered for when it was built.
1235        let mut names = Interner::new();
1236        let target = TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu));
1237        let mut module = Module::new(names.intern("test.c"), &target);
1238        let mut f = Func::new(names.intern("f"), Signature::new().with_returns(&[Type::int(64)]));
1239        for _ in 0..2 {
1240            let block = f.create_block();
1241            let mut build = Builder::new(&mut f, block);
1242            let seven = build.iconst(Type::int(64), 7);
1243            build.ret(&[seven]);
1244        }
1245        module.add_func(f);
1246        module.add_func(foldable(&mut names, "g"));
1247
1248        let mut opts = Options::for_level(OptLevel::O0);
1249        opts.toggles.push(("simplify-cfg".to_owned(), false));
1250        opts.toggles.push(("fold".to_owned(), true));
1251        opts.verify = true;
1252        let report = super::run(&mut module, &names, &opts);
1253
1254        assert!(report.broke.is_empty(), "{:?}", report.broke);
1255        // And it did run on it, so this is the verifier staying quiet rather than the pass
1256        // being skipped.
1257        assert!(spoke_about(&report, "fold", "f", &names));
1258    }
1259
1260    #[test]
1261    fn a_dump_of_a_pass_that_does_not_exist_is_refused_rather_than_ignored() {
1262        let mut dumps = Dumps::default();
1263        assert!(dumps.add("after-no-such-pass").is_err());
1264        assert!(dumps.add("sideways-fold").is_err());
1265        assert!(dumps.add("fold").is_err());
1266        assert!(dumps.is_empty());
1267    }
1268}