Skip to main content

rucc_opt/
split.rs

1//! Splits a loop into a run of iterations that needs no checks and the rest of it, which keeps them.
2//!
3//! Design: `spec/safe-memory/07-check-elimination.md` section 7.4, which names this and says what it
4//! is for: "Loop splitting is the general form. The checked part and the unchecked part are divided
5//! at `min(n, extent / sizeof(T))`."
6//!
7//! [`crate::hoist`] is the pass next door and it answers a different question. It puts one check in
8//! front of a loop that covers every access the loop makes, which needs the loop to make every one
9//! of them: an exact count, one way out, and a check every iteration reaches. Most loops in real code
10//! are not like that. The census on tamnd/rucc#782 says that of the roughly fifteen hundred checks
11//! SQLite still carries at `-O2`, six hundred and ninety two are in loops with a second way out and
12//! sixty four are checks an iteration can finish without reaching. Neither is a loop hoisting can say
13//! anything about, and both are loops this one can, because it never has to claim the loop reaches
14//! the end of what it might read. It only has to know a prefix that is safe.
15//!
16//! # What the two halves are
17//!
18//! The loop is copied. The original becomes the fast half and loses its checks, the copy becomes the
19//! slow half and keeps them, and a new block in front of the original decides which one runs. That
20//! block carries an offset in bytes from the first access, walks it on by the step every time round,
21//! and hands over to the slow half once the offset passes a window worked out in the preheader.
22//!
23//! The offset is a new value rather than one of the loop's own pointers, and the test is against
24//! the window rather than against anything the loop compares. That is what makes this work on a loop
25//! with several ways out: the fast half keeps every exit the loop had, so leaving early still leaves
26//! early, and the extra test is only ever the reason the fast half stops early and never the reason
27//! it runs longer.
28//!
29//! A loop where no address moves gets neither the block nor the offset. Which half runs is settled
30//! by an answer that does not change while the loop runs, so the way into the loop is where the two
31//! halves are chosen between and there is nothing to carry. Half the loops this takes on SQLite are
32//! that shape.
33//!
34//! # Where the window comes from
35//!
36//! For a check whose address is `first + delta` reading `reach` bytes each time, every offset with
37//! `delta + reach <= extent` is one the check cannot fail on, where `extent` is how many bytes from
38//! `first` on belong to whatever owns `first`. So the window is `extent - reach`, and where a loop
39//! has several checks that walk by the same amount the window is the smallest of theirs.
40//!
41//! Bytes rather than iterations, and that is the whole of the arithmetic. An earlier version of this
42//! counted iterations against `(extent - reach) / step + 1`, which is the same transformation and a
43//! much harder claim: it has a symbolic multiply and a symbolic divide in it at sixty four bits, and
44//! z3 does not finish on it in two and a half minutes in any of three formulations, so the pass sat
45//! outside the rule table that `spec/safe-memory/07-check-elimination.md` section 7.7 asks every
46//! elimination to be inside. In bytes it is `swept.sym.i64`, which is already in that table and
47//! already proved, and the pass asks it rather than deciding. `limited` below is where that
48//! happens.
49//!
50//! The extent is the half of that a compiler cannot work out, so it is asked at run time, through the
51//! `cap_extent` query that tamnd/rucc#792 added. The query takes a limit on how far to look and the
52//! answer is never more than that limit and never more than the truth, so what this pass asks for is
53//! as much as the arithmetic carries. That used to be a trip count times a step, on the grounds that
54//! what the query walked was work the loop was about to do anyway. tamnd/rucc#861 stopped it walking
55//! and tamnd/rucc#871 took the bound off: the query probes the far end of what it was asked for and
56//! halves, so the price does not turn on the number, and a limit smaller than the object is a smaller
57//! window and so fewer iterations in the half with no checks in it.
58//!
59//! An address that does not move is the same expression with a step of zero, and its offset is zero
60//! on every iteration, so there is nothing to carry and the window question collapses into whether
61//! the one access fits.
62//! Hoisting would rather have these, and it takes the ones in loops it is willing to touch. What is
63//! left over is the ones in loops it refused for one of its own reasons, a second way out or a call
64//! inside, and those come back here.
65//!
66//! # A walk that goes the other way
67//!
68//! A loop whose address goes down each time round is the same transformation looked at from the
69//! other end, and it is written here so that it is the same code. The offset the guard carries
70//! counts bytes moved from the first access rather than bytes added to it, so it still goes up by
71//! the step every time round and everything built on it is untouched: the guard block, the block
72//! parameter, the clamp and the test are the ones above, word for word.
73//!
74//! What changes is which end of the object the runtime is asked about. The window has to be room
75//! below the first access rather than above it, so the query is `cap_extent_back` and it is asked at
76//! `first + reach`, the end of the first access rather than its start. The answer is how many bytes
77//! ending there belong to whatever owns them, the window is that less the reach as before, and the
78//! access on iteration `delta` is the `reach` bytes ending at `first + reach - delta`. That is what
79//! `swept.down.sym.i64` in the rule table is written about, and it is asked instead of the ascending
80//! rule rather than derived from it.
81//!
82//! Anchoring at the end is what buys all of that. Anchoring at the lowest address the loop reaches
83//! would need a real trip count, since where the verified range starts would then depend on how far
84//! the loop goes, and this pass takes loops nobody counted. Not knowing is free for an ascending
85//! walk, where asking for too little only costs iterations in the slow half. It is unsound for a
86//! descending one, so the query goes the other way instead of the anchor.
87//!
88//! # A walk nobody could follow
89//!
90//! Everything above assumes the pass knows how far the address moves each time round. Most of what
91//! is left on real code is loops where it does not, and they are not exotic: a scanner that steps by
92//! one or by two depending on what it just read, a pointer that comes back round through a join
93//! because the body has a branch in it, a walk whose step is a width the caller passed in. None of
94//! those is an induction variable and scalar evolution has nothing to say about any of them, so they
95//! arrive here as an address that does something unknown.
96//!
97//! The way through is to stop asking how far the address moves and ask instead where it is. If the
98//! check's address is a fixed distance from a pointer the loop's header carries, then the guard can
99//! take where that pointer was on the way in from where it is now, and the difference is the
100//! displacement itself. It is exact rather than an upper bound on it, so the same window and the same
101//! rule apply word for word, and the guard tests it with the same unsigned comparison. It costs a
102//! subtract in the guard and saves the block parameter and the add at the latch, so it is not more
103//! code than counting.
104//!
105//! What has to be established is that the pointer is its own former self plus bytes, and the reason
106//! is money rather than soundness. The guard compares the difference against the window at run time,
107//! so `p = p->next` is safe to measure: a node that landed inside the first one's object passes the
108//! comparison and one that did not takes the slow half, and either way the answer is right. It is
109//! that a list never passes. The next node of a heap allocated list is its own object, so the guard
110//! fails on the second iteration and every one after it, and the split bought a second copy of the
111//! loop with every check still in both halves. Letting lists through on SQLite splits 73 more loops,
112//! puts 220 more calls to `check_bounds` in the object and adds 139 kilobytes, for 5 liveness checks.
113//! So the value the latch hands back has to reach the parameter through `ptr_add`s, block parameters
114//! inside the loop and `select`, and a load anywhere on the way is a refusal. `measured` is where
115//! that walk is, and it is syntactic because what it is buying is.
116//!
117//! A fixed distance from a pointer the header carries is not the only address the guard can find its
118//! way to, and on real code it is not even the commonest. The one above it is that pointer plus a
119//! variable, which is an address that is still a function of what the header carries and of what the
120//! loop was handed, and both the guard and the preheader hold every one of those. So the guard writes
121//! the arithmetic out again from its own parameters, the preheader writes it out again from the
122//! values it passes, and the subtraction between the two is the same subtraction. That is
123//! rematerialization rather than measurement, `writable` is where it is decided and `remade` is where
124//! it is written, and the fixed distance case is the instance of it that costs nothing to write.
125//!
126//! What may be written again is a list of opcodes rather than a question about effects, because two
127//! things have to hold and neither is what an effect flag answers. The copy has to compute the same
128//! number somewhere else, which is what rules out reading memory, and it has to be harmless in the
129//! preheader of a loop that turns out to run no iterations, which is what rules out a divide.
130//!
131//! # Why the fast half may drop a check
132//!
133//! `check_bounds` asks whether the bytes an access names lie inside one object. Every address in
134//! `[first, first + extent)` is inside the object that owns `first`, by what the query answers, and
135//! the window is exactly the offsets whose access stays inside that. So no check in the fast half
136//! could have failed.
137//!
138//! `check_live` asks whether anything owns the address right now, and the query answered that too,
139//! since a byte belonging to the owner of `first` is a byte with an owner. Right now is the catch,
140//! and it is why nothing that could free may be in the loop. A call in the body could free the object
141//! between the question and the iteration that reads it, and then the fast half would read freed
142//! storage with nothing to say so.
143//!
144//! That is a question about the callee rather than about calling, and [`crate::nofree`] answers it
145//! before the pipeline starts, so a call carrying [`rucc_ir::Flags::NOFREE`] is one the loop may
146//! keep. Hoisting refuses every call whatever it does, and the reason is not this one: it needs the
147//! loop to reach the end of what its count says, and a call that does not come back leaves it short.
148//! Splitting never claims the loop reaches the end, so a call that might not come back costs it
149//! nothing.
150//!
151//! `check_deriv` asks whether a pointer computed from another one stayed inside the capability the
152//! first one had, and that is the same containment written about a pointer rather than about the
153//! bytes under it. It is the narrower question of the two, since the window document 03 section 3.1
154//! allows a derivation runs a stride below the object and up to its end, and the fast half is only
155//! ever claiming the address is inside. So a loop whose bounds check the window covers has a
156//! derivation check the same window covers, and on the two benchmarks where an index walks a byte
157//! at a time that check was all the fast half had left in it.
158//!
159//! What it needs beyond a walk is that the extent was asked about the object the check names. The
160//! query goes to the first iteration's address, so an address a little way along from the pointer
161//! the check is about is a question about whatever owns that instead, which past the end of one
162//! object is the next object rather than nothing. Two shapes give the right object and `started` and
163//! `paired` are the two. Either the walk starts on the pointer the check names, or that pointer
164//! walks the loop alongside the new one, in which case the two are a fixed distance apart on every
165//! iteration and a window that wide holds the pair: the lower end being inside the object says the
166//! capability is that object and the upper end being inside it says the derivation stayed there.
167//!
168//! The second is the commoner by a long way, because `p = p + k` is what most pointer arithmetic in
169//! a loop is, and it is what `bench/safety/a-string-scan` does.
170//!
171//! Two answers of the query carry the weight and both are argued where the query is implemented. An
172//! address no watched region covers gets the whole limit back, so a loop over a local or a global
173//! splits into a fast half that runs the whole way, which is right because no check on such an
174//! address ever fires under this milestone. An address whose granule nobody owns gets zero, so the
175//! limit is zero, the fast half runs no iterations, and the check inside the slow half is what reports
176//! the dangling pointer, at the access rather than at the loop.
177//!
178//! # Which loops
179//!
180//! One latch, a preheader, nothing in it that could free, and no value defined inside it that
181//! anything outside reads. Not a count, unlike hoisting, and not even a step: the count was spent on
182//! how far to ask the runtime to look and nothing asks for less than everything any more, and the
183//! step was spent on the same thing. The last is loop closed form, which [`crate::canon`]
184//! establishes, and it is checked rather than assumed because the copy would otherwise leave a reader
185//! outside the loop seeing whichever half happened to define the value.
186//!
187//! Canonicalization runs a long way in front of this, and `simplify-cfg` between the two undoes some
188//! of what it did, so on SQLite the closed form condition once refused 351 of the checks this would
189//! otherwise have taken out. Running canonicalization again in front of this gets 156 of them back
190//! and costs 17672 bytes of `.text`, which is a bad trade for eleven more checks, so the answer is
191//! that this repairs the one loop it is splitting rather than the pipeline repairing every loop in
192//! the function. `repaired` is that, and with the repair reaching the joins the exits meet at as
193//! well as the exits themselves the condition now refuses none of them.
194//!
195//! What the repair cannot help with is a name the pass is about to write and has not written yet. A
196//! guard is worked out from values the loop was handed, and where the loop before it is one this is
197//! also splitting, a value that loop defines stops being one value the moment it has two halves.
198//! Those loops are refused, and there are five of them on SQLite against the two hundred and fifty
199//! the repair finishes.
200//!
201//! A loop with a loop inside it is not refused, and there is nothing about an inner loop that would
202//! make the copy wrong: the copier takes any set of blocks and the guard goes in front of the outer
203//! header either way. What the outer guard cannot speak for is a check inside the inner loop, since
204//! it measures where the outer walk has got to at the top of an outer iteration and the inner loop
205//! runs its whole way inside that iteration. Those checks stay in both halves and the inner loop's
206//! own split is what takes them, so what an outer split is worth is the checks in the outer loop's
207//! own blocks. On SQLite that is most of what is there: of the 169 nests the pass used to refuse
208//! outright, 162 have a check in the outer loop's own blocks and 113 have more than six.
209//!
210//! Where a nest plans twice the inner plan wins, because the two plans name blocks in common and
211//! applying either moves them. The outer one comes back on the next run of the pipeline. The size
212//! limit is the one limit, counted over the whole nest, which is what `heuristics::SPLIT_MAX_INSNS`
213//! already counts since a loop's block list holds the blocks of the loops inside it. A second and
214//! smaller limit was the obvious guess and the measurement says it is not needed: the outer loop's
215//! own blocks are over fifty instructions in 115 of those 169, so a nest that fits inside the limit
216//! is mostly the outer loop rather than mostly the inner one, and the limit is already pricing the
217//! part that pays.
218//!
219//! Not every check in the loop has to be one this can size. A check whose address the analysis cannot
220//! follow simply stays in both halves, and the fast half is then a loop with fewer checks in it rather
221//! than none. That is worth having on its own and it is worth having because it is what a real loop
222//! looks like: one sweep the analysis reads and one index that came out of a table.
223//!
224//! # Which level
225//!
226//! `-O2` and `-O3`, alongside `crate::unroll` and for the same reason. The loop body is copied, so
227//! the function grows by about the size of the loop, and buying speed with code is what those levels
228//! are for and what `-Os` and `-Oz` are for declining.
229
230use std::collections::{HashMap, HashSet};
231
232use rucc_cost::heuristics;
233use rucc_ir::{
234    Block, BlockCall, Builder, Def, Extra, Flags, Func, Inst, InstData, IntPred, Opcode, Type,
235    Value,
236};
237
238use crate::canon;
239use crate::cfg::Cfg;
240use crate::copy;
241use crate::discharge::{Question, constant, operand_of, yes};
242use crate::dom::Dominators;
243use crate::frontier::Frontiers;
244use crate::loops::{LoopId, Loops};
245use crate::rules::safety;
246use crate::scev::{Anchor, Evolution, Plain, Reading, Scev};
247use crate::trip::inst_of;
248use crate::{Analyses, Fuel, Pass, Preserved, Stats};
249
250/// What is reported when a loop is split.
251const SPLIT: &str = "loop split, the iterations in front of the first one that could fail a check \
252                     run without them";
253
254/// What is reported when a loop had to be put back into closed form before it could be split.
255const CLOSED_HERE: &str = "loop put back into closed form, a value it defines is read after it and both halves define one";
256
257/// What is reported when the pass ran out of fuel with a loop it was about to split.
258const NO_FUEL: &str = "loop left alone, the pass ran out of fuel";
259
260/// What is reported for a loop with nowhere to work the limit out.
261const NO_PREHEADER: &str = "loop left alone, it has no block in front of it to put a check in";
262
263/// What is reported for a loop whose blocks another loop being split here has already taken.
264const NESTED_WITH_ONE: &str = "loop left alone, a loop inside it is being split here instead";
265
266/// What is reported for a check that is not in the blocks of the loop being split.
267const INSIDE_A_LOOP: &str =
268    "check kept in both halves, it is in a loop inside the one being split and moves with that one";
269
270/// What is reported for a loop with more than one way round.
271const MANY_LATCHES: &str = "loop left alone, it goes back to its header from more than one place";
272
273/// What is reported for a loop with a call in it that could free.
274const A_CALL_INSIDE: &str = "loop left alone, a call in it might free what the loop is reading";
275
276/// What is reported for a loop holding something that ends a lifetime outright.
277const ENDS_A_LIFETIME: &str = "loop left alone, something in it ends a lifetime";
278
279/// What is reported for a loop holding something the copier cannot copy.
280const NOT_COPYABLE: &str = "loop left alone, something in it carries a side table this cannot copy";
281
282/// What is reported for a loop whose values are read after it without going through a parameter.
283const ESCAPES: &str = "loop left alone, a value it defines is read outside it";
284
285/// What is reported for a loop another loop's guard is about to name a value of.
286const WANTED_ELSEWHERE: &str =
287    "loop left alone, the guard of another loop being split here names a value it defines";
288
289/// What is reported for a loop whose two halves would be too much code.
290const TOO_BIG: &str = "loop left alone, the two halves would be more code than the limit allows";
291
292/// What is reported for a check whose address does not walk the loop.
293const NOT_A_SWEEP: &str = "check kept in both halves, its address does not walk the loop by a \
294                           constant";
295
296/// What is reported for a check whose address the analysis has nothing to say about.
297///
298/// The last of the four below rather than the only one, and what is left once [`stopped`] has had a
299/// look at the address. Anything that reaches here is an address built some way none of the three
300/// named shapes covers, so the row is the remainder of the census rather than the whole of it.
301const NOT_FOLLOWED: &str = "check kept in both halves, what its address does round the loop is not \
302                            something the analysis follows";
303
304/// What is reported for a check on a pointer the loop carries and reads back out of memory.
305const WALKS_A_STRUCTURE: &str = "check kept in both halves, the pointer it is about comes back \
306                                 round the loop out of memory, which is a walk over a linked \
307                                 structure";
308
309/// What is reported for a check whose address was itself read out of memory inside the loop.
310const ADDRESS_FROM_MEMORY: &str =
311    "check kept in both halves, the pointer it is about was read out of memory inside the loop";
312
313/// What is reported for a check whose address came back from a call inside the loop.
314const ADDRESS_FROM_A_CALL: &str =
315    "check kept in both halves, the pointer it is about came back from a call inside the loop";
316
317/// What is reported for a check whose address is one of two the loop chose between.
318const ADDRESS_FROM_A_CHOICE: &str =
319    "check kept in both halves, the pointer it is about is one of two the loop chose between";
320
321/// What is reported for a check on a pointer the pass cannot fault, moved by a displacement it can.
322const STEP_NOT_FOLLOWED: &str = "check kept in both halves, its address is a displacement off a \
323                                 pointer and the displacement is not something the analysis follows";
324
325/// What is reported for a check whose step does not keep its alignment.
326const MISALIGNED: &str =
327    "check kept in both halves, its step is not a whole number of its alignment";
328
329/// What is reported for a check the guard would have to measure, whose access wants an alignment
330/// nothing here can promise.
331const MEASURED_ALIGN: &str = "check kept in both halves, the guard would measure how far its \
332                              address moved and that is no answer about its alignment";
333
334/// What is reported for a check that already covers a range the program worked out.
335const ALREADY_COMPUTED: &str =
336    "check kept in both halves, how many bytes it covers is a number only the program has";
337
338/// What is reported for a derivation check whose walk does not start on the pointer it is about.
339const NOT_FROM_THE_START: &str = "derivation check kept in both halves, the walk starts along from \
340                                  the pointer the check is about rather than on it";
341
342/// What is reported for a check the rule table will not say yes about.
343const NOT_PROVED: &str = "check kept in both halves, no rule in the safety namespace says an offset inside the window is \
344     an access inside the object";
345
346/// The pass.
347#[derive(Debug)]
348pub struct Split;
349
350impl Pass for Split {
351    fn name(&self) -> &'static str {
352        "split"
353    }
354
355    fn describe(&self) -> &'static str {
356        "a loop becomes a run of iterations with no checks in it and the rest of the loop with them"
357    }
358
359    fn preserves(&self) -> Preserved {
360        // Blocks appear and edges move, so nothing built on the graph stands.
361        Preserved::NONE
362    }
363
364    fn run(&self, func: &mut Func, an: &mut Analyses, fuel: &mut Fuel) -> Stats {
365        let mut stats = Stats::new();
366        if func.entry().is_none() {
367            return stats;
368        }
369        let cfg = an.cfg(func);
370        let loops = an.loops(func);
371        if loops.count() == 0 {
372            return stats;
373        }
374
375        // Worked out first and applied afterwards, because scalar evolution reads the function and
376        // the transformation writes it. No two plans share a block, which `planned` sees to, so
377        // applying one leaves every other one's blocks where they were.
378        let mut plans = planned(func, cfg, loops, &mut stats);
379
380        // Closed form put back where it is missing, before anything is copied. The repair adds a
381        // block parameter and rewrites uses, so it moves no edge and creates no block, which is why
382        // the graph and the loop forest above are both still good after it. What it does move is
383        // which value a use inside another loop names, and a plan is a list of values, so a repair
384        // means the plans are worked out again rather than trusted. The stats go with them, or the
385        // first round's reasons would be counted twice.
386        let dom = an.dominators(func);
387        let fronts = an.frontiers(func);
388        let repairs = repaired(func, dom, fronts, loops, &plans, fuel);
389        if repairs.made > 0 {
390            stats = Stats::new();
391            plans = planned(func, cfg, loops, &mut stats);
392            for _ in 0..repairs.worked {
393                stats.optimized(CLOSED_HERE);
394            }
395        }
396        // A guard names values, and until it is written those uses are in the plans rather than in
397        // the function, so the walk that looks for a value read outside the loop cannot see them.
398        // They are collected here and the loops they belong to are refused, because a loop that is
399        // split stops having one value where another loop's guard expects to find one.
400        let named: Vec<(LoopId, Value)> = plans
401            .iter()
402            .flat_map(|plan| mentions(func, plan).into_iter().map(move |value| (plan.id, value)))
403            .collect();
404        plans.retain(|plan| {
405            if leaving(func, plan) {
406                stats.missed(ESCAPES);
407                return false;
408            }
409            if elsewhere(func, plan, &named) {
410                stats.missed(WANTED_ELSEWHERE);
411                return false;
412            }
413            true
414        });
415
416        let mut changed = false;
417        for plan in plans {
418            if !fuel.take() {
419                stats.missed(NO_FUEL);
420                continue;
421            }
422            apply(func, &plan);
423            stats.optimized(SPLIT);
424            changed = true;
425        }
426        if changed {
427            an.clear();
428        }
429        stats
430    }
431}
432
433/// How far past the first access an iteration reads, and who works that out.
434///
435/// Both are the same number and they differ in who does the arithmetic. `By` is a walk the analysis
436/// read, so the guard counts: it carries a byte offset of its own, starts it at zero on the way in
437/// and adds the step every time round. `Of` is a walk the analysis could not read, whose address is
438/// instead a fixed distance from a pointer the loop's header carries, so the guard measures: it
439/// takes where that pointer was on the way in from where it is now, and the difference is the
440/// displacement itself rather than a count standing in for it.
441///
442/// Measuring is what reaches a pointer that moves by an amount nobody wrote down, or by a different
443/// amount down each arm of a branch, or that comes back round through a join. None of those is an
444/// induction variable and there is nothing for scalar evolution to say about any of them, and
445/// between them they are 286 of the checks loop splitting still leaves in place on the SQLite
446/// amalgamation, at 44 sites. See tamnd/rucc#810.
447///
448/// The offset a measured walk produces is exact rather than an upper bound, which is what keeps this
449/// inside the rule table. `swept.sym.i64` is asked about it word for word as it is asked about a
450/// counted one, because `(p + k) - (first + k)` is `p - first` for whatever fixed `k` the check sits
451/// at, so the difference the guard computes is the displacement the rule is written about.
452#[derive(Clone, Copy, Debug, PartialEq, Eq)]
453enum Walk {
454    /// The address moves this many bytes every time round, either way. Zero is an address that does
455    /// not move, which is allowed and puts no limit on the loop. Negative is a walk from high to
456    /// low, and what changes for one is which end of the object the runtime is asked about rather
457    /// than anything about how the two halves are built.
458    By(i128),
459    /// The address is a fixed distance from a value the guard can work out for itself, out of the
460    /// parameters the header carries and the values the loop was handed. The loop moves it on by an
461    /// amount the analysis did not read, so where it is gets measured rather than counted.
462    Again {
463        /// The value to work out again, which is the check's address with the constant `ptr_add`s
464        /// on the front of it taken off. A parameter of the header is the commonest one and costs
465        /// nothing to work out, since the guard already carries it.
466        at: Value,
467    },
468}
469
470impl Walk {
471    /// Whether the address stays where it is, which is a loop that needs no guard at all.
472    fn still(self) -> bool {
473        self == Self::By(0)
474    }
475
476    /// Whether the address walks from high to low, which asks the runtime about the other end of
477    /// the object.
478    ///
479    /// A measured walk never does. The guard's subtraction is read unsigned, so a pointer that went
480    /// below where it started is an enormous displacement and the guard hands the loop to the half
481    /// that kept its checks, which is the answer that end of the object would have given anyway.
482    fn down(self) -> bool {
483        matches!(self, Self::By(step) if step < 0)
484    }
485
486    /// Which offset this walk shares with the others in the loop.
487    fn key(self) -> Key {
488        match self {
489            Self::By(step) => Key::Every(step.abs()),
490            Self::Again { at, .. } => Key::From(at),
491        }
492    }
493}
494
495/// Which checks are at the same offset from their own first access on every iteration, and so can
496/// share one offset in the guard and the smaller of their windows.
497#[derive(Clone, Copy, Debug, PartialEq, Eq)]
498enum Key {
499    /// They walk by the same number of bytes each time round, whichever way each of them goes.
500    Every(i128),
501    /// They are measured from the same value, which the guard works out again for itself. Two
502    /// checks a fixed distance from one pointer are the same distance apart on every iteration,
503    /// whatever the pointer does, so one subtraction answers for both, and one copy of whatever
504    /// arithmetic the pointer took answers for both as well.
505    From(Value),
506}
507
508/// One check the fast half will not need, and the walk that says so.
509#[derive(Debug)]
510struct Sweep {
511    /// The check itself, which is removed from the fast half and kept in the copy.
512    check: Inst,
513    /// Where the first iteration's address is computed from. An address rather than a value when
514    /// it is a global, since nothing outside the loop computes one of those. See [`Anchor`].
515    base: Anchor,
516    /// How far past that value the first iteration reads, in bytes. Usually a number, and a value
517    /// and a scale beside it when the loop started its counter at something it was handed. See
518    /// `spare` for how it is built and #810 for what it is worth.
519    apart: Plain,
520    /// What the address does round the loop, and so what the guard has to work out.
521    walk: Walk,
522    /// Everything inside the loop that has to be written again for the guard to have the address,
523    /// operands before uses. Empty for a counted walk and for a measured one off a parameter the
524    /// header already carries, which is most of them. See [`writable`].
525    rebuild: Vec<Value>,
526    /// How many bytes one access covers.
527    reach: i128,
528    /// How far past the window's first byte the walk's first access sits, when that is a distance
529    /// the loop works out rather than one written here. Nothing on almost every sweep, because the
530    /// two are the same address. See [`trailing`].
531    ahead: Option<Plain>,
532}
533
534/// One loop to split, worked out before anything is written.
535#[derive(Debug)]
536struct Plan {
537    /// The loop itself, which is read again when its closed form has to be repaired.
538    id: LoopId,
539    /// Where the limit is worked out.
540    preheader: Block,
541    /// The block the guard takes over from.
542    header: Block,
543    /// The block the back edge leaves from, which is where the iteration count goes up.
544    latch: Block,
545    /// Everything that is copied, which is the whole loop.
546    body: Vec<Block>,
547    /// The checks the fast half will not need, which is never empty in a plan.
548    sweeps: Vec<Sweep>,
549}
550
551/// Plans a loop, or counts what stopped it.
552///
553/// Nothing is reported for a loop with no check in it, because a loop that does no memory access is
554/// not a missed opportunity and a report for every one of them would bury the loops that are.
555fn sweep(
556    func: &Func,
557    cfg: &Cfg,
558    loops: &Loops,
559    scev: &mut Scev<'_>,
560    id: LoopId,
561    plans: &mut Vec<Plan>,
562    stats: &mut Stats,
563) {
564    let body = loops.blocks(id).to_vec();
565    let checks: Vec<Inst> = body
566        .iter()
567        .flat_map(|&block| func.insts(block).collect::<Vec<Inst>>())
568        .filter(|&inst| {
569            matches!(
570                func[inst].opcode,
571                Opcode::CheckBounds | Opcode::CheckLive | Opcode::CheckDeriv
572            )
573        })
574        .collect();
575    if checks.is_empty() {
576        return;
577    }
578
579    let (preheader, latch) = match shaped(func, cfg, loops, id, &body) {
580        Ok(shape) => shape,
581        Err(why) => {
582            stats.missed(why);
583            return;
584        }
585    };
586    let mut sweeps = Vec::new();
587    for check in checks {
588        // A check in a loop inside this one runs many times for each time round this one, at an
589        // address that moves with the inner loop rather than with this one. The guard here measures
590        // where this loop's walk has got to at the top of an iteration, and that says nothing about
591        // how far the inner loop goes before the iteration is over, so the check stays in both
592        // halves. What takes it is the inner loop's own split, which is a plan of its own.
593        if func.block_of(check).is_none_or(|block| loops.innermost(block) != Some(id)) {
594            stats.missed(INSIDE_A_LOOP);
595            continue;
596        }
597        match walked(func, cfg, loops, scev, id, latch, check) {
598            Ok(sweep) => sweeps.push(sweep),
599            Err(why) => stats.missed(why),
600        }
601    }
602    if sweeps.is_empty() {
603        return;
604    }
605    plans.push(Plan { id, preheader, header: loops.header(id), latch, body, sweeps });
606}
607
608/// The preheader and the latch of a loop this pass may copy, or why there is not one.
609///
610/// The conditions are the module comment's. The one worth restating is freeing, because it is the
611/// only one that is about what the fast half is allowed to leave out rather than about whether the
612/// copy can be made at all: the extent is asked once before the loop and believed for the whole of
613/// the fast half, so anything that could hand the storage back in the middle would make the answer
614/// stale, and the fast half has nothing left in it to notice.
615///
616/// Which is a question about the callee and not about calling, so it is asked of the callee.
617/// [`crate::nofree`] settles it before the pipeline starts and writes the answer onto the call site,
618/// and a call carrying it reaches nothing that ends a lifetime. Note that this is a weaker
619/// requirement than [`crate::hoist`]'s, which refuses every call whatever it does, because hoisting
620/// needs the loop to reach the end of what its count says and a call that does not come back leaves
621/// it short. Splitting never claims that, so coming back is not something it needs.
622fn shaped(
623    func: &Func,
624    cfg: &Cfg,
625    loops: &Loops,
626    id: LoopId,
627    body: &[Block],
628) -> Result<(Block, Block), &'static str> {
629    let Some(preheader) = loops.preheader(cfg, id) else {
630        return Err(NO_PREHEADER);
631    };
632    let [latch] = loops.latches(id) else {
633        return Err(MANY_LATCHES);
634    };
635    for &block in body {
636        for inst in func.insts(block) {
637            match func[inst].opcode {
638                Opcode::Call | Opcode::CallIndirect | Opcode::TailCall
639                    if !func[inst].flags.contains(Flags::NOFREE) =>
640                {
641                    return Err(A_CALL_INSIDE);
642                }
643                // Assembly could do anything and the two meta instructions end a lifetime by
644                // definition, which is the same answer `crate::nofree` gives for all three.
645                Opcode::InlineAsm | Opcode::MetaEnd | Opcode::MetaTransfer => {
646                    return Err(ENDS_A_LIFETIME);
647                }
648                _ => {}
649            }
650            if !copy::copyable(func, inst) {
651                return Err(NOT_COPYABLE);
652            }
653        }
654    }
655    let size = body.iter().map(|&block| func.insts(block).count()).sum::<usize>();
656    if size > heuristics::SPLIT_MAX_INSNS as usize {
657        return Err(TOO_BIG);
658    }
659    Ok((preheader, *latch))
660}
661
662/// Every loop in the function that is worth copying, and why each of the others is not.
663///
664/// A nest can plan twice, once for the inner loop and once for the outer one, and the two plans name
665/// blocks in common. Applying either of them moves those blocks, so only one may run, and the one
666/// kept is the inner one. That is not a coin toss: the outer plan takes checks out of the outer
667/// loop's own blocks, which run once per outer iteration, while the inner plan takes checks out of
668/// blocks that run once per inner iteration, and the inner loop is also the smaller thing to copy.
669/// The outer loop is left for the next run of the pipeline, when the inner one is already split.
670fn planned(func: &Func, cfg: &Cfg, loops: &Loops, stats: &mut Stats) -> Vec<Plan> {
671    let mut plans = Vec::new();
672    let mut scev = Scev::new(func, cfg, loops);
673    for id in loops.all() {
674        sweep(func, cfg, loops, &mut scev, id, &mut plans, stats);
675    }
676    plans.sort_by_key(|plan| std::cmp::Reverse(loops.depth(plan.id)));
677    let mut taken: HashSet<Block> = HashSet::new();
678    plans.retain(|plan| {
679        if plan.body.iter().any(|block| taken.contains(block)) {
680            stats.missed(NESTED_WITH_ONE);
681            return false;
682        }
683        taken.extend(plan.body.iter().copied());
684        true
685    });
686    plans
687}
688
689/// How many loops the closed form repair touched, and how many of those it finished.
690///
691/// Two numbers rather than one because they answer different questions. Anything touched at all is
692/// why the plans have to be worked out again, and only the ones it finished are loops that can now
693/// be copied and so are what gets reported.
694struct Repairs {
695    /// Loops the repair wrote something into.
696    made: usize,
697    /// Loops that are in closed form afterwards.
698    worked: usize,
699}
700
701/// Puts the loops that need it back into closed form, before anything is copied.
702///
703/// [`crate::canon`] establishes closed form a long way in front of this pass and `simplify-cfg`
704/// between the two undoes some of what it did. Running the whole of canonicalization again was
705/// measured and it costs 17672 bytes of `.text` on the SQLite amalgamation, because it repairs every
706/// loop in the function rather than the ones about to be copied. This repairs those, which costs
707/// nothing on a function with no loop to split.
708///
709/// A value read past a join that no single exit dominates gets a parameter at the join as well as
710/// at each exit, which is what the iterated dominance frontier in [`canon::leaked`] is for. What is
711/// still not repaired is a use the placements do not dominate at all, so the count of what worked
712/// is a second look rather than an assumption that the first one did.
713fn repaired(
714    func: &mut Func,
715    dom: &Dominators,
716    fronts: &Frontiers,
717    loops: &Loops,
718    plans: &[Plan],
719    fuel: &mut Fuel,
720) -> Repairs {
721    let mut repairs = Repairs { made: 0, worked: 0 };
722    for plan in plans {
723        if !leaving(func, plan) {
724            continue;
725        }
726        let mut wrote = false;
727        while let Some(job) = canon::leaked(func, dom, fronts, loops, plan.id) {
728            if !fuel.take() {
729                break;
730            }
731            canon::close(func, dom, loops, &job);
732            wrote = true;
733        }
734        if !wrote {
735            continue;
736        }
737        repairs.made += 1;
738        if !leaving(func, plan) {
739            repairs.worked += 1;
740        }
741    }
742    repairs
743}
744
745/// Whether anything after this loop reads a value its body defines.
746fn leaving(func: &Func, plan: &Plan) -> bool {
747    let inside: HashSet<Block> = plan.body.iter().copied().collect();
748    escapes(func, &plan.body, &inside)
749}
750
751/// Every value a plan's guard will name, which is a use that is not in the function yet.
752///
753/// The guard runs in front of the loop and works out where its first access is, so what it names is
754/// whatever those addresses were built on. Where a check's address has to
755/// be written again there is arithmetic to copy as well, and the values that arithmetic rests on are
756/// the operands of the instructions being copied, since [`remade`] rewrites the header's parameters
757/// and leaves everything else naming what it named inside the loop.
758fn mentions(func: &Func, plan: &Plan) -> Vec<Value> {
759    let mut found = Vec::new();
760    for sweep in &plan.sweeps {
761        found.extend(sweep.base.value());
762        found.extend(sweep.apart.value);
763        if let Walk::Again { at, .. } = sweep.walk {
764            found.push(at);
765        }
766        for &value in &sweep.rebuild {
767            found.push(value);
768            if let Def::Result { inst, .. } = func[value].def {
769                found.extend(func[func[inst].args].iter().copied());
770            }
771        }
772    }
773    found
774}
775
776/// Whether some other loop being split here has a guard that names a value this one's body defines.
777///
778/// Splitting a loop is what makes such a name wrong. Before it, the value is defined on the one path
779/// out of the loop and so is there to be read in front of the next one. After it, there are two
780/// paths out and the value on each belongs to its own half, which is the same thing loop closed form
781/// is about and is why the repair in front of this pass exists. The repair cannot help here, because
782/// the use it would point at a parameter is one the pass has not written down yet.
783fn elsewhere(func: &Func, plan: &Plan, named: &[(LoopId, Value)]) -> bool {
784    let defined = defines(func, &plan.body);
785    named.iter().any(|&(id, value)| id != plan.id && defined.contains(&value))
786}
787
788/// Every value the blocks of a loop define, parameters and results alike.
789fn defines(func: &Func, body: &[Block]) -> HashSet<Value> {
790    let mut defined: HashSet<Value> = HashSet::new();
791    for &block in body {
792        defined.extend(func[block].params.iter().copied());
793        for inst in func.insts(block) {
794            defined.extend(func[inst].results());
795        }
796    }
797    defined
798}
799
800/// Whether anything outside the loop reads a value defined inside it.
801///
802/// Where there is one, the two halves would leave it reading whichever of them happened to define
803/// it. Closed form is what makes it not one: the use names a parameter of the block the loop leaves
804/// to, and each half fills that parameter in on its own way out.
805fn escapes(func: &Func, body: &[Block], inside: &HashSet<Block>) -> bool {
806    let defined = defines(func, body);
807    for block in func.blocks() {
808        if inside.contains(&block) {
809            continue;
810        }
811        for inst in func.insts(block) {
812            if func[func[inst].args].iter().any(|value| defined.contains(value)) {
813                return true;
814            }
815            for call in func.successors(inst) {
816                if func[call.args].iter().any(|value| defined.contains(value)) {
817                    return true;
818                }
819            }
820        }
821    }
822    false
823}
824
825/// What one check's address does round the loop, or why the pass cannot say.
826///
827/// The counted walk is asked for first and the measured one takes what it could not. That order is
828/// the cheaper answer first: a counted walk costs the guard an add on a value it already carries,
829/// and a measured one costs it a subtraction of two pointers every time round. It is also the more
830/// exact answer first, since a counted walk knows the step and so knows the alignment, which a
831/// measured one never does.
832#[allow(clippy::too_many_arguments)]
833fn walked(
834    func: &Func,
835    cfg: &Cfg,
836    loops: &Loops,
837    scev: &mut Scev<'_>,
838    id: LoopId,
839    latch: Block,
840    check: Inst,
841) -> Result<Sweep, &'static str> {
842    // A derivation check names four operands and the pointer that walks is the third of them, since
843    // the capability it carries is the old pointer's rather than the new one's. Everything below is
844    // written about the address that moves, so the two are pulled apart here and what the shape
845    // needs beyond a walk is asked once the walk is known.
846    let (capability, source, pointer) = match (func[check].opcode, &func[func[check].args]) {
847        (Opcode::CheckDeriv, &[capability, from, to, _stride]) => (capability, Some(from), to),
848        (Opcode::CheckDeriv, _) => return Err(NOT_A_SWEEP),
849        // A check that already carries its own extent is one hoisting put somewhere, and how many
850        // bytes it covers is not a number this pass can divide by a step.
851        (_, args) if args.len() > 2 => return Err(ALREADY_COMPUTED),
852        (_, &[capability, pointer]) => (capability, None, pointer),
853        _ => return Err(NOT_A_SWEEP),
854    };
855    if operand_of(func, capability, Opcode::CapOf, 0) != Some(source.unwrap_or(pointer)) {
856        return Err(NOT_A_SWEEP);
857    }
858    // A liveness check reads no bytes, so the window it needs is the one byte its address is in.
859    // A bounds check carries how many it reads in its payload. A derivation check reads no bytes
860    // either, and the byte its address is in is the narrower of the two windows document 03 section
861    // 3.1 allows it, so asking for that one is a smaller claim than the judgement needs.
862    let (reach, align) = match func[check].extra {
863        Extra::Mem(held) => (i128::from(func[held].size), i128::from(func[held].align)),
864        _ => (1, 1),
865    };
866
867    let (base, apart, walk, rebuild) = match following(func, scev, id, pointer) {
868        Ok((base, apart, step)) => (base, apart, Walk::By(step), Vec::new()),
869        // The reason the counted walk gave is what gets reported when the measured one cannot take
870        // the check either, so that the census keeps saying what the analysis made of the address
871        // rather than collapsing every one of them into this fallback missing.
872        Err(why) => match measured(func, cfg, loops, id, latch, pointer) {
873            Some(found) => found,
874            // The one reason on that list that names no shape. Every other one says what the
875            // address was and why that is not enough, and this one says the analysis had nothing to
876            // say at all, so what it stopped on is worked out here rather than left as one row.
877            None if why == NOT_FOLLOWED => return Err(stopped(func, loops, id, latch, pointer)),
878            None => return Err(why),
879        },
880    };
881    match walk {
882        // An address a whole number of steps along from an aligned one is aligned, which is the
883        // whole of what this condition is. It is [`crate::hoist`]'s and it is here for the reason it
884        // is there, that a bounds check carries an alignment as well as a byte count.
885        Walk::By(step) if step != 0 && step % align != 0 => return Err(MISALIGNED),
886        // A measured walk moves by an amount nobody wrote down, so there is no such number to divide
887        // and nothing here can say the second access is as aligned as the first. Refusing on the
888        // access wanting any alignment at all is the conservative reading, and it is its own line in
889        // the census so that what it costs is a number rather than a guess.
890        //
891        // Refusing looks like bookkeeping about a payload, because `__rucc_check_bounds` takes an
892        // address, a size and a descriptor and the alignment never reaches it. It is not. The
893        // alignment is a conjunct of J1 in `spec/safe-memory/04-safety-model.md`, it is bug class S7
894        // in document 03, and `tests/safety` has three programs for it that are marked as gaps
895        // closing on `tamnd/rucc#431`. What that means here is that the field is going to start
896        // being read, and a pass that had quietly stopped preserving it in the meantime would be
897        // the reason it could not. So the refusal stays and the sixty odd checks it costs are the
898        // price of a claim that is still open rather than a mistake to be tidied away.
899        Walk::Again { .. } if align > 1 => return Err(MEASURED_ALIGN),
900        _ => {}
901    }
902    // A derivation check asks about the old pointer's capability, and the window is worked out from
903    // the extent of whatever owns the first iteration's address, so those two have to be the same
904    // object. Either the walk starts on the old pointer, which [`started`] is, or the old pointer
905    // walks the loop alongside the new one and one window holds the pair, which [`paired`] is.
906    let (apart, reach, ahead) = match source {
907        None => (apart, reach, None),
908        Some(from) if started(base, apart, from) => (apart, reach, None),
909        Some(from) => match paired(func, scev, id, base, apart, walk, from) {
910            Some((apart, reach)) => (apart, reach, None),
911            None => match trailing(func, scev, id, base, apart, walk, from) {
912                Some((apart, ahead)) => (apart, reach, Some(ahead)),
913                None => return Err(NOT_FROM_THE_START),
914            },
915        },
916    };
917    // Whether an offset inside the window means an access inside the object, which is what dropping
918    // this check rests on and is not something this file decides. The direction goes with it,
919    // because a walk from high to low is a different claim about addresses and has its own rule.
920    if !windowed(reach, walk.down()) {
921        return Err(NOT_PROVED);
922    }
923    Ok(Sweep { check, base, apart, walk, rebuild, reach, ahead })
924}
925
926/// Whether the first iteration's address is a given pointer rather than somewhere along from it.
927///
928/// [`spare`] asks the runtime about the first iteration's address, which is the base plus however
929/// far the first access sits past it, so a window says what it is meant to say about a derivation
930/// check only when those two are the same address. The condition is the base being the pointer the
931/// check names and the displacement being nothing, which together say the walk starts on it.
932///
933/// A walk that starts a little way along is not rescued by the guard refusing. An address past the
934/// end of one object can be inside the next one, and then the extent comes back positive, the
935/// window is real, and what it is about is the wrong object. The one thing that does hold is a
936/// walk starting on an address nobody owns, which answers zero and sends every iteration to the
937/// slow half, and that is not enough on its own.
938///
939/// [`paired`] is the other way this can hold, and between the two of them they are most of what a
940/// derivation check in a loop looks like.
941fn started(base: Anchor, apart: Plain, from: Value) -> bool {
942    base == Anchor::Value(from) && flat(apart) == Some(0)
943}
944
945/// One window that holds the pointer a derivation check is about and where its walk begins.
946///
947/// `p = p + k` is the commonest derivation there is and [`started`] refuses every one of them,
948/// because the pointer the check names is the one moving and the walk therefore starts wherever the
949/// loop was handed rather than on it. On SQLite that refusal is 1546 checks against the 146
950/// [`started`] takes, and `bench/safety/a-string-scan` is the shape: a cursor stepped a byte at a
951/// time, with the derivation check the only thing the fast half still had in it.
952///
953/// The way through is to stop asking about one address and ask about both. Both have to follow one
954/// anchor, so that the distance between them is a number this can work out, and then a window
955/// measured from whichever of them is lower and wide enough to cover the gap holds the pair on the
956/// first iteration. That is the same claim [`windowed`] already asks about an access that many
957/// bytes wide, written about two pointers instead of about the bytes under one, and the pass asks
958/// it in exactly that form rather than inventing a second one.
959///
960/// What it earns is what a derivation check wants. The lower end is inside the object the query was
961/// about, so the capability the check names is that object, and the upper end is inside it too, so
962/// the pointer computed from it did not leave. Which of the two is the old pointer does not come
963/// into it, which is why a step down needs nothing said separately: `p = p - 1` is the same pair a
964/// byte apart with the ends the other way round.
965///
966/// # The two steps this takes
967///
968/// The old pointer moving by the same step as the new one is the first, and there the distance
969/// between the two is the same number on every iteration, so the one window holds the pair wherever
970/// the walk has got to.
971///
972/// The old pointer not moving at all is the second, and there the pair comes apart as the walk goes
973/// on. It is still taken, and what makes it sound is that a pointer which does not move only has to
974/// be placed once. The first iteration's window holds it, the first iteration is in the fast half
975/// whenever anything is, and a window on a later iteration says where the walk has reached. So the
976/// two things a derivation check asks are answered by two askings of the one rule rather than by
977/// one, and neither of them is arithmetic this file did quietly. On SQLite these are 370 of the
978/// refusals against the 55 where the old pointer moves at a step of its own, and that last case is
979/// the one that stays refused: a pointer running away at its own rate is not placed by either
980/// window.
981///
982/// The displacements have to be numbers here, since putting the window on the lower of the two and
983/// making it as wide as the gap is arithmetic there is no reason to do at run time when the answer
984/// is already known. A gap the loop works out is [`trailing`], which puts the window somewhere else
985/// and hands the guard the subtraction.
986fn paired(
987    func: &Func,
988    scev: &mut Scev<'_>,
989    id: LoopId,
990    base: Anchor,
991    apart: Plain,
992    walk: Walk,
993    from: Value,
994) -> Option<(Plain, i128)> {
995    let Walk::By(step) = walk else { return None };
996    let (anchor, behind, along) = following(func, scev, id, from).ok()?;
997    if anchor != base || (along != step && along != 0) {
998        return None;
999    }
1000    let (near, far) = (flat(behind)?, flat(apart)?);
1001    let reach = near.abs_diff(far).checked_add(1)?;
1002    let apart = Plain { value: None, read: None, scale: 0, offset: near.min(far) };
1003    Some((apart, i128::try_from(reach).ok()?))
1004}
1005
1006/// The same window when the gap between the two pointers is a distance the loop works out.
1007///
1008/// [`paired`] needs both displacements to be numbers, because it puts the window on the lower of
1009/// the two and makes it as wide as the difference, and neither of those is arithmetic worth doing
1010/// where the answer is already known. A subscript computed in an outer loop is not a number. On
1011/// SQLite that is 103 of the refusals and `bench/safety/a-strided-column-sum.c` is the shape:
1012/// `grid[row * COLS + col]` walked down the rows, where the pointer the check names is the
1013/// allocation itself and the walk begins `col` elements into it.
1014///
1015/// What is done instead is to put the window on the pointer the check names, which is the object
1016/// the check is about and so the object the query has to be about, and hand the guard the gap to
1017/// take off the window it measured. The preheader of the loop being split is where that happens, it
1018/// is a multiply and a subtract, and the value being multiplied is one the outer loop already
1019/// worked out.
1020///
1021/// Two things have to hold and both are asked rather than assumed. The pointer the check names has
1022/// to stand still, for the reason [`paired`] gives. And the gap has to come out at or above zero,
1023/// since a walk beginning below the pointer the window was measured from is a walk into bytes the
1024/// extent said nothing about. That second one is not a range the analysis reads, it is a comparison
1025/// the guard makes, and it is the one extra instruction this costs over [`paired`].
1026///
1027/// A walk that goes down is left alone. Its window is measured backwards from the end of the first
1028/// access, so the gap would be a claim about bytes on the other side of the pointer and it is a
1029/// different argument rather than this one with a sign changed.
1030fn trailing(
1031    func: &Func,
1032    scev: &mut Scev<'_>,
1033    id: LoopId,
1034    base: Anchor,
1035    apart: Plain,
1036    walk: Walk,
1037    from: Value,
1038) -> Option<(Plain, Plain)> {
1039    if !matches!(walk, Walk::By(_)) || walk.down() {
1040        return None;
1041    }
1042    let (anchor, behind, along) = following(func, scev, id, from).ok()?;
1043    if anchor != base || along != 0 {
1044        return None;
1045    }
1046    let near = flat(behind)?;
1047    // Nothing to hand the guard when the walk's own displacement is a number as well, since that is
1048    // the case [`paired`] took and this would be a worse answer to it.
1049    apart.value.filter(|_| apart.scale != 0)?;
1050    let ahead = Plain { offset: apart.offset.checked_sub(near)?, ..apart };
1051    Some((Plain { value: None, read: None, scale: 0, offset: near }, ahead))
1052}
1053
1054/// The displacement as a number, when it is nothing but one.
1055///
1056/// [`displacement`]'s test written the other way round: nothing to add is a value that is not there
1057/// or is not counted, and no number on top of it.
1058fn flat(apart: Plain) -> Option<i128> {
1059    apart.value.filter(|_| apart.scale != 0).is_none().then_some(apart.offset)
1060}
1061
1062/// The walk scalar evolution read, as a base to measure from and a step in bytes.
1063///
1064/// An address that does not move is a sweep with a step of zero, and the arithmetic downstream takes
1065/// it without a special case anywhere. Hoisting would rather have these, but hoisting only gets the
1066/// ones in loops it is willing to touch at all, and a loop it refused for one of its own reasons
1067/// leaves the check where it is. Splitting is willing to touch more loops, so the same check comes
1068/// back here and there is no reason to hand it back.
1069fn following(
1070    func: &Func,
1071    scev: &mut Scev<'_>,
1072    id: LoopId,
1073    pointer: Value,
1074) -> Result<(Anchor, Plain, i128), &'static str> {
1075    let (start, step) = match scev.evolution(id, pointer) {
1076        Evolution::Affine(chrec) => {
1077            let Some(step) = chrec.step.as_number() else {
1078                return Err(NOT_A_SWEEP);
1079            };
1080            (chrec.base, step)
1081        }
1082        Evolution::Invariant(base) => (base, 0),
1083        _ => return Err(NOT_FOLLOWED),
1084    };
1085    // Scale one because the base is an address. Anything else is a multiple of a pointer, which is
1086    // not a thing the loop computed, so it is a shape this reads rather than a case to handle.
1087    //
1088    // The second arm is `a + 8 * start`, an address the loop reached before it began, which is what
1089    // a counter the caller handed in looks like once the front end has multiplied the element size
1090    // through it. The pointer is the side the whole thing is measured from and the index is what is
1091    // scaled beside it, so anything else with two values in it is refused here rather than turned
1092    // into an address off whichever value came first.
1093    match (start.plain(), start.on()) {
1094        (Some(at @ Plain { value: Some(base), read: None, scale: 1, .. }), _) => Ok((
1095            Anchor::Value(base),
1096            Plain { value: None, read: None, scale: 0, offset: at.offset },
1097            step,
1098        )),
1099        (_, Some((base, apart))) if walks(func, base, apart) => Ok((base, apart, step)),
1100        _ => Err(NOT_A_SWEEP),
1101    }
1102}
1103
1104/// The walk the guard can measure, for an address the guard can work out for itself.
1105///
1106/// A syntactic walk rather than an analysis, because what it has to establish is syntactic. The
1107/// address is peeled of the constant `ptr_add`s on the front of it, and what is under them has to be
1108/// something the guard could write again out of the parameters the header hands it and the values
1109/// the loop was handed from outside. The first access is then the same expression written in the
1110/// preheader out of the values the preheader passes, `k` bytes along, and the displacement on any
1111/// later iteration is the one less the other. That is a subtraction the guard can do, whatever the
1112/// loop did to the pointer in between.
1113///
1114/// The commonest shape by far is the address being a parameter of the header outright, and that
1115/// costs nothing to write again: the guard already carries the parameter and the preheader already
1116/// passes it. Everything past that is [`writable`] and [`remade`], which are what make `p + x` for
1117/// a variable `x` reachable, and `x` is a variable in a third of what is left here.
1118///
1119/// # What the back edge has to look like
1120///
1121/// The value the latch hands the parameter has to be that same parameter moved: through `ptr_add`s,
1122/// through parameters of blocks inside the loop, and through a `select`, which is what a branch that
1123/// moves the pointer differently down each arm turns into. Anything else is refused.
1124///
1125/// That question is asked of every pointer the address is built on that the header carries. One the
1126/// loop was handed from outside does not move at all and so has nothing to answer.
1127///
1128/// The refusal is the point of the walk, and not for the reason it looks like. The subtraction is
1129/// sound whatever the pointer did, because the guard compares the difference against the window at
1130/// run time: a pointer that landed inside the first one's object passes and one that did not takes
1131/// the slow half. What the refusal is about is profit. A list is `p = p->next`, where the value on
1132/// the back edge is a load, and the next node of a heap allocated list is its own object, so the
1133/// guard fails on the second iteration and every one after it and both halves keep every check.
1134/// Measured on SQLite, taking lists as well splits 73 more loops, puts 220 more calls to
1135/// `check_bounds` in the object and adds 139 kilobytes, and removes 5 liveness checks.
1136fn measured(
1137    func: &Func,
1138    cfg: &Cfg,
1139    loops: &Loops,
1140    id: LoopId,
1141    latch: Block,
1142    pointer: Value,
1143) -> Option<(Anchor, Plain, Walk, Vec<Value>)> {
1144    let (at, offset) = peeled(func, pointer);
1145    if !func[at].ty.is_ptr() {
1146        return None;
1147    }
1148    let mut rebuild = Vec::new();
1149    let mut leaves = Vec::new();
1150    let mut seen = HashSet::new();
1151    if !writable(func, loops, id, at, &mut rebuild, &mut leaves, &mut seen) {
1152        return None;
1153    }
1154    if rebuild.len() > heuristics::SPLIT_REMADE_INSNS {
1155        return None;
1156    }
1157    if !leaves.iter().all(|&leaf| carried(func, cfg, loops, id, latch, leaf)) {
1158        return None;
1159    }
1160    // The base is where the first access is measured from, and it is written in the preheader by
1161    // `limited` rather than named here, since for anything but a bare parameter no such value exists
1162    // yet. `Anchor::Value(at)` says which expression to write, and `limited` is where it is written.
1163    let apart = Plain { value: None, read: None, scale: 0, offset };
1164    Some((Anchor::Value(at), apart, Walk::Again { at }, rebuild))
1165}
1166
1167/// Whether the guard could write the expression that works this address out somewhere else, and in
1168/// what order.
1169///
1170/// The two places it would be written are the guard, out of the parameters the header carries, and
1171/// the preheader, out of the values the preheader passes the header. So a value stops the walk when
1172/// both of those already have it, and there are two ways that happens. A value defined outside the
1173/// loop is the same number wherever it is read, so it is written again by being read again. A
1174/// parameter of the header is carried by the guard and passed by the preheader, so each of them has
1175/// its own in hand. Both kinds are leaves, and a pointer leaf is reported to the caller because
1176/// whether the address is worth measuring turns on what the loop does to it.
1177///
1178/// Everything else in the loop has to be an instruction this may write a second copy of. A parameter
1179/// of a block inside the loop is not: it is a join, and which value arrived depends on which way the
1180/// iteration went, which neither the guard nor the preheader is in a position to know. Nor is
1181/// anything that reads memory, because the second copy would read it at a different moment.
1182///
1183/// The order is a post order, so operands come out in front of the uses that want them, which is
1184/// what [`remade`] needs to write them in one pass. It may hold junk when this refuses, and the
1185/// caller throws it away.
1186fn writable(
1187    func: &Func,
1188    loops: &Loops,
1189    id: LoopId,
1190    value: Value,
1191    order: &mut Vec<Value>,
1192    leaves: &mut Vec<Value>,
1193    seen: &mut HashSet<Value>,
1194) -> bool {
1195    // A value reached twice is written once, and its place in the order is the first one, which is
1196    // in front of both uses. Returning true here is safe because a refusal anywhere refuses the
1197    // whole address, so a value already seen is one already accepted.
1198    if !seen.insert(value) {
1199        return true;
1200    }
1201    let at = match func[value].def {
1202        Def::Result { inst, .. } => func.block_of(inst),
1203        Def::Param { block, .. } => Some(block),
1204    };
1205    if at.is_none_or(|at| !loops.contains(id, at)) {
1206        if func[value].ty.is_ptr() {
1207            leaves.push(value);
1208        }
1209        return true;
1210    }
1211    // A value defined in a loop inside this one is neither of those. It is not the same number
1212    // wherever it is read, so reading it again in the preheader is not writing it again, and it is
1213    // not a parameter of the header, so neither block has it in hand. The two questions look alike
1214    // and the answers are opposite, which is why this arm is separate from the one above rather
1215    // than folded into it as "not in this loop's own blocks".
1216    if at.is_some_and(|at| loops.innermost(at) != Some(id)) {
1217        return false;
1218    }
1219    match func[value].def {
1220        Def::Param { block, .. } => {
1221            if block != loops.header(id) {
1222                return false;
1223            }
1224            if func[value].ty.is_ptr() {
1225                leaves.push(value);
1226            }
1227            true
1228        }
1229        Def::Result { inst, index } => {
1230            if index != 0 || !plain(func[inst].opcode) {
1231                return false;
1232            }
1233            let args = func[func[inst].args].to_vec();
1234            if !args.iter().all(|&arg| writable(func, loops, id, arg, order, leaves, seen)) {
1235                return false;
1236            }
1237            order.push(value);
1238            true
1239        }
1240    }
1241}
1242
1243/// Whether an instruction is one the guard may write a second copy of.
1244///
1245/// A list rather than a question about effects, and deliberately. What has to hold is that a second
1246/// copy in another block computes the same number, which rules out anything that reads memory and
1247/// anything that depends on where it is, and that writing it in the preheader is harmless on a loop
1248/// that turns out to run no iterations at all, which rules out anything that can fault. A division
1249/// is the one that catches people out: it has no effects to speak of and it traps on a zero the
1250/// first iteration would never have reached. Naming what is allowed makes an opcode added later
1251/// refused until somebody looks at it, which is the right way round for this.
1252fn plain(opcode: Opcode) -> bool {
1253    matches!(
1254        opcode,
1255        Opcode::IConst
1256            | Opcode::Add
1257            | Opcode::Sub
1258            | Opcode::Mul
1259            | Opcode::Shl
1260            | Opcode::LShr
1261            | Opcode::AShr
1262            | Opcode::And
1263            | Opcode::Or
1264            | Opcode::Xor
1265            | Opcode::SExt
1266            | Opcode::ZExt
1267            | Opcode::Trunc
1268            | Opcode::ICmp
1269            | Opcode::Select
1270            | Opcode::PtrAdd
1271            | Opcode::GlobalAddr
1272    )
1273}
1274
1275/// Writes the expression that works an address out into the block a builder is on, with the header's
1276/// parameters replaced by whatever that block has in their place.
1277///
1278/// The order is [`writable`]'s, so every operand has been written by the time the use of it is
1279/// reached and one pass over the list is enough. A value not in the map is one from outside the loop,
1280/// which is itself wherever it is read.
1281///
1282/// Flags come off. `nsw` on an add in the loop is a promise about an address the loop was going to
1283/// compute, and the copy in the preheader is computed whether the loop runs or not, so a promise that
1284/// held there does not obviously hold here. Dropping it costs nothing, since what is built is a
1285/// question for the runtime rather than an address anything reads through.
1286fn remade(
1287    build: &mut Builder<'_>,
1288    made: &mut Vec<Value>,
1289    order: &[Value],
1290    at: Value,
1291    swap: &HashMap<Value, Value>,
1292) -> Value {
1293    let mut swap = swap.clone();
1294    for &value in order {
1295        let Def::Result { inst, .. } = build.func()[value].def else {
1296            unreachable!("the order holds nothing but instruction results")
1297        };
1298        let data = build.func()[inst];
1299        let args: Vec<Value> = build.func()[data.args]
1300            .iter()
1301            .map(|arg| swap.get(arg).copied().unwrap_or(*arg))
1302            .collect();
1303        let args = build.func().push_values(&args);
1304        let ty = build.func()[value].ty;
1305        let copy =
1306            build.value(InstData { args, extra: data.extra, ..InstData::new(data.opcode) }, ty);
1307        made.push(copy);
1308        swap.insert(value, copy);
1309    }
1310    swap.get(&at).copied().unwrap_or(at)
1311}
1312
1313/// Whether the loop moves a pointer it carries in a way this is willing to measure.
1314///
1315/// A pointer the loop was handed from outside does not move at all and is nothing to refuse. One the
1316/// header carries is handed back round the latch, and what comes back has to be that same pointer
1317/// moved, which is [`moving`] and is where the linked list refusal lives.
1318fn carried(func: &Func, cfg: &Cfg, loops: &Loops, id: LoopId, latch: Block, leaf: Value) -> bool {
1319    let header = loops.header(id);
1320    let Def::Param { block, index } = func[leaf].def else { return true };
1321    if block != header {
1322        return true;
1323    }
1324    let Some(term) = func.terminator(latch) else { return false };
1325    let round = copy::edge_args(func, term, header);
1326    let Some(&next) = round.get(index as usize) else { return false };
1327    let mut seen = HashSet::new();
1328    moving(func, cfg, loops, id, leaf, next, &mut seen)
1329}
1330
1331/// A pointer with the constant `ptr_add`s on the front of it taken off, and how many bytes they came
1332/// to between them.
1333fn peeled(func: &Func, pointer: Value) -> (Value, i128) {
1334    let mut at = pointer;
1335    let mut offset = 0;
1336    while let Some(by) = operand_of(func, at, Opcode::PtrAdd, 1) {
1337        let (Some(step), Some(of)) = (constant(func, by), operand_of(func, at, Opcode::PtrAdd, 0))
1338        else {
1339            break;
1340        };
1341        offset += step;
1342        at = of;
1343    }
1344    (at, offset)
1345}
1346
1347/// A pointer with every `ptr_add` on the front of it taken off, and whether any of them moved it by
1348/// an amount that is not a number.
1349///
1350/// [`peeled`] stops at a step that is not a number, because what it is working out is a fixed
1351/// distance and a step nobody wrote down is not one. This does not stop, because what it is working
1352/// out is where the address came from, and a step nobody wrote down is still a step off something.
1353/// That the step was there at all is the second thing it hands back, since a displacement the
1354/// program computed is one of the ways an address stops being something the analysis follows.
1355fn beneath(func: &Func, pointer: Value) -> (Value, bool) {
1356    let mut at = pointer;
1357    let mut worked = false;
1358    while let Some(of) = operand_of(func, at, Opcode::PtrAdd, 0) {
1359        let by = operand_of(func, at, Opcode::PtrAdd, 1);
1360        worked = worked || by.is_some_and(|by| constant(func, by).is_none());
1361        at = of;
1362    }
1363    (at, worked)
1364}
1365
1366/// What the analysis stopped on, for an address it had nothing to say about.
1367///
1368/// [`NOT_FOLLOWED`] used to be one row and it is the largest in the census, which made it the least
1369/// useful thing in there: a number that big is a list of different problems, and the row said which
1370/// pass gave up rather than what it gave up on. So the address is taken apart once more here, at the
1371/// point the reason is finally reported, and what is underneath it is what gets named.
1372///
1373/// The header parameter is looked at first and looked through, because a pointer the loop carries is
1374/// the interesting case and what it is depends on what comes back round the latch rather than on the
1375/// parameter. A load there is `p = p->next`, which is the walk over a linked structure the census
1376/// wants counted on its own: nothing in this pass will ever split one, since the guard tests a
1377/// distance and the next node of a list is its own object.
1378fn stopped(func: &Func, loops: &Loops, id: LoopId, latch: Block, pointer: Value) -> &'static str {
1379    let (base, worked) = beneath(func, pointer);
1380    // Only the load is named over the back edge. What else can come back is an address the loop
1381    // worked out some other way, and where that was worked out is the question the rest of this
1382    // answers, so naming it here as well would be the same answer written in two places.
1383    if let Some(next) = round(func, loops, id, latch, base) {
1384        if shape(func, beneath(func, next).0) == ADDRESS_FROM_MEMORY {
1385            return WALKS_A_STRUCTURE;
1386        }
1387    }
1388    let named = shape(func, base);
1389    if named != NOT_FOLLOWED {
1390        return named;
1391    }
1392    // Nothing to say about the pointer the address is built on, so what is left to say is how far
1393    // along it the address is. That is worth its own row because it is a different thing to fix:
1394    // the pointer is fine and the subscript is what nothing here can count.
1395    if worked { STEP_NOT_FOLLOWED } else { NOT_FOLLOWED }
1396}
1397
1398/// The value a header parameter is handed on the way back round, if the pointer is one.
1399///
1400/// [`carried`] does this walk to decide whether to refuse and this one does it to decide what to
1401/// say, which is why neither calls the other: that one wants to know if what comes back is the
1402/// parameter moved, and this one wants the value itself.
1403fn round(func: &Func, loops: &Loops, id: LoopId, latch: Block, pointer: Value) -> Option<Value> {
1404    let Def::Param { block, index } = func[pointer].def else { return None };
1405    if block != loops.header(id) {
1406        return None;
1407    }
1408    let term = func.terminator(latch)?;
1409    copy::edge_args(func, term, block).get(index as usize).copied()
1410}
1411
1412/// Where a pointer with nothing on the front of it came from, said as one of the census rows.
1413fn shape(func: &Func, base: Value) -> &'static str {
1414    let Def::Result { inst, .. } = func[base].def else { return NOT_FOLLOWED };
1415    match func[inst].opcode {
1416        Opcode::Load => ADDRESS_FROM_MEMORY,
1417        Opcode::Call | Opcode::CallIndirect => ADDRESS_FROM_A_CALL,
1418        Opcode::Select => ADDRESS_FROM_A_CHOICE,
1419        _ => NOT_FOLLOWED,
1420    }
1421}
1422
1423/// Whether a value is a header parameter moved by some number of bytes.
1424///
1425/// The conditions are [`measured`]'s and the walk is the obvious one. False is a value that is not
1426/// the parameter moved, which is a refusal, and true is the parameter moved by amounts this does not
1427/// need to know. It used to hand back the largest step it saw, which sized how far the runtime was
1428/// asked to look, and nothing is sized by a step any more.
1429fn moving(
1430    func: &Func,
1431    cfg: &Cfg,
1432    loops: &Loops,
1433    id: LoopId,
1434    param: Value,
1435    value: Value,
1436    seen: &mut HashSet<Value>,
1437) -> bool {
1438    if value == param {
1439        return true;
1440    }
1441    // A value already on the way back is one this has been through, and coming back round to it is
1442    // what a walk through a join looks like. Not a refusal, because this path holds nothing that has
1443    // not been looked at.
1444    if !seen.insert(value) {
1445        return true;
1446    }
1447    let at = match func[value].def {
1448        Def::Result { inst, .. } => match func.block_of(inst) {
1449            Some(block) => block,
1450            None => return false,
1451        },
1452        Def::Param { block, .. } => block,
1453    };
1454    // Anything defined outside the loop is something the loop was handed rather than the parameter
1455    // moved, and it is where the walk stops as well as what it refuses. A value defined in a loop
1456    // inside this one is refused by the same test and it is refused for a stronger reason: what it
1457    // does is a question about the inner loop's iterations rather than about this one's.
1458    if loops.innermost(at) != Some(id) {
1459        return false;
1460    }
1461    match func[value].def {
1462        Def::Result { inst, .. } => {
1463            let args = &func[func[inst].args];
1464            match func[inst].opcode {
1465                Opcode::PtrAdd => match (args.first(), args.get(1)) {
1466                    (Some(&of), Some(_)) => moving(func, cfg, loops, id, param, of, seen),
1467                    _ => false,
1468                },
1469                // Both arms have to be the parameter moved, since either of them may be the one
1470                // taken. The condition is not looked at, because how the loop chose is not something
1471                // the displacement depends on.
1472                Opcode::Select => match (args.get(1), args.get(2)) {
1473                    (Some(&one), Some(&two)) => {
1474                        moving(func, cfg, loops, id, param, one, seen)
1475                            && moving(func, cfg, loops, id, param, two, seen)
1476                    }
1477                    _ => false,
1478                },
1479                _ => false,
1480            }
1481        }
1482        // A parameter of a block inside the loop is a join, and every way into it has to be the
1483        // parameter moved. The header is not one of them: its other parameters are other values and
1484        // the parameter itself was the base case above.
1485        Def::Param { block, index } => {
1486            if block == loops.header(id) {
1487                return false;
1488            }
1489            let mut moved = true;
1490            for &pred in cfg.predecessors(block) {
1491                let Some(term) = func.terminator(pred) else { return false };
1492                let args = copy::edge_args(func, term, block);
1493                let Some(&came) = args.get(index as usize) else { return false };
1494                moved = moved && moving(func, cfg, loops, id, param, came, seen);
1495            }
1496            moved
1497        }
1498    }
1499}
1500
1501/// Whether a pointer and a byte displacement beside it are the two the address is really built out
1502/// of, rather than two values an expression happened to end up holding.
1503///
1504/// The displacement has to end up as wide as the arithmetic, because what is built from it here is
1505/// a `ptr_add` in a preheader. It gets there one of three ways: it is a plain number, or it is
1506/// already sixty four bits, or it is narrower and the invariant says which extension it is read
1507/// through, which is what an index the caller handed in looks like in C, where the index is an
1508/// `int`.
1509fn walks(func: &Func, base: Anchor, apart: Plain) -> bool {
1510    let word = Type::int(64);
1511    if !base.value().is_none_or(|base| func[base].ty.is_ptr()) {
1512        return false;
1513    }
1514    // A global with nothing but a number beside it, which is what a walk over a file scope array
1515    // from a fixed place in it looks like. A number is as wide as it needs to be.
1516    let Some(value) = apart.value.filter(|_| apart.scale != 0) else { return true };
1517    match apart.read {
1518        None => func[value].ty == word,
1519        Some(read) => read.to == word && func[value].ty.is_int() && func[value].ty.bits() < 64,
1520    }
1521}
1522
1523/// Makes the two halves and the block that chooses between them.
1524///
1525/// The order matters in two places. The copy is made before anything is rewired, so the copy's back
1526/// edge is remapped to the copy's own header rather than to a guard that did not exist yet. The
1527/// checks come out of the fast half last, so the copy still has them.
1528fn apply(func: &mut Func, plan: &Plan) {
1529    // The slow half, which is the loop as it stands, under a substitution that renames everything it
1530    // defines. Nothing is seeded, so its header gets parameters of its own, which is what a copy
1531    // reached from a block that also reaches the original needs.
1532    let mut renamed: HashMap<Value, Value> = HashMap::new();
1533    let copies = copy::blocks(func, &plan.body, &mut renamed);
1534    let slow = copies[&plan.header];
1535
1536    let Choice { ok, windows } = limited(func, plan);
1537
1538    // Nothing in the loop moves, so which half runs is settled in the preheader and settled for
1539    // good. There is no guard block and nothing carried round: the way into the loop is the choice.
1540    if windows.is_empty() {
1541        let term = func.terminator(plan.preheader).expect("a preheader ends in a jump");
1542        let args = copy::edge_args(func, term, plan.header);
1543        func.remove_inst(term);
1544        Builder::new(func, plan.preheader).br_if(ok, plan.header, &args, slow, &args);
1545        take(func, plan);
1546        return;
1547    }
1548
1549    // The guard, which takes over the header's place: the preheader arrives here, the back edge
1550    // comes back to here, and the header is reached from here and nowhere else. Its first
1551    // parameters are offsets of its own, one per distinct step, because where the loop's own
1552    // pointers are is not something this pass has to find and a loop with several ways out may
1553    // have nothing that walks in step with what its checks are about.
1554    //
1555    // A measured offset gets no parameter and nothing carried round. Where its pointer is now is
1556    // worked out from the parameters below, which are the ones the header carries, either by being
1557    // one of them outright or by the guard writing the arithmetic out again.
1558    let word = Type::int(64);
1559    let counting: Vec<i128> =
1560        windows.iter().filter(|window| window.from.is_none()).map(|w| stepped(w.key)).collect();
1561    let types: Vec<Type> = func[plan.header].params.iter().map(|&param| func[param].ty).collect();
1562    let guard = func.create_block();
1563    let offsets: Vec<Value> = counting.iter().map(|_| func.append_param(guard, word)).collect();
1564    let carried: Vec<Value> = types.iter().map(|&ty| func.append_param(guard, ty)).collect();
1565
1566    // Unsigned, because the window is a byte count and so is the offset, and because unsigned is
1567    // what the rule the removal rests on is written in. That is what makes the subtraction below
1568    // safe as well: a pointer that went under where it started comes out as a displacement no
1569    // window is ever going to hold, so the loop goes to the half that kept its checks.
1570    let held: HashMap<Value, Value> =
1571        func[plan.header].params.iter().copied().zip(carried.iter().copied()).collect();
1572    // Nothing built here has to be moved afterwards, unlike in the preheader: the guard is a block
1573    // this pass just made and it has no terminator yet, so appending puts things in the order they
1574    // were built and the branch at the end goes on last. `spent` is where the builder drops what it
1575    // made and nothing reads it back.
1576    let mut build = Builder::new(func, guard);
1577    let mut spent = Vec::new();
1578    let mut inside: Option<Value> = None;
1579    let mut counted = 0;
1580    for window in &windows {
1581        let offset = match window.from {
1582            None => {
1583                let offset = offsets[counted];
1584                counted += 1;
1585                offset
1586            }
1587            Some(from) => {
1588                let Key::From(at) = window.key else {
1589                    unreachable!("only a measured window holds where its pointer began")
1590                };
1591                let here = remade(&mut build, &mut spent, &window.rebuild, at, &held);
1592                let now = build.unary(Opcode::PtrToInt, here, word);
1593                build.binary(Opcode::Sub, now, from, Flags::NONE)
1594            }
1595        };
1596        let under = build.icmp(IntPred::Ule, offset, window.bound);
1597        inside = Some(match inside {
1598            None => under,
1599            Some(so_far) => build.binary(Opcode::And, so_far, under, Flags::NONE),
1600        });
1601    }
1602    let inside = inside.expect("a plan with a window has at least one of them");
1603    build.br_if(inside, plan.header, &carried, slow, &carried);
1604
1605    // The way in, which tests whether the fast half may run at all and starts every offset at the
1606    // first access. A loop nothing fits in never reaches the guard.
1607    let term = func.terminator(plan.preheader).expect("a preheader ends in a jump to the header");
1608    let args = copy::edge_args(func, term, plan.header);
1609    func.remove_inst(term);
1610    let mut build = Builder::new(func, plan.preheader);
1611    let zero = build.iconst(word, 0);
1612    let mut into: Vec<Value> = offsets.iter().map(|_| zero).collect();
1613    into.extend_from_slice(&args);
1614    build.br_if(ok, guard, &into, slow, &args);
1615
1616    // The way round, which walks each counted offset on by its step. The offsets are the guard's
1617    // parameters and the guard dominates every block in the fast half, so the latch may read them.
1618    // `nuw` rather than `nsw` because [`bounded`] held the window short of where this could wrap,
1619    // and it held it there in unsigned terms. A measured offset has nothing here: the guard reads
1620    // the pointer the loop already hands round.
1621    let term = func.terminator(plan.latch).expect("a latch ends in a branch back to the header");
1622    let mut build = Builder::new(func, plan.latch);
1623    let mut made = Vec::new();
1624    let mut next = Vec::new();
1625    for (&offset, &step) in offsets.iter().zip(&counting) {
1626        let by = build.iconst(word, step);
1627        made.push(by);
1628        let walked = build.binary(Opcode::Add, offset, by, Flags::NUW);
1629        made.push(walked);
1630        next.push(walked);
1631    }
1632    for value in made {
1633        let inst = inst_of(func, value);
1634        func.remove_inst(inst);
1635        func.insert_before(inst, term);
1636    }
1637    route(func, term, plan.header, guard, &next);
1638    take(func, plan);
1639}
1640
1641/// Takes the checks the fast half does not need out of it.
1642///
1643/// The `cap_of` each one was reading is left where it is, for `dce` after this pass to take away,
1644/// which is the arrangement [`crate::hoist`] and [`crate::discharge`] are both in.
1645fn take(func: &mut Func, plan: &Plan) {
1646    for sweep in &plan.sweeps {
1647        func.remove_inst(sweep.check);
1648    }
1649}
1650
1651/// Sends every edge this terminator has to `from` to `to` instead, with more arguments in front.
1652fn route(func: &mut Func, term: Inst, from: Block, to: Block, first: &[Value]) {
1653    for at in func.target_list(term).iter() {
1654        let call = func[at];
1655        if call.block != from {
1656            continue;
1657        }
1658        let mut args = first.to_vec();
1659        args.extend_from_slice(&func[call.args]);
1660        let args = func.push_values(&args);
1661        func.set_block_call(at, BlockCall { block: to, args, ..call });
1662    }
1663}
1664
1665/// One offset the guard works out every time round, and how far it may get.
1666struct Window {
1667    /// Which checks share it, which for a counted offset is how far the address moves each time
1668    /// round. That is a magnitude, because the offset counts bytes from the first access and counts
1669    /// them the same way whichever direction the address walks.
1670    key: Key,
1671    /// The highest offset an access may start at and still be inside what the extent covers.
1672    bound: Value,
1673    /// Where the pointer was on the way into the loop, as an integer, for an offset the guard
1674    /// measures. `None` for one it counts, which starts at zero and needs nothing to measure from.
1675    from: Option<Value>,
1676    /// What the guard writes again to know where the pointer is now, operands before uses. Empty
1677    /// for a counted offset, and empty for a measured one off a parameter the header carries, since
1678    /// the guard carries that parameter itself. See [`writable`].
1679    rebuild: Vec<Value>,
1680}
1681
1682/// How the two halves are chosen between, which depends on whether any address in the loop moves.
1683struct Choice {
1684    /// Whether every check in the loop fits at all, which the preheader tests before it enters the
1685    /// fast half. It is false for a dangling pointer or an object smaller than the thing being read
1686    /// out of it, and then the fast half runs no iterations and the check in the slow half reports
1687    /// the fault at the access rather than at the loop.
1688    ok: Value,
1689    /// One per distinct step, and empty when no address in the loop moves. A loop like that needs
1690    /// no guard block and nothing carried round it, because `ok` is the whole answer and it does
1691    /// not change while the loop runs.
1692    windows: Vec<Window>,
1693}
1694
1695/// Builds what the preheader has to work out before either half can run.
1696///
1697/// One `cap_extent` per check and what it leaves room for, all of it in the preheader in front of
1698/// the jump into the loop. A builder appends to the end of a block, which in a block that already
1699/// has its terminator is after it, so everything is built first and then moved in front of the
1700/// terminator in the order it was built.
1701///
1702/// # Why the window is bytes and not iterations
1703///
1704/// This used to work out how many iterations a check allows, which is `(extent - reach) / step + 1`
1705/// clamped at zero, and count iterations against it. The claim that has to hold for the fast half
1706/// to be allowed to drop its checks was then that `i * step + reach <= extent` for every `i` below
1707/// that limit, which has a symbolic multiply and a symbolic divide in it at sixty four bits, and
1708/// z3 does not finish on it in two and a half minutes in any of three formulations. So the whole
1709/// transformation sat outside the rule table that `spec/safe-memory/07-check-elimination.md`
1710/// section 7.7 asks every elimination to be inside, and it sat there for a solver reason rather
1711/// than a design one, which is the worst kind.
1712///
1713/// Counting bytes instead of iterations takes the arithmetic out. The offset the loop is at moves
1714/// by `step` each time round exactly as the address does, the window is `extent - reach`, and the
1715/// claim is that an offset at or below that plus the reach is inside the extent. No multiply and no
1716/// divide, and it is the claim `swept.sym.i64` in `crates/rucc-opt/rules/safety.rules` already
1717/// makes, which [`windowed`] asks. The pass earns that rule's hypotheses rather than assuming them:
1718/// `ok` is where `extent` is held to be at least `reach`, so the window cannot have wrapped, and
1719/// [`bounded`] is where the offset is held short of where adding one more step would.
1720///
1721/// It is also less code. A loop with one step in it loses a divide from its preheader and carries
1722/// the same one value round that it did before.
1723///
1724/// # Why one window per step and not one per check
1725///
1726/// Two checks that walk by the same amount are at the same offset on every iteration, so they can
1727/// share the offset and the smaller of their two windows. On SQLite 127 of the 268 loops this
1728/// splits have one distinct step and five have two, so this is one value round the loop almost
1729/// always and two occasionally.
1730fn limited(func: &mut Func, plan: &Plan) -> Choice {
1731    let word = Type::int(64);
1732    let term = func.terminator(plan.preheader).expect("a preheader ends in a jump to the header");
1733    // What the preheader hands the header, which is where a measured offset is measured from. Read
1734    // before the builder exists, because reading it borrows the function.
1735    let entering = copy::edge_args(func, term, plan.header);
1736    // What the preheader has in place of each parameter the header carries, which is what a measured
1737    // address is written again out of to get the first iteration's.
1738    let swap: HashMap<Value, Value> =
1739        func[plan.header].params.iter().copied().zip(entering.iter().copied()).collect();
1740    let mut made = Vec::new();
1741    let mut build = Builder::new(func, plan.preheader);
1742
1743    let mut ok: Option<Value> = None;
1744    let mut windows: Vec<Window> = Vec::new();
1745    // Every measured address written once, since the same expression under the same substitution is
1746    // the same value and two checks off one pointer are the commonest thing here.
1747    let mut begun: HashMap<Value, Value> = HashMap::new();
1748    // Every question asked once, for the same reason. See [`Asked`].
1749    let mut asked = Asked::default();
1750    for sweep in &plan.sweeps {
1751        let base = match sweep.walk {
1752            Walk::By(_) => anchored(&mut build, &mut made, sweep.base),
1753            Walk::Again { at, .. } => match begun.get(&at) {
1754                Some(&had) => had,
1755                None => {
1756                    let first = remade(&mut build, &mut made, &sweep.rebuild, at, &swap);
1757                    begun.insert(at, first);
1758                    first
1759                }
1760            },
1761        };
1762        let (window, zero, also) = spare(&mut build, &mut made, sweep, base, &mut asked);
1763        // Every check has to fit for the fast half to be the one that runs, and this is where the
1764        // hypothesis the rule is asked under is earned: a window worked out from an extent smaller
1765        // than the reach is one that wrapped, and none of what follows would mean anything.
1766        let fits = build.icmp(IntPred::Sge, window, zero);
1767        made.push(fits);
1768        // What the sweep asked for beside that, which is nothing on all but the ones [`trailing`]
1769        // took and is the gap being at or above zero on those.
1770        let fits = match also {
1771            None => fits,
1772            Some(more) => {
1773                let both = build.binary(Opcode::And, fits, more, Flags::NONE);
1774                made.push(both);
1775                both
1776            }
1777        };
1778        ok = Some(match ok {
1779            None => fits,
1780            Some(so_far) => {
1781                let both = build.binary(Opcode::And, so_far, fits, Flags::NONE);
1782                made.push(both);
1783                both
1784            }
1785        });
1786        if sweep.walk.still() {
1787            continue;
1788        }
1789        // Two checks that walk by the same amount are at the same offset on every iteration, so
1790        // they share the offset and the smaller of their two windows. The amount is a magnitude,
1791        // which is what lets a walk up and a walk down by eight share one offset: the offset counts
1792        // bytes from the first access and both of them are eight bytes further along each time
1793        // round. Which way they went is in the window each of them worked out, and taking the
1794        // smaller of two windows is no different for being about two directions.
1795        //
1796        // Two checks the guard measures share for the same reason and by the other key. A fixed
1797        // distance from one pointer is a fixed distance from it on every iteration, so both of them
1798        // moved by whatever that pointer moved by and one subtraction answers for the pair.
1799        let key = sweep.walk.key();
1800        match windows.iter().position(|held| held.key == key) {
1801            Some(at) => {
1802                let bound = windows[at].bound;
1803                let smaller = build.icmp(IntPred::Ult, window, bound);
1804                made.push(smaller);
1805                let least = build.select(smaller, window, bound);
1806                made.push(least);
1807                windows[at].bound = least;
1808            }
1809            None => {
1810                // Where a measured offset is measured from, worked out once in the preheader
1811                // because it is the same address on every iteration by definition.
1812                let from = match key {
1813                    Key::Every(_) => None,
1814                    Key::From(_) => {
1815                        let from = build.unary(Opcode::PtrToInt, base, word);
1816                        made.push(from);
1817                        Some(from)
1818                    }
1819                };
1820                let rebuild = if from.is_some() { sweep.rebuild.clone() } else { Vec::new() };
1821                windows.push(Window { key, bound: window, from, rebuild });
1822            }
1823        }
1824    }
1825    let ok = ok.expect("a plan holds at least one check");
1826
1827    for window in &mut windows {
1828        window.bound = bounded(&mut build, &mut made, stepped(window.key), window.bound);
1829    }
1830
1831    for value in made {
1832        let inst = inst_of(func, value);
1833        func.remove_inst(inst);
1834        func.insert_before(inst, term);
1835    }
1836    Choice { ok, windows }
1837}
1838
1839/// How much the offset goes up by between one test and the next, which is nothing for one the guard
1840/// measures.
1841///
1842/// A measured offset is worked out from the pointer every time round rather than added to, so it is
1843/// never one step past anything and there is no step to leave room for. What it can be is enormous,
1844/// when the pointer went below where it started and the subtraction came out as a huge unsigned
1845/// number, and that is the answer wanted: the guard is meant to hand a loop like that to the half
1846/// that kept its checks.
1847fn stepped(key: Key) -> i128 {
1848    match key {
1849        Key::Every(step) => step,
1850        Key::From(_) => 0,
1851    }
1852}
1853
1854/// Holds a window short of where one more step would take the offset out of sixty four bits.
1855///
1856/// The offset goes up by the step every time round and is tested afterwards, so it reaches one step
1857/// past the window before the guard sends the loop to the other half. Nothing else here bounds the
1858/// window: `cap_extent` answers with no more than it was asked for, and what it was asked for is a
1859/// trip count times a step, which saturates rather than refusing. An offset that wrapped would come
1860/// back small, the guard would let it through, and the fast half would read past the end of the
1861/// object with nothing left in it to say so.
1862///
1863/// One comparison and one select in the preheader, and the value it clamps to is so far past any
1864/// object a program allocates that this never fires. It is here because the failure it stops is
1865/// silent.
1866fn bounded(build: &mut Builder<'_>, made: &mut Vec<Value>, step: i128, bound: Value) -> Value {
1867    let word = Type::int(64);
1868    let room = build.iconst(word, i128::from(i64::MAX) - step);
1869    made.push(room);
1870    let over = build.icmp(IntPred::Ugt, bound, room);
1871    made.push(over);
1872    let held = build.select(over, room, bound);
1873    made.push(held);
1874    held
1875}
1876
1877/// Whether one offset at or below the window is one whose access is inside the extent.
1878///
1879/// This function decides nothing. It builds the term `swept.sym.i64` is written about and asks the
1880/// table, which is section 7.7's split: the pass established the window and carries the offset, and
1881/// whether an offset inside the window means an access inside the object is somebody's proof rather
1882/// than this file's opinion. It is the same rule [`crate::hoist`] asks about a loop whose extent the
1883/// program works out, and it is the same question, since a window is a hoisted check's far end under
1884/// another name.
1885///
1886/// Four of its five arguments are opaque. The address, the extent and the window are values the pass
1887/// does not have as numbers, and the offset is whichever iteration the reader cares about, which is
1888/// how one question comes to be about all of them. The rule's three hypotheses about that pair are
1889/// what [`limited`] and [`bounded`] earn.
1890///
1891/// A walk from high to low asks `swept.down.sym.i64` instead, which is the same claim written about
1892/// addresses that go the other way. Asking the ascending rule and subtracting somewhere in the pass
1893/// would be arithmetic on the thing being proved, which is what section 7.7 exists to stop, so the
1894/// direction picks a term and the table answers about that term or does not.
1895fn windowed(reach: i128, down: bool) -> bool {
1896    let mut question = Question::default();
1897    let at = question.opaque();
1898    let at = question.app("value.i64", &[at]);
1899    let span = question.opaque();
1900    let span = question.app("value.i64", &[span]);
1901    let far = question.opaque();
1902    let far = question.app("value.i64", &[far]);
1903    let reach = question.number(reach);
1904    let reach = question.app("iconst.i64", &[reach]);
1905    let delta = question.opaque();
1906    let delta = question.app("value.i64", &[delta]);
1907    let head = if down { "swept.down.sym.i64" } else { "swept.sym.i64" };
1908    let term = question.app(head, &[at, span, far, reach, delta]);
1909    match safety::TABLE.find(&question, term) {
1910        Some(found) => yes(&safety::TABLE, found.rule),
1911        None => false,
1912    }
1913}
1914
1915/// The base as a value here, writing the address of a global out again when that is what it is.
1916///
1917/// One instruction, and the same one the loop has inside it. Working it out again is why
1918/// [`crate::licm`] leaves the one in the loop alone, and it is why the address can be described
1919/// rather than named in the first place.
1920fn anchored(build: &mut Builder<'_>, made: &mut Vec<Value>, base: Anchor) -> Value {
1921    match base {
1922        Anchor::Value(value) => value,
1923        Anchor::Address(symbol) => {
1924            let extra = Extra::Symbol(symbol);
1925            let at =
1926                build.value(InstData { extra, ..InstData::new(Opcode::GlobalAddr) }, Type::PTR);
1927            made.push(at);
1928            at
1929        }
1930    }
1931}
1932
1933/// How far the first access sits past the base, as a value, or `None` when it sits on it.
1934///
1935/// Wrapping arithmetic throughout, because this is the address the loop was going to compute
1936/// anyway. The flags a `nsw` would put on it would be a promise about the caller's index, and what
1937/// this is building is a question for the runtime rather than an address anything reads.
1938fn displacement(build: &mut Builder<'_>, made: &mut Vec<Value>, apart: Plain) -> Option<Value> {
1939    let word = Type::int(64);
1940    let mut sum = match apart.value.filter(|_| apart.scale != 0) {
1941        None => {
1942            return (apart.offset != 0).then(|| {
1943                let by = build.iconst(word, apart.offset);
1944                made.push(by);
1945                by
1946            });
1947        }
1948        Some(value) => value,
1949    };
1950    // The extension the invariant describes, emitted before anything is done with the value. It
1951    // comes first because everything after it is arithmetic at the wide type and the value is not
1952    // that width yet.
1953    if let Some(read) = apart.read {
1954        let widen = match read.reading {
1955            Reading::Signed => Opcode::SExt,
1956            Reading::Unsigned => Opcode::ZExt,
1957        };
1958        sum = build.unary(widen, sum, read.to);
1959        made.push(sum);
1960    }
1961    if apart.scale != 1 {
1962        let by = build.iconst(word, apart.scale);
1963        made.push(by);
1964        sum = build.binary(Opcode::Mul, sum, by, Flags::NONE);
1965        made.push(sum);
1966    }
1967    if apart.offset != 0 {
1968        let by = build.iconst(word, apart.offset);
1969        made.push(by);
1970        sum = build.binary(Opcode::Add, sum, by, Flags::NONE);
1971        made.push(sum);
1972    }
1973    Some(sum)
1974}
1975
1976/// How many bytes past the first access belong to whatever owns it, and a zero to compare that with.
1977///
1978/// The question both callers rest on. `extent - reach` is negative when the first access does not
1979/// fit at all, zero when exactly one fits, and how much room there is for further ones otherwise.
1980///
1981/// # A walk from high to low
1982///
1983/// The offset the guard carries is a magnitude, so a loop whose address goes down is a loop whose
1984/// offset goes up in exactly the same way and everything built around the offset is untouched. What
1985/// changes is which end of the object is asked about. An ascending walk starts at the first access
1986/// and runs off the top of it, so `cap_extent` at the first address is the question. A descending
1987/// one starts at the first access and runs off the bottom, so the question is `cap_extent_back` at
1988/// the end of the first access, which is `first + reach`.
1989///
1990/// Anchoring at the end rather than at `first` is what makes the two the same shape. The answer is
1991/// then how many bytes below the end of the first access belong to the same thing, the window is
1992/// that less the reach exactly as above, and the access on iteration `delta` is the `reach` bytes
1993/// ending at `first + reach - delta`. That is the claim `swept.down.sym.i64` is written about, with
1994/// `at` being the end of the first access, and it is a claim about every iteration for the same
1995/// reason the ascending one is.
1996///
1997/// # Asking once
1998///
1999/// [`spare`] runs once per sweep, and a loop that walks one pointer has a bounds check, a liveness
2000/// check and a derivation check on it, so the same question about the same address used to be asked
2001/// three times over and after tamnd/rucc#869 more often than that. On SQLite that came to 4184 calls
2002/// to the runtime for 591 split loops, which is seven per loop, and `a-string-scan` had five in one
2003/// preheader at one address. [`Asked`] is what makes it one. Two questions built out of the same
2004/// pieces are the same question here, because the whole of what this builds sits in one block that
2005/// has no call in it, so nothing between two of them can change what the second one would answer.
2006///
2007/// [`crate::number`] would say the same thing about the arithmetic and cannot say it about the query,
2008/// which has effects, and in any case it runs before this pass rather than after it, so there is
2009/// nothing behind this that would tidy up after it.
2010fn spare(
2011    build: &mut Builder<'_>,
2012    made: &mut Vec<Value>,
2013    sweep: &Sweep,
2014    base: Value,
2015    asked: &mut Asked,
2016) -> (Value, Value, Option<Value>) {
2017    let word = Type::int(64);
2018    let first = match asked.first(base, sweep.apart) {
2019        Some(had) => had,
2020        None => {
2021            let first = match displacement(build, made, sweep.apart) {
2022                None => base,
2023                Some(by) => {
2024                    let args = build.func().push_values(&[base, by]);
2025                    let data = InstData::new(Opcode::PtrAdd);
2026                    let sum = build.value(InstData { args, ..data }, Type::PTR);
2027                    made.push(sum);
2028                    sum
2029                }
2030            };
2031            asked.firsts.push(((base, sweep.apart), first));
2032            first
2033        }
2034    };
2035    // How far the runtime is asked to look, which is as far as the arithmetic carries. The answer
2036    // is a true count of the bytes that belong to the object, never more than the truth and never
2037    // more than what was asked for, so a smaller ask is a smaller window and a smaller window is
2038    // fewer iterations in the half that has no checks in it. There is nothing on the other side of
2039    // that trade any more. The query probes the far end of what it was asked for and halves rather
2040    // than walking, about twenty five reads of the plane whatever the number is, so the price does
2041    // not turn on the number and the largest ask is the right one.
2042    let want = asked.number(build, made, i128::from(i64::MAX));
2043
2044    // Where the question is asked from, which for a walk that goes down is the end of the first
2045    // access rather than its start. The arithmetic wraps, in the way [`displacement`] wraps and for
2046    // the same reason: this is an address the loop was going to reach anyway and the value is a
2047    // question for the runtime rather than something anything reads through.
2048    let (query, at) = if sweep.walk.down() {
2049        let end = match asked.end(first, sweep.reach) {
2050            Some(had) => had,
2051            None => {
2052                let by = asked.number(build, made, sweep.reach);
2053                let args = build.func().push_values(&[first, by]);
2054                let data = InstData::new(Opcode::PtrAdd);
2055                let end = build.value(InstData { args, ..data }, Type::PTR);
2056                made.push(end);
2057                asked.ends.push(((first, sweep.reach), end));
2058                end
2059            }
2060        };
2061        (Opcode::CapExtentBack, end)
2062    } else {
2063        (Opcode::CapExtent, first)
2064    };
2065
2066    let extent = match asked.extent(query, at, want) {
2067        Some(had) => had,
2068        None => {
2069            let args = build.func().push_values(&[at]);
2070            let data = InstData::new(Opcode::CapOf);
2071            let capability = build.value(InstData { args, ..data }, Type::CAP);
2072            made.push(capability);
2073            let args = build.func().push_values(&[capability, at, want]);
2074            let extent = build.value(InstData { args, ..InstData::new(query) }, word);
2075            made.push(extent);
2076            asked.extents.push(((query, at, want), extent));
2077            extent
2078        }
2079    };
2080
2081    let reach = asked.number(build, made, sweep.reach);
2082    let left = build.binary(Opcode::Sub, extent, reach, Flags::NSW);
2083    made.push(left);
2084    let zero = asked.number(build, made, 0);
2085
2086    // The gap [`trailing`] left for the guard to work out, which is how far into the window the
2087    // walk's first access sits. Taking it off the window is what makes the window one about the
2088    // walk again, and asking it to be at or above zero is what says the walk begins inside the
2089    // object the window was measured in rather than somewhere below it.
2090    let Some(ahead) = sweep.ahead.and_then(|ahead| displacement(build, made, ahead)) else {
2091        return (left, zero, None);
2092    };
2093    let short = build.binary(Opcode::Sub, left, ahead, Flags::NSW);
2094    made.push(short);
2095    let above = build.icmp(IntPred::Sge, ahead, zero);
2096    made.push(above);
2097    (short, zero, Some(above))
2098}
2099
2100/// What the preheader has worked out already, so that one question is asked once.
2101///
2102/// Association lists rather than maps, because a plan holds a handful of sweeps and the keys are
2103/// what scalar evolution hands out, which is `Eq` and not `Hash`. Looking a key up walks the list,
2104/// and the longest list on SQLite is a dozen entries.
2105#[derive(Default)]
2106struct Asked {
2107    /// Numbers written down, by the number.
2108    numbers: Vec<(i128, Value)>,
2109    /// Where the first access is, by the base it is measured from and how far past it it sits.
2110    firsts: Vec<((Value, Plain), Value)>,
2111    /// The end of a first access, by where it starts and how many bytes it is.
2112    ends: Vec<((Value, i128), Value)>,
2113    /// What the runtime answered, by which end was asked, about which address and how far.
2114    extents: Vec<((Opcode, Value, Value), Value)>,
2115}
2116
2117impl Asked {
2118    /// A number written down in the preheader, once per number.
2119    fn number(&mut self, build: &mut Builder<'_>, made: &mut Vec<Value>, imm: i128) -> Value {
2120        if let Some(&(_, had)) = self.numbers.iter().find(|&&(seen, _)| seen == imm) {
2121            return had;
2122        }
2123        let value = build.iconst(Type::int(64), imm);
2124        made.push(value);
2125        self.numbers.push((imm, value));
2126        value
2127    }
2128
2129    /// The first access off this base and this far past it, if it has been worked out.
2130    fn first(&self, base: Value, apart: Plain) -> Option<Value> {
2131        self.firsts.iter().find(|&&(key, _)| key == (base, apart)).map(|&(_, had)| had)
2132    }
2133
2134    /// The end of this first access, if it has been worked out.
2135    fn end(&self, first: Value, reach: i128) -> Option<Value> {
2136        self.ends.iter().find(|&&(key, _)| key == (first, reach)).map(|&(_, had)| had)
2137    }
2138
2139    /// What the runtime said about this address, if it has been asked.
2140    fn extent(&self, query: Opcode, at: Value, want: Value) -> Option<Value> {
2141        self.extents.iter().find(|&&(key, _)| key == (query, at, want)).map(|&(_, had)| had)
2142    }
2143}
2144
2145#[cfg(test)]
2146mod tests {
2147    use rucc_base::Interner;
2148    use rucc_ir::{
2149        Block, Builder, Extra, Flags, Func, Inst, InstData, IntPred, MemInfo, MemOrder, Module,
2150        Opcode, Restrict, Signature, Type, Value, verify_func,
2151    };
2152    use rucc_target::{TargetInfo, Triple};
2153
2154    use super::{SPLIT, Split};
2155    use crate::canon::Canon;
2156    use crate::stats::Kind;
2157    use crate::{Fuel, Pass, Stats};
2158
2159    /// How many times the loop goes round, and how wide each element of the walk is.
2160    const TRIPS: i128 = 16;
2161    const WIDTH: i128 = 4;
2162
2163    /// A counted loop that reads one element each time round and can stop on what it read.
2164    ///
2165    /// ```text
2166    /// entry(a): jump head(0)
2167    /// head(i):  p = a + i*4; check_bounds cap_of(p), p; v = load p
2168    ///           br v == 0 -> done, more
2169    /// more:     next = i + 1; br next < 16 -> head(next), done
2170    /// done:     ret
2171    /// ```
2172    ///
2173    /// The second way out is the point. Hoisting refuses this loop, because a loop that can stop in
2174    /// the middle reads fewer bytes than its count says and one check in front of it for all of them
2175    /// would refuse a program that was right. Splitting does not care, because the count it reads is
2176    /// only ever an upper limit on how far to look.
2177    fn leaving() -> (Interner, Func, Vec<Block>) {
2178        walking(Some(TRIPS), Flags::NSW)
2179    }
2180
2181    /// The same loop, with how many times it goes round handed in rather than written down.
2182    ///
2183    /// A loop whose count is an expression rather than a number, which this pass no longer reads and
2184    /// which is still worth a test of its own: the shape has to split like any other and the guard
2185    /// has to come out the same as the one a written down count gets.
2186    fn counting() -> (Interner, Func, Vec<Block>) {
2187        walking(None, Flags::NSW)
2188    }
2189
2190    /// The same loop again, with an increment that promises nothing, so nobody counts it.
2191    ///
2192    /// What `-fwrapv` produces, and the shape a great deal of real code is in. Hoisting refuses it,
2193    /// because a count that rests on the counter not wrapping is not a count it may size a check
2194    /// with. This pass sizes nothing with a count, so it takes it.
2195    fn uncounted() -> (Interner, Func, Vec<Block>) {
2196        walking(Some(TRIPS), Flags::NONE)
2197    }
2198
2199    /// The same loop, reading from an index the caller handed in rather than from zero.
2200    ///
2201    /// `a[start + i]`, whose first address is `a + 4 * start`: a pointer and a displacement, with a
2202    /// number for neither of them. This is the shape the pass used to give up on, and it is a
2203    /// common one, because a loop over part of an array is written this way and so is every walk
2204    /// that begins where the last one stopped. See #810.
2205    fn from_an_index() -> (Interner, Func, Vec<Block>) {
2206        let mut names = Interner::new();
2207        let params = [Type::PTR, Type::int(64)];
2208        let mut func = Func::new(names.intern("f"), Signature::new().with_params(&params));
2209        let entry = func.create_block();
2210        let head = func.create_block();
2211        let more = func.create_block();
2212        let done = func.create_block();
2213        let array = func.append_param(entry, Type::PTR);
2214        let start = func.append_param(entry, Type::int(64));
2215        let counter = func.append_param(head, Type::int(64));
2216
2217        let zero = Builder::new(&mut func, entry).iconst(Type::int(64), 0);
2218        Builder::new(&mut func, entry).jump(head, &[zero]);
2219
2220        let mut build = Builder::new(&mut func, head);
2221        let index = build.binary(Opcode::Add, counter, start, Flags::NSW);
2222        let by = build.iconst(Type::int(64), WIDTH);
2223        let scaled = build.binary(Opcode::Mul, index, by, Flags::NSW);
2224        let args = build.func().push_values(&[array, scaled]);
2225        let pointer = build.value(InstData { args, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
2226        check(&mut build, pointer);
2227        let read = build.load(Type::int(32), pointer, mem(), Flags::NONE);
2228        let nothing = build.iconst(Type::int(32), 0);
2229        let stop = build.icmp(IntPred::Eq, read, nothing);
2230        build.br_if(stop, done, &[], more, &[]);
2231
2232        let mut build = Builder::new(&mut func, more);
2233        let one = build.iconst(Type::int(64), 1);
2234        let next = build.binary(Opcode::Add, counter, one, Flags::NSW);
2235        let limit = build.iconst(Type::int(64), TRIPS);
2236        let again = build.icmp(IntPred::Slt, next, limit);
2237        build.br_if(again, head, &[next], done, &[]);
2238        Builder::new(&mut func, done).ret(&[]);
2239        (names, func, vec![entry, head, more, done])
2240    }
2241
2242    /// The same loop over a file scope array, with the `global_addr` inside the loop.
2243    ///
2244    /// Which is where one sits, because working the address out again costs a single instruction
2245    /// and `crate::licm` would rather do that than hold it in a register the whole way round. So
2246    /// the address of the array is not a value defined outside the loop and never will be, and the
2247    /// pass has to take it from where it is or not at all. See #810.
2248    fn over_a_global() -> (Interner, Func, Vec<Block>) {
2249        let mut names = Interner::new();
2250        let tab = names.intern("tab");
2251        let mut func = Func::new(names.intern("f"), Signature::new());
2252        let entry = func.create_block();
2253        let head = func.create_block();
2254        let more = func.create_block();
2255        let done = func.create_block();
2256        let counter = func.append_param(head, Type::int(64));
2257
2258        let zero = Builder::new(&mut func, entry).iconst(Type::int(64), 0);
2259        Builder::new(&mut func, entry).jump(head, &[zero]);
2260
2261        let mut build = Builder::new(&mut func, head);
2262        let by = build.iconst(Type::int(64), WIDTH);
2263        let scaled = build.binary(Opcode::Mul, counter, by, Flags::NSW);
2264        let extra = Extra::Symbol(tab);
2265        let array = build.value(InstData { extra, ..InstData::new(Opcode::GlobalAddr) }, Type::PTR);
2266        let args = build.func().push_values(&[array, scaled]);
2267        let pointer = build.value(InstData { args, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
2268        check(&mut build, pointer);
2269        let read = build.load(Type::int(32), pointer, mem(), Flags::NONE);
2270        let nothing = build.iconst(Type::int(32), 0);
2271        let stop = build.icmp(IntPred::Eq, read, nothing);
2272        build.br_if(stop, done, &[], more, &[]);
2273
2274        let mut build = Builder::new(&mut func, more);
2275        let one = build.iconst(Type::int(64), 1);
2276        let next = build.binary(Opcode::Add, counter, one, Flags::NSW);
2277        let limit = build.iconst(Type::int(64), TRIPS);
2278        let again = build.icmp(IntPred::Slt, next, limit);
2279        build.br_if(again, head, &[next], done, &[]);
2280        Builder::new(&mut func, done).ret(&[]);
2281        (names, func, vec![entry, head, more, done])
2282    }
2283
2284    /// The same loop again, with the index in `int` and sign extended, which is what C gives.
2285    ///
2286    /// `a[start + i]` with `start` and `i` both `int`. The front end adds them at thirty two bits
2287    /// and sign extends the sum before scaling it, so the first thing scalar evolution meets is the
2288    /// extension of a chrec whose base is a value rather than a number. Splitting takes it because
2289    /// the widened base is described rather than named, and this pass emits the extension in the
2290    /// preheader. See #810.
2291    fn from_a_narrow_index() -> (Interner, Func, Vec<Block>) {
2292        let mut names = Interner::new();
2293        let params = [Type::PTR, Type::int(32)];
2294        let mut func = Func::new(names.intern("f"), Signature::new().with_params(&params));
2295        let entry = func.create_block();
2296        let head = func.create_block();
2297        let more = func.create_block();
2298        let done = func.create_block();
2299        let array = func.append_param(entry, Type::PTR);
2300        let start = func.append_param(entry, Type::int(32));
2301        let counter = func.append_param(head, Type::int(32));
2302
2303        let zero = Builder::new(&mut func, entry).iconst(Type::int(32), 0);
2304        Builder::new(&mut func, entry).jump(head, &[zero]);
2305
2306        let mut build = Builder::new(&mut func, head);
2307        let index = build.binary(Opcode::Add, counter, start, Flags::NSW);
2308        let wide = build.unary(Opcode::SExt, index, Type::int(64));
2309        let by = build.iconst(Type::int(64), WIDTH);
2310        let scaled = build.binary(Opcode::Mul, wide, by, Flags::NSW);
2311        let args = build.func().push_values(&[array, scaled]);
2312        let pointer = build.value(InstData { args, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
2313        check(&mut build, pointer);
2314        let read = build.load(Type::int(32), pointer, mem(), Flags::NONE);
2315        let nothing = build.iconst(Type::int(32), 0);
2316        let stop = build.icmp(IntPred::Eq, read, nothing);
2317        build.br_if(stop, done, &[], more, &[]);
2318
2319        let mut build = Builder::new(&mut func, more);
2320        let one = build.iconst(Type::int(32), 1);
2321        let next = build.binary(Opcode::Add, counter, one, Flags::NSW);
2322        let limit = build.iconst(Type::int(32), TRIPS);
2323        let again = build.icmp(IntPred::Slt, next, limit);
2324        build.br_if(again, head, &[next], done, &[]);
2325        Builder::new(&mut func, done).ret(&[]);
2326        (names, func, vec![entry, head, more, done])
2327    }
2328
2329    /// The same loop again, walking from the end of the array down to the start of it.
2330    ///
2331    /// ```text
2332    /// entry(a): jump head(15)
2333    /// head(i):  p = a + i*4; check_bounds cap_of(p), p; v = load p
2334    ///           br v == 0 -> done, more
2335    /// more:     next = i - 1; br next >= 0 -> head(next), done
2336    /// done:     ret
2337    /// ```
2338    ///
2339    /// The step is minus four, so the first access is the highest address the loop touches and every
2340    /// later one is below it. What the pass has to ask about is room under the first access rather
2341    /// than over it, which is `cap_extent_back` at the end of that access. See #680.
2342    fn downwards() -> (Interner, Func, Vec<Block>) {
2343        let mut names = Interner::new();
2344        let mut func = Func::new(names.intern("f"), Signature::new().with_params(&[Type::PTR]));
2345        let entry = func.create_block();
2346        let head = func.create_block();
2347        let more = func.create_block();
2348        let done = func.create_block();
2349        let array = func.append_param(entry, Type::PTR);
2350        let counter = func.append_param(head, Type::int(64));
2351
2352        let last = Builder::new(&mut func, entry).iconst(Type::int(64), TRIPS - 1);
2353        Builder::new(&mut func, entry).jump(head, &[last]);
2354
2355        let mut build = Builder::new(&mut func, head);
2356        let by = build.iconst(Type::int(64), WIDTH);
2357        let scaled = build.binary(Opcode::Mul, counter, by, Flags::NSW);
2358        let args = build.func().push_values(&[array, scaled]);
2359        let pointer = build.value(InstData { args, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
2360        check(&mut build, pointer);
2361        let read = build.load(Type::int(32), pointer, mem(), Flags::NONE);
2362        let nothing = build.iconst(Type::int(32), 0);
2363        let stop = build.icmp(IntPred::Eq, read, nothing);
2364        build.br_if(stop, done, &[], more, &[]);
2365
2366        let mut build = Builder::new(&mut func, more);
2367        let one = build.iconst(Type::int(64), 1);
2368        let next = build.binary(Opcode::Sub, counter, one, Flags::NSW);
2369        let floor = build.iconst(Type::int(64), 0);
2370        let again = build.icmp(IntPred::Sge, next, floor);
2371        build.br_if(again, head, &[next], done, &[]);
2372        Builder::new(&mut func, done).ret(&[]);
2373        (names, func, vec![entry, head, more, done])
2374    }
2375
2376    /// A scanner whose pointer moves by one byte or by two, depending on what it just read.
2377    ///
2378    /// ```text
2379    /// entry(a): jump head(a)
2380    /// head(p):  check_bounds cap_of(p), p; v = load p
2381    ///           br v == 0 -> done, more
2382    /// more:     br v < 0 -> two, one
2383    /// one:      jump back(p + 1)
2384    /// two:      jump back(p + 2)
2385    /// back(q):  jump head(q)
2386    /// done:     ret
2387    /// ```
2388    ///
2389    /// What a UTF-8 walk looks like, and what half of SQLite's text handling looks like. There is no
2390    /// step to speak of, so scalar evolution says nothing and the guard has to measure how far the
2391    /// pointer got rather than count how far it should have got. See #810.
2392    fn by_what_it_read() -> (Interner, Func, Vec<Block>) {
2393        let mut names = Interner::new();
2394        let mut func = Func::new(names.intern("f"), Signature::new().with_params(&[Type::PTR]));
2395        let entry = func.create_block();
2396        let head = func.create_block();
2397        let more = func.create_block();
2398        let one = func.create_block();
2399        let two = func.create_block();
2400        let back = func.create_block();
2401        let done = func.create_block();
2402        let text = func.append_param(entry, Type::PTR);
2403        let at = func.append_param(head, Type::PTR);
2404        let next = func.append_param(back, Type::PTR);
2405
2406        Builder::new(&mut func, entry).jump(head, &[text]);
2407
2408        let mut build = Builder::new(&mut func, head);
2409        checking(&mut build, at, byte());
2410        let read = build.load(Type::int(8), at, byte(), Flags::NONE);
2411        let nothing = build.iconst(Type::int(8), 0);
2412        let stop = build.icmp(IntPred::Eq, read, nothing);
2413        build.br_if(stop, done, &[], more, &[]);
2414
2415        let mut build = Builder::new(&mut func, more);
2416        let wide = build.icmp(IntPred::Slt, read, nothing);
2417        build.br_if(wide, two, &[], one, &[]);
2418
2419        for (block, step) in [(one, 1), (two, 2)] {
2420            let mut build = Builder::new(&mut func, block);
2421            let by = build.iconst(Type::int(64), step);
2422            let args = build.func().push_values(&[at, by]);
2423            let far = build.value(InstData { args, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
2424            build.jump(back, &[far]);
2425        }
2426
2427        Builder::new(&mut func, back).jump(head, &[next]);
2428        Builder::new(&mut func, done).ret(&[]);
2429        (names, func, vec![entry, head, more, one, two, back, done])
2430    }
2431
2432    /// A walk whose address is a pointer the header carries plus an index it also carries.
2433    ///
2434    /// ```text
2435    /// entry(a, n): jump head(a, 0)
2436    /// head(p, i):  x = i & 7; q = p + x
2437    ///              check_bounds cap_of(q), q
2438    ///              j = i + 1; f = p + 8
2439    ///              br j < n -> head(f, j), done
2440    /// done:        ret
2441    /// ```
2442    ///
2443    /// The `and` is what stops scalar evolution: `i` walks by one and `i & 7` does not walk by
2444    /// anything, so the address is not an induction variable and nothing counts it. It is still a
2445    /// function of what the header carries, so the guard can write the two instructions out again
2446    /// from its own parameters and the preheader can write them out again from what it passes. See
2447    /// #810.
2448    ///
2449    /// A `load` in place of the `and` is the same fixture with the answer the other way, which is
2450    /// `x_came_out_of_memory` below.
2451    fn from_what_it_carries(reading: bool) -> (Interner, Func, Vec<Block>) {
2452        let word = Type::int(64);
2453        let mut names = Interner::new();
2454        let mut func =
2455            Func::new(names.intern("f"), Signature::new().with_params(&[Type::PTR, word]));
2456        let entry = func.create_block();
2457        let head = func.create_block();
2458        let done = func.create_block();
2459        let text = func.append_param(entry, Type::PTR);
2460        let count = func.append_param(entry, word);
2461        let at = func.append_param(head, Type::PTR);
2462        let index = func.append_param(head, word);
2463
2464        let mut build = Builder::new(&mut func, entry);
2465        let zero = build.iconst(word, 0);
2466        build.jump(head, &[text, zero]);
2467
2468        let mut build = Builder::new(&mut func, head);
2469        let spread = if reading {
2470            build.load(word, at, mem(), Flags::NONE)
2471        } else {
2472            let mask = build.iconst(word, 7);
2473            build.binary(Opcode::And, index, mask, Flags::NONE)
2474        };
2475        let args = build.func().push_values(&[at, spread]);
2476        let pointer = build.value(InstData { args, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
2477        checking(&mut build, pointer, byte());
2478        let one = build.iconst(word, 1);
2479        let next = build.binary(Opcode::Add, index, one, Flags::NSW);
2480        let by = build.iconst(word, 8);
2481        let args = build.func().push_values(&[at, by]);
2482        let far = build.value(InstData { args, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
2483        let again = build.icmp(IntPred::Slt, next, count);
2484        build.br_if(again, head, &[far, next], done, &[]);
2485        Builder::new(&mut func, done).ret(&[]);
2486        (names, func, vec![entry, head, done])
2487    }
2488
2489    /// A walk down a linked list, where the next pointer is read out of the current node.
2490    ///
2491    /// ```text
2492    /// entry(a): jump head(a)
2493    /// head(p):  check_bounds cap_of(p), p; v = load p
2494    ///           br v == 0 -> done, more
2495    /// more:     q = load p + 8; jump head(q)
2496    /// done:     ret
2497    /// ```
2498    ///
2499    /// The case measuring does not take. Not because subtracting the two nodes would be wrong, but
2500    /// because the second one is its own object, so the guard would send every iteration after the
2501    /// first to the slow half and the split would be two copies of the loop for nothing. See #810.
2502    fn down_a_list() -> (Interner, Func, Vec<Block>) {
2503        let mut names = Interner::new();
2504        let mut func = Func::new(names.intern("f"), Signature::new().with_params(&[Type::PTR]));
2505        let entry = func.create_block();
2506        let head = func.create_block();
2507        let more = func.create_block();
2508        let done = func.create_block();
2509        let list = func.append_param(entry, Type::PTR);
2510        let at = func.append_param(head, Type::PTR);
2511
2512        Builder::new(&mut func, entry).jump(head, &[list]);
2513
2514        let mut build = Builder::new(&mut func, head);
2515        checking(&mut build, at, byte());
2516        let read = build.load(Type::int(8), at, byte(), Flags::NONE);
2517        let nothing = build.iconst(Type::int(8), 0);
2518        let stop = build.icmp(IntPred::Eq, read, nothing);
2519        build.br_if(stop, done, &[], more, &[]);
2520
2521        let mut build = Builder::new(&mut func, more);
2522        let by = build.iconst(Type::int(64), 8);
2523        let args = build.func().push_values(&[at, by]);
2524        let field = build.value(InstData { args, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
2525        let next = build.load(Type::PTR, field, mem(), Flags::NONE);
2526        build.jump(head, &[next]);
2527        Builder::new(&mut func, done).ret(&[]);
2528        (names, func, vec![entry, head, more, done])
2529    }
2530
2531    /// Builds the loop, with the exit test against a number or against a second parameter.
2532    /// The same loop as [`walking`], with the counter starting at a number the caller handed in.
2533    ///
2534    /// `a[start + i]` for `i` from nothing up to `TRIPS`, which is the shape an inner loop over a
2535    /// row of a matrix has once the outer loop's subscript is folded into the start. What it gives
2536    /// the pass is a walk whose displacement off the array is a value rather than a number.
2537    fn offsetting(flags: Flags) -> (Interner, Func, Vec<Block>) {
2538        let mut names = Interner::new();
2539        let word = Type::int(64);
2540        let params = vec![Type::PTR, word];
2541        let mut func = Func::new(names.intern("f"), Signature::new().with_params(&params));
2542        let entry = func.create_block();
2543        let head = func.create_block();
2544        let more = func.create_block();
2545        let done = func.create_block();
2546        let array = func.append_param(entry, Type::PTR);
2547        let start = func.append_param(entry, word);
2548        let counter = func.append_param(head, word);
2549
2550        Builder::new(&mut func, entry).jump(head, &[start]);
2551
2552        let mut build = Builder::new(&mut func, head);
2553        let by = build.iconst(word, WIDTH);
2554        let scaled = build.binary(Opcode::Mul, counter, by, Flags::NSW);
2555        let args = build.func().push_values(&[array, scaled]);
2556        let pointer = build.value(InstData { args, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
2557        check(&mut build, pointer);
2558        let read = build.load(Type::int(32), pointer, mem(), Flags::NONE);
2559        let nothing = build.iconst(Type::int(32), 0);
2560        let stop = build.icmp(IntPred::Eq, read, nothing);
2561        build.br_if(stop, done, &[], more, &[]);
2562
2563        let mut build = Builder::new(&mut func, more);
2564        let one = build.iconst(word, 1);
2565        let next = build.binary(Opcode::Add, counter, one, flags);
2566        let times = build.iconst(word, TRIPS);
2567        let limit = build.binary(Opcode::Add, start, times, Flags::NSW);
2568        let again = build.icmp(IntPred::Slt, next, limit);
2569        build.br_if(again, head, &[next], done, &[]);
2570        Builder::new(&mut func, done).ret(&[]);
2571        (names, func, vec![entry, head, more, done])
2572    }
2573
2574    fn walking(times: Option<i128>, flags: Flags) -> (Interner, Func, Vec<Block>) {
2575        let mut names = Interner::new();
2576        let mut params = vec![Type::PTR];
2577        params.extend(times.is_none().then_some(Type::int(64)));
2578        let mut func = Func::new(names.intern("f"), Signature::new().with_params(&params));
2579        let entry = func.create_block();
2580        let head = func.create_block();
2581        let more = func.create_block();
2582        let done = func.create_block();
2583        let array = func.append_param(entry, Type::PTR);
2584        let handed = times.is_none().then(|| func.append_param(entry, Type::int(64)));
2585        let counter = func.append_param(head, Type::int(64));
2586
2587        let zero = Builder::new(&mut func, entry).iconst(Type::int(64), 0);
2588        Builder::new(&mut func, entry).jump(head, &[zero]);
2589
2590        let mut build = Builder::new(&mut func, head);
2591        let by = build.iconst(Type::int(64), WIDTH);
2592        let scaled = build.binary(Opcode::Mul, counter, by, Flags::NSW);
2593        let args = build.func().push_values(&[array, scaled]);
2594        let pointer = build.value(InstData { args, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
2595        check(&mut build, pointer);
2596        let read = build.load(Type::int(32), pointer, mem(), Flags::NONE);
2597        let nothing = build.iconst(Type::int(32), 0);
2598        let stop = build.icmp(IntPred::Eq, read, nothing);
2599        build.br_if(stop, done, &[], more, &[]);
2600
2601        let mut build = Builder::new(&mut func, more);
2602        let one = build.iconst(Type::int(64), 1);
2603        let next = build.binary(Opcode::Add, counter, one, flags);
2604        let limit = match (times, handed) {
2605            (Some(times), _) => build.iconst(Type::int(64), times),
2606            (None, handed) => handed.expect("a loop with no number for a limit was handed one"),
2607        };
2608        let again = build.icmp(IntPred::Slt, next, limit);
2609        build.br_if(again, head, &[next], done, &[]);
2610        Builder::new(&mut func, done).ret(&[]);
2611        (names, func, vec![entry, head, more, done])
2612    }
2613
2614    /// Builds a loop with two ways out that meet again, so neither way out dominates the meeting.
2615    ///
2616    /// A parameter at each exit is what section 26.4 asks for and it does not reach this on its own.
2617    /// Both exits grow one and a use at the join still names the value the loop defined, because a
2618    /// parameter is only a name where its block dominates.
2619    fn joining() -> (Interner, Func, Vec<Block>) {
2620        let mut names = Interner::new();
2621        let params = [Type::PTR, Type::int(64)];
2622        let mut func = Func::new(names.intern("f"), Signature::new().with_params(&params));
2623        let entry = func.create_block();
2624        let head = func.create_block();
2625        let more = func.create_block();
2626        let left = func.create_block();
2627        let right = func.create_block();
2628        let join = func.create_block();
2629        let array = func.append_param(entry, Type::PTR);
2630        let handed = func.append_param(entry, Type::int(64));
2631        let counter = func.append_param(head, Type::int(64));
2632
2633        let zero = Builder::new(&mut func, entry).iconst(Type::int(64), 0);
2634        Builder::new(&mut func, entry).jump(head, &[zero]);
2635
2636        let mut build = Builder::new(&mut func, head);
2637        let by = build.iconst(Type::int(64), WIDTH);
2638        let scaled = build.binary(Opcode::Mul, counter, by, Flags::NSW);
2639        let args = build.func().push_values(&[array, scaled]);
2640        let pointer = build.value(InstData { args, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
2641        check(&mut build, pointer);
2642        let read = build.load(Type::int(32), pointer, mem(), Flags::NONE);
2643        let nothing = build.iconst(Type::int(32), 0);
2644        let stop = build.icmp(IntPred::Eq, read, nothing);
2645        build.br_if(stop, left, &[], more, &[]);
2646
2647        let mut build = Builder::new(&mut func, more);
2648        let one = build.iconst(Type::int(64), 1);
2649        let next = build.binary(Opcode::Add, counter, one, Flags::NSW);
2650        let again = build.icmp(IntPred::Slt, next, handed);
2651        build.br_if(again, head, &[next], right, &[]);
2652
2653        Builder::new(&mut func, left).jump(join, &[]);
2654        Builder::new(&mut func, right).jump(join, &[]);
2655        Builder::new(&mut func, join).ret(&[]);
2656        (names, func, vec![entry, head, more, left, right, join])
2657    }
2658
2659    /// Builds two loops one after the other, the second starting from where the first stopped.
2660    ///
2661    /// The guard the second one gets is worked out from where its walk starts, which is a value the
2662    /// first loop defines, and splitting the first loop is what stops that being one value.
2663    fn one_after_another() -> (Interner, Func, Vec<Block>) {
2664        let mut names = Interner::new();
2665        let params = [Type::PTR, Type::int(64)];
2666        let mut func = Func::new(names.intern("f"), Signature::new().with_params(&params));
2667        let entry = func.create_block();
2668        let head = func.create_block();
2669        let more = func.create_block();
2670        let over = func.create_block();
2671        let next = func.create_block();
2672        let again = func.create_block();
2673        let done = func.create_block();
2674        let array = func.append_param(entry, Type::PTR);
2675        let limit = func.append_param(entry, Type::int(64));
2676        let first = func.append_param(head, Type::int(64));
2677        let second = func.append_param(next, Type::int(64));
2678
2679        let zero = Builder::new(&mut func, entry).iconst(Type::int(64), 0);
2680        Builder::new(&mut func, entry).jump(head, &[zero]);
2681
2682        let mut build = Builder::new(&mut func, head);
2683        let args = build.func().push_values(&[array, first]);
2684        let at = build.value(InstData { args, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
2685        checking(&mut build, at, byte());
2686        let read = build.load(Type::int(8), at, byte(), Flags::NONE);
2687        let nothing = build.iconst(Type::int(8), 0);
2688        let stop = build.icmp(IntPred::Eq, read, nothing);
2689        build.br_if(stop, over, &[], more, &[]);
2690
2691        let mut build = Builder::new(&mut func, more);
2692        let one = build.iconst(Type::int(64), 1);
2693        let step = build.binary(Opcode::Add, first, one, Flags::NSW);
2694        build.jump(head, &[step]);
2695
2696        Builder::new(&mut func, over).jump(next, &[first]);
2697
2698        let mut build = Builder::new(&mut func, next);
2699        let args = build.func().push_values(&[array, second]);
2700        let here = build.value(InstData { args, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
2701        checking(&mut build, here, byte());
2702        let seen = build.load(Type::int(8), here, byte(), Flags::NONE);
2703        let blank = build.iconst(Type::int(8), 32);
2704        let over_too = build.icmp(IntPred::Eq, seen, blank);
2705        build.br_if(over_too, done, &[], again, &[]);
2706
2707        let mut build = Builder::new(&mut func, again);
2708        let one = build.iconst(Type::int(64), 1);
2709        let onward = build.binary(Opcode::Add, second, one, Flags::NSW);
2710        let go = build.icmp(IntPred::Slt, onward, limit);
2711        build.br_if(go, next, &[onward], done, &[]);
2712
2713        Builder::new(&mut func, done).ret(&[]);
2714        (names, func, vec![entry, head, more, over, next, again, done])
2715    }
2716
2717    /// Builds a loop with a loop inside it, each of them reading the array it was handed.
2718    ///
2719    /// The outer loop reads one element per outer iteration, which is a check in its own blocks. The
2720    /// inner loop reads one per inner iteration, and whether that one is checked is the argument, so
2721    /// that the same nest can be a nest whose inner loop is worth splitting and one whose is not.
2722    fn nested(inner_reads: bool) -> (Interner, Func, Vec<Block>) {
2723        let mut names = Interner::new();
2724        let params = [Type::PTR, Type::int(64), Type::int(64)];
2725        let mut func = Func::new(names.intern("f"), Signature::new().with_params(&params));
2726        let entry = func.create_block();
2727        let outer = func.create_block();
2728        let inner = func.create_block();
2729        let round = func.create_block();
2730        let after = func.create_block();
2731        let done = func.create_block();
2732        let array = func.append_param(entry, Type::PTR);
2733        let rows = func.append_param(entry, Type::int(64));
2734        let columns = func.append_param(entry, Type::int(64));
2735        let row = func.append_param(outer, Type::int(64));
2736        let column = func.append_param(inner, Type::int(64));
2737
2738        let zero = Builder::new(&mut func, entry).iconst(Type::int(64), 0);
2739        Builder::new(&mut func, entry).jump(outer, &[zero]);
2740
2741        let mut build = Builder::new(&mut func, outer);
2742        let by = build.iconst(Type::int(64), WIDTH);
2743        let scaled = build.binary(Opcode::Mul, row, by, Flags::NSW);
2744        let args = build.func().push_values(&[array, scaled]);
2745        let at = build.value(InstData { args, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
2746        check(&mut build, at);
2747        build.load(Type::int(32), at, mem(), Flags::NONE);
2748        let start = build.iconst(Type::int(64), 0);
2749        build.jump(inner, &[start]);
2750
2751        let mut build = Builder::new(&mut func, inner);
2752        let wide = build.iconst(Type::int(64), WIDTH);
2753        let along = build.binary(Opcode::Mul, column, wide, Flags::NSW);
2754        let args = build.func().push_values(&[array, along]);
2755        let here = build.value(InstData { args, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
2756        if inner_reads {
2757            check(&mut build, here);
2758            build.load(Type::int(32), here, mem(), Flags::NONE);
2759        }
2760        build.jump(round, &[]);
2761
2762        let mut build = Builder::new(&mut func, round);
2763        let one = build.iconst(Type::int(64), 1);
2764        let onward = build.binary(Opcode::Add, column, one, Flags::NSW);
2765        let more = build.icmp(IntPred::Slt, onward, columns);
2766        build.br_if(more, inner, &[onward], after, &[]);
2767
2768        let mut build = Builder::new(&mut func, after);
2769        let one = build.iconst(Type::int(64), 1);
2770        let next = build.binary(Opcode::Add, row, one, Flags::NSW);
2771        let again = build.icmp(IntPred::Slt, next, rows);
2772        build.br_if(again, outer, &[next], done, &[]);
2773
2774        Builder::new(&mut func, done).ret(&[]);
2775        (names, func, vec![entry, outer, inner, round, after, done])
2776    }
2777
2778    /// Builds a nest whose outer loop reads at an address the inner loop worked out.
2779    ///
2780    /// The check is in the outer loop's own blocks, so it is one the outer guard would speak for,
2781    /// but the offset it reads at is defined inside the inner loop. That value is not the same
2782    /// number wherever it is read and it is not a parameter of the outer header, so neither the
2783    /// guard nor the preheader has it in hand, and naming it in either of them names something that
2784    /// does not reach there.
2785    fn reading_what_the_inner_loop_found() -> (Interner, Func, Vec<Block>) {
2786        let mut names = Interner::new();
2787        let params = [Type::PTR, Type::int(64), Type::int(64)];
2788        let mut func = Func::new(names.intern("f"), Signature::new().with_params(&params));
2789        let entry = func.create_block();
2790        let outer = func.create_block();
2791        let inner = func.create_block();
2792        let after = func.create_block();
2793        let done = func.create_block();
2794        let array = func.append_param(entry, Type::PTR);
2795        let rows = func.append_param(entry, Type::int(64));
2796        let columns = func.append_param(entry, Type::int(64));
2797        let row = func.append_param(outer, Type::int(64));
2798        let column = func.append_param(inner, Type::int(64));
2799
2800        let zero = Builder::new(&mut func, entry).iconst(Type::int(64), 0);
2801        Builder::new(&mut func, entry).jump(outer, &[zero]);
2802
2803        let start = Builder::new(&mut func, outer).iconst(Type::int(64), 0);
2804        Builder::new(&mut func, outer).jump(inner, &[start]);
2805
2806        let mut build = Builder::new(&mut func, inner);
2807        let one = build.iconst(Type::int(64), 1);
2808        let onward = build.binary(Opcode::Add, column, one, Flags::NSW);
2809        let more = build.icmp(IntPred::Slt, onward, columns);
2810        build.br_if(more, inner, &[onward], after, &[]);
2811
2812        let mut build = Builder::new(&mut func, after);
2813        let args = build.func().push_values(&[array, onward]);
2814        let at = build.value(InstData { args, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
2815        checking(&mut build, at, byte());
2816        build.load(Type::int(8), at, byte(), Flags::NONE);
2817        let one = build.iconst(Type::int(64), 1);
2818        let next = build.binary(Opcode::Add, row, one, Flags::NSW);
2819        let again = build.icmp(IntPred::Slt, next, rows);
2820        build.br_if(again, outer, &[next], done, &[]);
2821
2822        Builder::new(&mut func, done).ret(&[]);
2823        (names, func, vec![entry, outer, inner, after, done])
2824    }
2825
2826    /// What one access in the loop covers.
2827    fn mem() -> MemInfo {
2828        MemInfo {
2829            size: WIDTH as u64,
2830            align: WIDTH as u32,
2831            order: MemOrder::NotAtomic,
2832            tbaa: None,
2833            owns: 0,
2834            restrict: Restrict::NONE,
2835        }
2836    }
2837
2838    /// What one access covers in a loop that walks a byte at a time.
2839    ///
2840    /// A walk the guard has to measure has to be over something wanting no alignment, because a step
2841    /// nobody wrote down is a step nothing can divide by the alignment. Which is what the loops this
2842    /// reaches look like anyway: they are scanners over text.
2843    fn byte() -> MemInfo {
2844        MemInfo {
2845            size: 1,
2846            align: 1,
2847            order: MemOrder::NotAtomic,
2848            tbaa: None,
2849            owns: 0,
2850            restrict: Restrict::NONE,
2851        }
2852    }
2853
2854    /// Puts `cap_of` and a `check_bounds` at `pointer` into a block.
2855    ///
2856    /// The shape `rucc-safety` emits, written out here rather than reached for, because `rucc-opt`
2857    /// is rank 9 alongside `rucc-safety` and cannot depend on it.
2858    fn check(build: &mut Builder<'_>, pointer: Value) {
2859        checking(build, pointer, mem());
2860    }
2861
2862    /// The same, for an access of some other width.
2863    fn checking(build: &mut Builder<'_>, pointer: Value, info: MemInfo) {
2864        let args = build.func().push_values(&[pointer]);
2865        let capability = build.value(InstData { args, ..InstData::new(Opcode::CapOf) }, Type::CAP);
2866        let args = build.func().push_values(&[capability, pointer]);
2867        let extra = Extra::Mem(build.func().add_mem(info));
2868        build.inst(InstData { args, extra, ..InstData::new(Opcode::CheckBounds) }, &[]);
2869    }
2870
2871    /// Puts the `cap_of` and the `check_deriv` `rucc-safety` writes behind pointer arithmetic into
2872    /// a block, naming `from` as the pointer the arithmetic started from.
2873    ///
2874    /// Built at the end of the block and then moved in front of the terminator, which is what the
2875    /// builder makes easy and is where a check on an address the block works out belongs anyway.
2876    fn deriving(func: &mut Func, block: Block, from: Value, derived: Value) {
2877        let term = func.terminator(block).expect("the block ends in a branch");
2878        let held: Vec<Inst> = func.insts(block).collect();
2879        let mut build = Builder::new(func, block);
2880        let args = build.func().push_values(&[from]);
2881        let capability = build.value(InstData { args, ..InstData::new(Opcode::CapOf) }, Type::CAP);
2882        let stride = build.iconst(Type::int(64), WIDTH);
2883        let args = build.func().push_values(&[capability, from, derived, stride]);
2884        build.inst(InstData { args, ..InstData::new(Opcode::CheckDeriv) }, &[]);
2885        let added: Vec<Inst> = func.insts(block).filter(|inst| !held.contains(inst)).collect();
2886        for inst in added {
2887            func.remove_inst(inst);
2888            func.insert_before(inst, term);
2889        }
2890    }
2891
2892    /// A second walk off the same pointer, stepping by `step` bytes a time round.
2893    ///
2894    /// The counter the header carries scaled by something other than the stride the loop already
2895    /// walks by, which is a pointer following the same anchor at a rate of its own.
2896    fn beside(func: &mut Func, block: Block, from: Value, step: i128) -> Value {
2897        let term = func.terminator(block).expect("the block ends in a branch");
2898        let mul = func
2899            .insts(block)
2900            .find(|&inst| func[inst].opcode == Opcode::Mul)
2901            .expect("the loop scales its counter");
2902        let counter = func[func[mul].args][0];
2903        let mut build = Builder::new(func, block);
2904        let by = build.iconst(Type::int(64), step);
2905        let scaled = build.binary(Opcode::Mul, counter, by, Flags::NSW);
2906        let args = build.func().push_values(&[from, scaled]);
2907        let along = build.value(InstData { args, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
2908        for value in [by, scaled, along] {
2909            let inst = super::inst_of(func, value);
2910            func.remove_inst(inst);
2911            func.insert_before(inst, term);
2912        }
2913        along
2914    }
2915
2916    /// One stride past a pointer, worked out in front of the block's terminator.
2917    fn stepped(func: &mut Func, block: Block, from: Value) -> Value {
2918        let term = func.terminator(block).expect("the block ends in a branch");
2919        let mut build = Builder::new(func, block);
2920        let by = build.iconst(Type::int(64), WIDTH);
2921        let args = build.func().push_values(&[from, by]);
2922        let along = build.value(InstData { args, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
2923        for value in [by, along] {
2924            let inst = super::inst_of(func, value);
2925            func.remove_inst(inst);
2926            func.insert_before(inst, term);
2927        }
2928        along
2929    }
2930
2931    /// The address the loop works out and the pointer it started from.
2932    fn arithmetic(func: &Func, block: Block) -> (Value, Value) {
2933        let add = func
2934            .insts(block)
2935            .find(|&inst| func[inst].opcode == Opcode::PtrAdd)
2936            .expect("the loop works out an address");
2937        let from = func[func[add].args][0];
2938        let derived = func[add].results().next().expect("a ptr_add gives one pointer");
2939        (from, derived)
2940    }
2941
2942    /// Canonicalizes and then splits, with as much fuel as both want.
2943    ///
2944    /// Both, because the pass is written against the shape [`Canon`] leaves, and it is
2945    /// canonicalization that gives the loop the preheader the limit is worked out in.
2946    fn split_up(func: &mut Func) -> Stats {
2947        let mut an = crate::machine::fixtures::analyses();
2948        Canon.run(func, &mut an, &mut Fuel::unlimited());
2949        Split.run(func, &mut an, &mut Fuel::unlimited())
2950    }
2951
2952    #[test]
2953    fn a_loop_whose_result_is_read_after_it_is_put_back_into_closed_form_first() {
2954        // Canonicalization runs a long way in front of this pass and `simplify-cfg` between the two
2955        // undoes some of what it did, which is why the loop here is canonicalized and then broken.
2956        // Both halves would define the value the code after the loop reads, so the pass repairs the
2957        // one loop it is about to copy rather than refusing it or running canonicalization again.
2958        let (mut names, mut func, blocks) = leaving();
2959        let mut an = crate::machine::fixtures::analyses();
2960        Canon.run(&mut func, &mut an, &mut Fuel::unlimited());
2961
2962        let (head, done) = (blocks[1], blocks[3]);
2963        let read = func
2964            .insts(head)
2965            .find(|&inst| func[inst].opcode == Opcode::Load)
2966            .and_then(|inst| func[inst].results().next())
2967            .expect("the loop loads what it walks over");
2968        let term = func.terminator(done).expect("the block after the loop returns");
2969        let sum = Builder::new(&mut func, done).binary(Opcode::Add, read, read, Flags::NONE);
2970        let inst = super::inst_of(&func, sum);
2971        func.remove_inst(inst);
2972        func.insert_before(inst, term);
2973        an.clear();
2974
2975        let stats = Split.run(&mut func, &mut an, &mut Fuel::unlimited());
2976        assert_eq!(stats.count(Kind::Optimized, super::CLOSED_HERE), 1);
2977        assert_eq!(stats.count(Kind::Optimized, SPLIT), 1);
2978        assert_eq!(func[done].params.len(), 1, "the block after the loop took the value in");
2979        assert_eq!(all(&func, Opcode::CheckBounds).len(), 1, "the fast half lost its check");
2980        sound(&func, &mut names);
2981    }
2982
2983    #[test]
2984    fn a_value_read_past_a_join_that_neither_way_out_dominates_is_handed_over_there_as_well() {
2985        // Two ways out of the loop and they meet again, so a parameter at each of them is a name
2986        // the code at the meeting cannot say. The repair puts one there too, which is where the
2987        // iterated dominance frontier comes in, and both halves then hand their own value along.
2988        let (mut names, mut func, blocks) = joining();
2989        let mut an = crate::machine::fixtures::analyses();
2990        Canon.run(&mut func, &mut an, &mut Fuel::unlimited());
2991
2992        let (head, join) = (blocks[1], blocks[5]);
2993        let read = func
2994            .insts(head)
2995            .find(|&inst| func[inst].opcode == Opcode::Load)
2996            .and_then(|inst| func[inst].results().next())
2997            .expect("the loop loads what it walks over");
2998        let term = func.terminator(join).expect("the block the two ways out meet at returns");
2999        let sum = Builder::new(&mut func, join).binary(Opcode::Add, read, read, Flags::NONE);
3000        let inst = super::inst_of(&func, sum);
3001        func.remove_inst(inst);
3002        func.insert_before(inst, term);
3003        an.clear();
3004
3005        let stats = Split.run(&mut func, &mut an, &mut Fuel::unlimited());
3006        assert_eq!(stats.count(Kind::Optimized, super::CLOSED_HERE), 1);
3007        assert_eq!(stats.count(Kind::Optimized, SPLIT), 1);
3008        assert_eq!(stats.count(Kind::Missed, super::ESCAPES), 0);
3009        assert_eq!(func[join].params.len(), 1, "the meeting took the value in as well");
3010        assert_eq!(all(&func, Opcode::CheckBounds).len(), 1, "the fast half lost its check");
3011        sound(&func, &mut names);
3012    }
3013
3014    #[test]
3015    fn a_loop_whose_value_the_next_loops_guard_names_is_left_alone() {
3016        // The second loop starts where the first one stopped, so its guard names a value the first
3017        // loop's body defines. Splitting the first loop would leave that value with one definition
3018        // per half and the guard naming neither, and the repair cannot help because the guard is
3019        // not written down yet. Without the refusal the verifier reports the guard's address as a
3020        // value that arrives at a block and does not reach the use, which is what SQLite hit.
3021        let (mut names, mut func, _) = one_after_another();
3022        let mut an = crate::machine::fixtures::analyses();
3023        Canon.run(&mut func, &mut an, &mut Fuel::unlimited());
3024
3025        let stats = Split.run(&mut func, &mut an, &mut Fuel::unlimited());
3026        sound(&func, &mut names);
3027        assert_eq!(stats.count(Kind::Missed, super::WANTED_ELSEWHERE), 1);
3028        assert_eq!(stats.count(Kind::Optimized, SPLIT), 1);
3029    }
3030
3031    #[test]
3032    fn a_loop_with_a_loop_inside_it_is_split() {
3033        // Nothing about an inner loop makes the copy wrong. The whole nest is copied, the guard goes
3034        // in front of the outer header, and the check in the outer loop's own blocks comes out of
3035        // the fast half. The inner loop reads nothing here, so it plans nothing and does not compete
3036        // with the outer one for the blocks they have in common.
3037        let (mut names, mut func, _) = nested(false);
3038        let stats = split_up(&mut func);
3039        assert_eq!(stats.count(Kind::Optimized, SPLIT), 1);
3040        assert_eq!(stats.count(Kind::Missed, super::NESTED_WITH_ONE), 0);
3041        assert_eq!(all(&func, Opcode::CheckBounds).len(), 1, "the fast half lost its check");
3042        sound(&func, &mut names);
3043    }
3044
3045    #[test]
3046    fn the_inner_loop_is_the_one_split_when_both_of_them_could_be() {
3047        // Both loops plan, and the two plans name the inner loop's blocks between them, so only one
3048        // of them may run. The inner one is kept: its checks run once per inner iteration rather
3049        // than once per outer one, and it is the smaller thing to copy. The outer one is left for
3050        // the next run of the pipeline.
3051        let (mut names, mut func, _) = nested(true);
3052        let stats = split_up(&mut func);
3053        assert_eq!(stats.count(Kind::Optimized, SPLIT), 1);
3054        assert_eq!(stats.count(Kind::Missed, super::NESTED_WITH_ONE), 1);
3055        assert_eq!(stats.count(Kind::Missed, super::INSIDE_A_LOOP), 1);
3056        sound(&func, &mut names);
3057    }
3058
3059    #[test]
3060    fn a_value_the_inner_loop_defined_is_not_one_the_guard_may_write_again() {
3061        // The check is in the outer loop's own blocks, so the guard would speak for it, and the
3062        // offset it reads at came out of the inner loop. Reading that value again in the preheader
3063        // is not writing it again, because it is not the same number wherever it is read, and it is
3064        // not a parameter of the outer header either, so it is neither of the two things the walk
3065        // stops at. Treating it as the first of them puts a name in the guard that does not reach
3066        // there, which the verifier catches, so the address is refused and the check stays.
3067        //
3068        // Canonicalization is what would otherwise hide this, since the repair gives the block after
3069        // the inner loop a parameter for the value and the address then names that instead. It is
3070        // left out here for that reason, and the loop has its preheader written into the fixture.
3071        let (mut names, mut func, _) = reading_what_the_inner_loop_found();
3072        let mut an = crate::machine::fixtures::analyses();
3073        let stats = Split.run(&mut func, &mut an, &mut Fuel::unlimited());
3074        // Soundness first, because it is the stronger of the two: without the refusal the guard and
3075        // the preheader both name the inner loop's value and the verifier says so at each of them.
3076        sound(&func, &mut names);
3077        assert_eq!(stats.count(Kind::Optimized, SPLIT), 0);
3078    }
3079
3080    /// What a value is, when it is a number written down.
3081    fn number(func: &Func, value: Value) -> Option<i128> {
3082        let inst = crate::trip::inst_of(func, value);
3083        if func[inst].opcode != Opcode::IConst {
3084            return None;
3085        }
3086        let Extra::Imm(imm) = func[inst].extra else { return None };
3087        Some(func[imm].signed(func[value].ty))
3088    }
3089
3090    /// Every instruction in the function with this opcode, and the block it is in.
3091    fn all(func: &Func, opcode: Opcode) -> Vec<(Block, Inst)> {
3092        func.blocks()
3093            .flat_map(|block| func.insts(block).map(move |inst| (block, inst)).collect::<Vec<_>>())
3094            .filter(|&(_, inst)| func[inst].opcode == opcode)
3095            .collect()
3096    }
3097
3098    /// Insists the function is one the rest of the compiler may believe.
3099    ///
3100    /// This is what the tests here rest on. The pass makes a second copy of a loop, gives a new
3101    /// block parameters that stand for the old header's, and moves a preheader's worth of
3102    /// arithmetic in front of a terminator that was already there, so whether every value is in
3103    /// scope where it is read is not something reading the code settles.
3104    fn sound(func: &Func, names: &mut Interner) {
3105        let target = TargetInfo::new("x86_64-unknown-linux-gnu".parse::<Triple>().unwrap());
3106        let module = Module::new(names.intern("t.c"), &target);
3107        if let Err(errors) = verify_func(&module, func, names) {
3108            panic!("{errors:#?}");
3109        }
3110    }
3111
3112    #[test]
3113    fn a_loop_that_can_stop_early_is_split_even_though_hoisting_will_not_touch_it() {
3114        // The census row this pass was written for. Of the checks SQLite still carries at -O2, the
3115        // largest group by far is in loops with a second way out, which is exactly the loop here.
3116        let (mut names, mut func, _) = leaving();
3117        let mut an = crate::machine::fixtures::analyses();
3118        Canon.run(&mut func, &mut an, &mut Fuel::unlimited());
3119        let refused = crate::hoist::Hoist.run(&mut func, &mut an, &mut Fuel::unlimited());
3120        assert!(!refused.changed(), "hoisting has nothing to say about this loop");
3121
3122        let stats = Split.run(&mut func, &mut an, &mut Fuel::unlimited());
3123        assert_eq!(stats.count(Kind::Optimized, SPLIT), 1);
3124        sound(&func, &mut names);
3125    }
3126
3127    #[test]
3128    fn the_half_the_loop_runs_first_has_no_check_in_it_and_the_other_one_keeps_it() {
3129        // One check went in and one check came out, and the one that came out is in the copy. That
3130        // is the whole transformation: the same work, with the checking half reached only once the
3131        // guard says the run of safe iterations is over.
3132        let (mut names, mut func, blocks) = leaving();
3133        let head = blocks[1];
3134        split_up(&mut func);
3135
3136        let left = all(&func, Opcode::CheckBounds);
3137        assert_eq!(left.len(), 1, "one check, and it is the one the slow half kept");
3138        assert_ne!(left[0].0, head, "and it is not in the block the loop started in");
3139        sound(&func, &mut names);
3140    }
3141
3142    #[test]
3143    fn the_derivation_check_on_an_index_that_walks_goes_the_way_the_bounds_check_beside_it_goes() {
3144        // `a[i]` is two judgements, one about the arithmetic and one about the access, and the
3145        // window covers both. It covers the arithmetic more easily than the access, since a
3146        // derivation is allowed to land anywhere the access is allowed to and a stride short of
3147        // that as well. Until the guard spoke for it this was the whole of what the fast half of a
3148        // byte at a time loop still had in it.
3149        let (mut names, mut func, blocks) = walking(Some(TRIPS), Flags::NSW);
3150        let (from, derived) = arithmetic(&func, blocks[1]);
3151        deriving(&mut func, blocks[1], from, derived);
3152
3153        let stats = split_up(&mut func);
3154        assert_eq!(stats.count(Kind::Optimized, SPLIT), 1);
3155        assert_eq!(all(&func, Opcode::CheckBounds).len(), 1, "the fast half lost its check");
3156        assert_eq!(all(&func, Opcode::CheckDeriv).len(), 1, "and the derivation check with it");
3157        sound(&func, &mut names);
3158    }
3159
3160    #[test]
3161    fn two_checks_on_one_address_ask_the_runtime_one_question() {
3162        // tamnd/rucc#871. `a[i]` carries a bounds check and a derivation check and the guard sizes
3163        // both of them from the same address, so the preheader called the runtime twice about it.
3164        // What made the two calls different was how many bytes each one said the loop was going to
3165        // read, and that stopped meaning anything when the query stopped walking, so both ask for
3166        // everything now and the second is a value the preheader already has. On `a-string-scan` it
3167        // was five calls at one address.
3168        let (mut names, mut func, blocks) = walking(Some(TRIPS), Flags::NSW);
3169        let (from, derived) = arithmetic(&func, blocks[1]);
3170        deriving(&mut func, blocks[1], from, derived);
3171
3172        let stats = split_up(&mut func);
3173        assert_eq!(stats.count(Kind::Optimized, SPLIT), 1);
3174        assert_eq!(all(&func, Opcode::CapExtent).len(), 1, "one question for the two checks");
3175        sound(&func, &mut names);
3176    }
3177
3178    #[test]
3179    fn a_derivation_check_whose_walk_starts_along_from_the_pointer_it_is_about_is_taken() {
3180        // `&a[i] + 1` walks from a stride past `a`, so a window measured where the walk begins is a
3181        // window about whoever owns that address rather than about whoever owns `a`. Measuring from
3182        // `a` instead and widening the window by the stride answers both: `a` is in it on the first
3183        // iteration and the walk is in it on every one.
3184        let (mut names, mut func, blocks) = walking(Some(TRIPS), Flags::NSW);
3185        let head = blocks[1];
3186        let (from, walked) = arithmetic(&func, head);
3187        let past = stepped(&mut func, head, walked);
3188        deriving(&mut func, head, from, past);
3189
3190        let stats = split_up(&mut func);
3191        assert_eq!(stats.count(Kind::Optimized, SPLIT), 1);
3192        assert_eq!(stats.count(Kind::Missed, super::NOT_FROM_THE_START), 0);
3193        assert_eq!(all(&func, Opcode::CheckDeriv).len(), 1, "the fast half lost the check");
3194        sound(&func, &mut names);
3195    }
3196
3197    #[test]
3198    fn a_derivation_check_whose_pointer_sits_above_the_walk_is_taken() {
3199        // The same thing the other way round. The pointer the check names is a stride past `a` and
3200        // the walk starts on `a`, so the lower of the two is where the walk begins and the window
3201        // is as wide as the gap. Which of the pair is the one that moves does not come into it.
3202        let (mut names, mut func, blocks) = walking(Some(TRIPS), Flags::NSW);
3203        let head = blocks[1];
3204        let (array, walked) = arithmetic(&func, head);
3205        let above = stepped(&mut func, head, array);
3206        deriving(&mut func, head, above, walked);
3207
3208        let stats = split_up(&mut func);
3209        assert_eq!(stats.count(Kind::Optimized, SPLIT), 1);
3210        assert_eq!(stats.count(Kind::Missed, super::NOT_FROM_THE_START), 0);
3211        assert_eq!(all(&func, Opcode::CheckDeriv).len(), 1, "the fast half lost the check");
3212        sound(&func, &mut names);
3213    }
3214
3215    #[test]
3216    fn a_derivation_check_whose_walk_begins_a_handed_distance_into_the_object_is_taken() {
3217        // `a[start + i]`, where the check is about `a` and the walk begins `start` elements in. The
3218        // window goes on `a`, which is the object the check is about, and the guard takes the gap
3219        // off what it measured there and asks for the gap to be at or above zero.
3220        let (mut names, mut func, blocks) = offsetting(Flags::NSW);
3221        let head = blocks[1];
3222        let (array, walked) = arithmetic(&func, head);
3223        deriving(&mut func, head, array, walked);
3224
3225        let stats = split_up(&mut func);
3226        assert_eq!(stats.count(Kind::Optimized, SPLIT), 1);
3227        assert_eq!(stats.count(Kind::Missed, super::NOT_FROM_THE_START), 0);
3228        assert_eq!(all(&func, Opcode::CheckDeriv).len(), 1, "the fast half lost the check");
3229        sound(&func, &mut names);
3230    }
3231
3232    #[test]
3233    fn a_derivation_check_whose_pointer_moves_and_whose_walk_begins_a_handed_distance_in_stays() {
3234        // Both pointers walk and the distance off the array is not a number, so neither window is
3235        // available: the pair cannot be measured against each other and the one that would go on
3236        // the pointer the check names needs that pointer to stand still. It is the gap left over.
3237        let (mut names, mut func, blocks) = offsetting(Flags::NSW);
3238        let head = blocks[1];
3239        let (_, walked) = arithmetic(&func, head);
3240        let past = stepped(&mut func, head, walked);
3241        deriving(&mut func, head, walked, past);
3242
3243        let stats = split_up(&mut func);
3244        assert_eq!(stats.count(Kind::Optimized, SPLIT), 1);
3245        assert_eq!(stats.count(Kind::Missed, super::NOT_FROM_THE_START), 1);
3246        assert_eq!(all(&func, Opcode::CheckDeriv).len(), 2, "the check is in both halves");
3247        sound(&func, &mut names);
3248    }
3249
3250    #[test]
3251    fn a_derivation_check_whose_pointer_walks_at_a_step_of_its_own_stays() {
3252        // The case neither window speaks for. The pointer the check names runs away at twice the
3253        // rate the walk does, so the distance between the two is a different number every time
3254        // round and no window a number of bytes wide holds the pair for more than one iteration.
3255        let (mut names, mut func, blocks) = walking(Some(TRIPS), Flags::NSW);
3256        let head = blocks[1];
3257        let (array, walked) = arithmetic(&func, head);
3258        let faster = beside(&mut func, head, array, 2 * WIDTH);
3259        deriving(&mut func, head, faster, walked);
3260
3261        let stats = split_up(&mut func);
3262        assert_eq!(stats.count(Kind::Optimized, SPLIT), 1);
3263        assert_eq!(stats.count(Kind::Missed, super::NOT_FROM_THE_START), 1);
3264        assert_eq!(all(&func, Opcode::CheckDeriv).len(), 2, "the check is in both halves");
3265        sound(&func, &mut names);
3266    }
3267
3268    #[test]
3269    fn a_derivation_check_whose_own_pointer_walks_beside_the_new_one_is_taken_by_one_window() {
3270        // `p = p + k`, where the pointer the check names is the one that moves, so no window
3271        // measured from a single address speaks for it. One measured from the lower of the two and
3272        // a step and a byte wide holds the pair wherever the walk has got to, and that says the old
3273        // pointer is inside the object and the new one did not leave it. This is `a-string-scan`,
3274        // where the derivation check was the whole of what the fast half still had.
3275        let (mut names, mut func, blocks) = walking(Some(TRIPS), Flags::NSW);
3276        let head = blocks[1];
3277        let (_, walked) = arithmetic(&func, head);
3278        let past = stepped(&mut func, head, walked);
3279        deriving(&mut func, head, walked, past);
3280
3281        let stats = split_up(&mut func);
3282        assert_eq!(stats.count(Kind::Optimized, SPLIT), 1);
3283        assert_eq!(stats.count(Kind::Missed, super::NOT_FROM_THE_START), 0);
3284        assert_eq!(all(&func, Opcode::CheckDeriv).len(), 1, "the fast half lost it");
3285        sound(&func, &mut names);
3286    }
3287
3288    #[test]
3289    fn how_far_the_runtime_is_asked_to_look_is_settled_in_front_of_the_loop() {
3290        // The one thing a compiler cannot work out here is how many bytes belong to the object, so
3291        // it is asked, once, before the loop starts. Once is what makes this worth doing: a query
3292        // per loop in place of a check per iteration.
3293        let (mut names, mut func, _) = leaving();
3294        split_up(&mut func);
3295
3296        let asked = all(&func, Opcode::CapExtent);
3297        assert_eq!(asked.len(), 1, "one question for the one check that was sized");
3298        let cfg = crate::Cfg::new(&func);
3299        let doms = crate::Dominators::new(&cfg);
3300        let loops = crate::Loops::new(&cfg, &doms);
3301        assert!(
3302            loops.all().all(|id| !loops.contains(id, asked[0].0)),
3303            "and it is outside the loop"
3304        );
3305        sound(&func, &mut names);
3306    }
3307
3308    #[test]
3309    fn a_walk_that_starts_at_an_index_the_caller_handed_in_is_split() {
3310        // #810. The first address is `a + 4 * start` and the question has to be put about that
3311        // address rather than about the array, because an extent measured from the array covers
3312        // bytes in front of where the loop begins and would say the walk fits when it does not.
3313        let (mut names, mut func, blocks) = from_an_index();
3314        let stats = split_up(&mut func);
3315        assert_eq!(stats.count(Kind::Optimized, SPLIT), 1);
3316        assert_eq!(all(&func, Opcode::CheckBounds).len(), 1, "the fast half lost its check");
3317
3318        let asked = all(&func, Opcode::CapExtent);
3319        assert_eq!(asked.len(), 1, "one question for the one check that was sized");
3320        let at = func[func[asked[0].1].args][1];
3321        let inst = super::inst_of(&func, at);
3322        assert_eq!(func[inst].opcode, Opcode::PtrAdd, "the question is asked about a displacement");
3323        assert_eq!(func[func[inst].args][0], func[blocks[0]].params[0], "off the array");
3324        sound(&func, &mut names);
3325    }
3326
3327    #[test]
3328    fn a_walk_over_a_file_scope_array_is_split_and_the_address_is_written_out_again() {
3329        // #810. The address of a global is a link time constant, so it does not change inside a
3330        // loop wherever the instruction that works it out happens to sit. The question in front of
3331        // the loop gets a `global_addr` of its own rather than reading the one inside, which is one
3332        // instruction and is the same trade `crate::licm` already makes for these.
3333        let (mut names, mut func, _) = over_a_global();
3334        let stats = split_up(&mut func);
3335        assert_eq!(stats.count(Kind::Optimized, SPLIT), 1);
3336        assert_eq!(all(&func, Opcode::CheckBounds).len(), 1, "the fast half lost its check");
3337
3338        let asked = all(&func, Opcode::CapExtent);
3339        assert_eq!(asked.len(), 1, "one question for the one check that was sized");
3340        let at = func[func[asked[0].1].args][1];
3341        let inst = super::inst_of(&func, at);
3342        assert_eq!(func[inst].opcode, Opcode::GlobalAddr, "asked about the array itself");
3343
3344        let cfg = crate::Cfg::new(&func);
3345        let doms = crate::Dominators::new(&cfg);
3346        let loops = crate::Loops::new(&cfg, &doms);
3347        let addresses = all(&func, Opcode::GlobalAddr);
3348        assert_eq!(addresses.len(), 3, "one in each half of the loop and one in front of them");
3349        assert_eq!(
3350            addresses
3351                .iter()
3352                .filter(|&&(block, _)| loops.all().all(|id| !loops.contains(id, block)))
3353                .count(),
3354            1,
3355            "and the one in front is outside every loop, which is where the question is asked",
3356        );
3357        sound(&func, &mut names);
3358    }
3359
3360    #[test]
3361    fn a_walk_whose_step_is_not_a_number_is_split_and_the_guard_measures_how_far_it_got() {
3362        // #810. The pointer moves by one or by two and nothing knows which, so there is no step to
3363        // carry and no count to keep. What the guard can do instead is subtract: where the pointer
3364        // is now, less where it was on the way in, is the displacement itself rather than a number
3365        // standing in for it, so the same window and the same rule apply unchanged.
3366        let (mut names, mut func, blocks) = by_what_it_read();
3367        let stats = split_up(&mut func);
3368        assert_eq!(stats.count(Kind::Optimized, SPLIT), 1);
3369        assert_eq!(all(&func, Opcode::CheckBounds).len(), 1, "the fast half lost its check");
3370
3371        let asked = all(&func, Opcode::CapExtent);
3372        assert_eq!(asked.len(), 1, "one question for the one check that was sized");
3373        assert_eq!(
3374            func[func[asked[0].1].args][1], func[blocks[0]].params[0],
3375            "asked about the pointer the loop was handed, which is where the walk begins",
3376        );
3377
3378        let measured = all(&func, Opcode::PtrToInt);
3379        assert_eq!(measured.len(), 2, "where the pointer began and where it is now");
3380        sound(&func, &mut names);
3381    }
3382
3383    #[test]
3384    fn a_guard_that_measures_carries_nothing_round_the_loop() {
3385        // The measured offset costs less than the counted one rather than more. It is worked out
3386        // from a pointer the loop already hands itself, so the guard needs no parameter for it and
3387        // the latch needs no add, and what is left is one subtraction where there was a block
3388        // parameter and an increment.
3389        let (mut names, mut func, _) = by_what_it_read();
3390        split_up(&mut func);
3391
3392        let cfg = crate::Cfg::new(&func);
3393        let doms = crate::Dominators::new(&cfg);
3394        let loops = crate::Loops::new(&cfg, &doms);
3395        let guard = loops
3396            .all()
3397            .map(|id| loops.header(id))
3398            .find(|&block| func.insts(block).any(|inst| func[inst].opcode == Opcode::PtrToInt))
3399            .expect("the guard is the header of the loop it took over");
3400        assert_eq!(func[guard].params.len(), 1, "the pointer the header carried, and nothing else");
3401        sound(&func, &mut names);
3402    }
3403
3404    #[test]
3405    fn an_address_built_out_of_what_the_header_carries_is_written_again_in_the_guard() {
3406        // #810. `p + (i & 7)` is not an induction variable and scalar evolution has nothing to say
3407        // about it, and it is not a fixed distance from a pointer either, so measuring where the
3408        // pointer went does not reach it. It is still a function of the two parameters the header
3409        // carries, so both the guard and the preheader can write the two instructions out again
3410        // from what each of them already has, and then the subtraction is the one that was already
3411        // here.
3412        let (mut names, mut func, blocks) = from_what_it_carries(false);
3413        let stats = split_up(&mut func);
3414        assert_eq!(stats.count(Kind::Optimized, SPLIT), 1);
3415        assert_eq!(all(&func, Opcode::CheckBounds).len(), 1, "the fast half lost its check");
3416
3417        let masks = all(&func, Opcode::And);
3418        assert_eq!(masks.len(), 4, "one per half, one in the guard and one in the preheader");
3419        let inside: Vec<Block> = masks.iter().map(|&(block, _)| block).collect();
3420        assert!(inside.contains(&blocks[0]), "the preheader works the first address out");
3421
3422        let asked = all(&func, Opcode::CapExtent);
3423        assert_eq!(asked.len(), 1, "one question, in front of the loop");
3424        assert_eq!(asked[0].0, blocks[0], "asked in the preheader about the first address");
3425        let measured = all(&func, Opcode::PtrToInt);
3426        assert_eq!(measured.len(), 2, "where the address began and where it is now");
3427        sound(&func, &mut names);
3428    }
3429
3430    #[test]
3431    fn an_address_built_on_something_read_out_of_memory_is_left_alone() {
3432        // The same loop with a load where the mask was. A second copy of a load in the guard is a
3433        // second read at another moment, which is not the same number, and a copy of it in the
3434        // preheader is a read on a loop that may run no iterations at all. So the address stops
3435        // being something either block could work out and the check stays in both halves.
3436        let (mut names, mut func, _) = from_what_it_carries(true);
3437        let stats = split_up(&mut func);
3438        assert_eq!(stats.count(Kind::Optimized, SPLIT), 0, "the loop is left alone");
3439        assert_eq!(stats.count(Kind::Missed, super::STEP_NOT_FOLLOWED), 1, "and says which half");
3440        assert_eq!(all(&func, Opcode::CheckBounds).len(), 1, "and the check stays where it was");
3441        assert!(all(&func, Opcode::CapExtent).is_empty(), "with nothing asked in front of it");
3442        sound(&func, &mut names);
3443    }
3444
3445    #[test]
3446    fn a_walk_down_a_linked_list_is_left_alone() {
3447        // Splitting a list would be sound and would not pay. The guard tests the difference at run
3448        // time, so a second node that landed inside the first one's object would pass it, but the
3449        // next node of a heap allocated list is its own object and the guard fails from the second
3450        // iteration on, leaving two copies of the loop with every check in both. What stops it is
3451        // the walk over the back edge, which insists the pointer is its own former self plus bytes,
3452        // and a load is not.
3453        let (mut names, mut func, _) = down_a_list();
3454        let stats = split_up(&mut func);
3455        assert_eq!(stats.count(Kind::Optimized, SPLIT), 0, "the loop is left alone");
3456        assert_eq!(stats.count(Kind::Missed, super::WALKS_A_STRUCTURE), 1, "and says it is a list");
3457        assert_eq!(all(&func, Opcode::CheckBounds).len(), 1, "and the check stays where it was");
3458        assert!(all(&func, Opcode::CapExtent).is_empty(), "with nothing asked in front of it");
3459        sound(&func, &mut names);
3460    }
3461
3462    /// Where the address the loop checks came from, for [`made_in_the_loop`].
3463    enum Made {
3464        /// Read out of memory.
3465        Read,
3466        /// Handed back by a call that cannot free.
3467        Returned,
3468        /// One of two, chosen every iteration.
3469        Chosen,
3470        /// Worked out from the counter as a number and then used as an address.
3471        Cast,
3472    }
3473
3474    /// A loop whose checked address is made in the body, in one of the ways the census names.
3475    ///
3476    /// ```text
3477    /// entry(a, n): jump head(0)
3478    /// head(i):     p = <made here>; check_bounds cap_of(p), p
3479    ///              j = i + 1; br j < n -> head(j), done
3480    /// done:        ret
3481    /// ```
3482    ///
3483    /// The same loop every time, because what these rows differ in is where the pointer came from
3484    /// and that is the only thing varied here. None of the four is an address scalar evolution can
3485    /// evolve and none is one the guard could write again, so all of them reach the same refusal.
3486    /// What each one is for is that the refusal now says which of them it was.
3487    fn made_in_the_loop(how: Made) -> (Interner, Func, Vec<Block>) {
3488        let word = Type::int(64);
3489        let mut names = Interner::new();
3490        let mut func =
3491            Func::new(names.intern("f"), Signature::new().with_params(&[Type::PTR, word]));
3492        let entry = func.create_block();
3493        let head = func.create_block();
3494        let done = func.create_block();
3495        let text = func.append_param(entry, Type::PTR);
3496        let count = func.append_param(entry, word);
3497        let index = func.append_param(head, word);
3498
3499        let mut build = Builder::new(&mut func, entry);
3500        let zero = build.iconst(word, 0);
3501        build.jump(head, &[zero]);
3502
3503        let mut build = Builder::new(&mut func, head);
3504        let args = build.func().push_values(&[text, index]);
3505        let along = build.value(InstData { args, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
3506        let pointer = match how {
3507            Made::Read => build.load(Type::PTR, along, mem(), Flags::NONE),
3508            Made::Returned => {
3509                let callee = names.intern("somewhere");
3510                let returns = Signature::new().with_returns(&[Type::PTR]);
3511                let signature = build.func().add_signature(returns);
3512                let call = build.call(callee, signature, &[]);
3513                // Without this the loop is refused for the call before any check is looked at, and
3514                // the row would be one no build ever reports. A callee that cannot free is the only
3515                // way a call gets to be in a loop this pass is still willing to split.
3516                build.func()[call].flags |= Flags::NOFREE;
3517                build.func()[call].results().next().expect("the callee hands back a pointer")
3518            }
3519            // One arm reads memory, which is what keeps the guard from writing the choice out
3520            // again. Two arms it could write are a choice it takes rather than refuses.
3521            Made::Chosen => {
3522                let other = build.load(Type::PTR, along, mem(), Flags::NONE);
3523                let odd = build.iconst(word, 1);
3524                let which = build.binary(Opcode::And, index, odd, Flags::NONE);
3525                let none = build.iconst(word, 0);
3526                let taken = build.icmp(IntPred::Eq, which, none);
3527                build.select(taken, text, other)
3528            }
3529            Made::Cast => build.unary(Opcode::IntToPtr, index, Type::PTR),
3530        };
3531        checking(&mut build, pointer, byte());
3532        let one = build.iconst(word, 1);
3533        let next = build.binary(Opcode::Add, index, one, Flags::NSW);
3534        let again = build.icmp(IntPred::Slt, next, count);
3535        build.br_if(again, head, &[next], done, &[]);
3536        Builder::new(&mut func, done).ret(&[]);
3537        (names, func, vec![entry, head, done])
3538    }
3539
3540    /// What the census says about a loop built by [`made_in_the_loop`].
3541    fn refusal(how: Made) -> (Interner, Func, Stats) {
3542        let (names, mut func, _) = made_in_the_loop(how);
3543        let stats = split_up(&mut func);
3544        assert_eq!(stats.count(Kind::Optimized, SPLIT), 0, "the loop is left alone");
3545        (names, func, stats)
3546    }
3547
3548    #[test]
3549    fn an_address_read_out_of_memory_says_so() {
3550        // A second copy of the load is a second read at another moment, so neither the guard nor
3551        // the preheader can work the address out, and the check stays in both halves. What this is
3552        // about is the row it lands in: the pointer came out of memory, which is a different thing
3553        // to do something about than a subscript nothing can count.
3554        let (mut names, func, stats) = refusal(Made::Read);
3555        assert_eq!(stats.count(Kind::Missed, super::ADDRESS_FROM_MEMORY), 1);
3556        sound(&func, &mut names);
3557    }
3558
3559    #[test]
3560    fn an_address_handed_back_by_a_call_says_so() {
3561        // The loop is still one this pass would split, since the callee cannot free, so the check
3562        // is looked at and refused on its own account rather than the loop being dropped first.
3563        let (mut names, func, stats) = refusal(Made::Returned);
3564        assert_eq!(stats.count(Kind::Missed, super::ADDRESS_FROM_A_CALL), 1);
3565        sound(&func, &mut names);
3566    }
3567
3568    #[test]
3569    fn an_address_the_loop_chose_between_says_so() {
3570        // Named by what the address is rather than by what is under the arm that reads memory. The
3571        // choice is the outer thing and it is the thing anybody reading the census would go and
3572        // look at, since which arm was taken is what the guard would have to know.
3573        let (mut names, func, stats) = refusal(Made::Chosen);
3574        assert_eq!(stats.count(Kind::Missed, super::ADDRESS_FROM_A_CHOICE), 1);
3575        sound(&func, &mut names);
3576    }
3577
3578    #[test]
3579    fn an_address_none_of_the_rows_fits_is_still_counted() {
3580        // The remainder, which is what the old single row has become. Keeping it is the point: a
3581        // census that named three shapes and dropped everything else would be a census of what
3582        // somebody thought to look for rather than of what the build does.
3583        let (mut names, func, stats) = refusal(Made::Cast);
3584        assert_eq!(stats.count(Kind::Missed, super::NOT_FOLLOWED), 1);
3585        sound(&func, &mut names);
3586    }
3587
3588    #[test]
3589    fn a_walk_the_guard_would_measure_is_left_alone_when_its_access_wants_alignment() {
3590        // A step nobody wrote down is a step nothing can divide by the alignment, so a measured walk
3591        // has no answer about whether the second access is as aligned as the first. Refusing is the
3592        // conservative reading and it has its own line in the census, so what it costs is a number.
3593        let (mut names, mut func, _) = by_what_it_read();
3594        for (_, inst) in all(&func, Opcode::CheckBounds) {
3595            let extra = Extra::Mem(func.add_mem(mem()));
3596            func[inst].extra = extra;
3597        }
3598        let stats = split_up(&mut func);
3599        assert_eq!(stats.count(Kind::Optimized, SPLIT), 0, "the loop is left alone");
3600        assert_eq!(stats.count(Kind::Missed, super::MEASURED_ALIGN), 1);
3601        sound(&func, &mut names);
3602    }
3603
3604    #[test]
3605    fn a_walk_from_an_index_in_int_is_split_and_the_extension_is_emitted_in_front() {
3606        // #810, and the shape that is actually in C rather than the one that is convenient to
3607        // build. The chrec of `start + i` is in `int` and its base is `start`, so widening it to
3608        // pointer width wants `sext(start)`, which nothing in the function computes. The invariant
3609        // describes the extension instead and this pass emits it, once, in the preheader.
3610        let (mut names, mut func, blocks) = from_a_narrow_index();
3611        let stats = split_up(&mut func);
3612        assert_eq!(stats.count(Kind::Optimized, SPLIT), 1);
3613        assert_eq!(all(&func, Opcode::CheckBounds).len(), 1, "the fast half lost its check");
3614
3615        let asked = all(&func, Opcode::CapExtent);
3616        assert_eq!(asked.len(), 1, "one question for the one check that was sized");
3617        let at = func[func[asked[0].1].args][1];
3618        let sum = super::inst_of(&func, at);
3619        assert_eq!(func[sum].opcode, Opcode::PtrAdd, "the question is asked about a displacement");
3620        assert_eq!(func[func[sum].args][0], func[blocks[0]].params[0], "off the array");
3621        let widened = all(&func, Opcode::SExt);
3622        assert_eq!(widened.len(), 3, "one extension in each half of the loop and one in front");
3623        let start = func[blocks[0]].params[1];
3624        assert_eq!(
3625            widened.iter().filter(|&&(_, inst)| func[func[inst].args][0] == start).count(),
3626            1,
3627            "and the one in front is of the index the caller handed in, which the halves never take",
3628        );
3629        sound(&func, &mut names);
3630    }
3631
3632    #[test]
3633    fn a_walk_from_high_to_low_is_split_and_the_question_goes_the_other_way() {
3634        // #680. The offset the guard carries counts bytes moved rather than bytes added, so it goes
3635        // up here exactly as it does in an ascending loop and the guard is the same guard. The one
3636        // thing that turns over is which end of the object the runtime is asked about, and it is
3637        // asked at the end of the first access rather than at its start so that the window is room
3638        // below and the rule the pass asks is the mirror of the one it asks going up.
3639        let (mut names, mut func, blocks) = downwards();
3640        let stats = split_up(&mut func);
3641        assert_eq!(stats.count(Kind::Optimized, SPLIT), 1);
3642        assert_eq!(all(&func, Opcode::CheckBounds).len(), 1, "the fast half lost its check");
3643
3644        assert!(all(&func, Opcode::CapExtent).is_empty(), "nothing asked about the bytes above");
3645        let asked = all(&func, Opcode::CapExtentBack);
3646        assert_eq!(asked.len(), 1, "one question for the one check that was sized");
3647        let at = func[func[asked[0].1].args][1];
3648        let end = super::inst_of(&func, at);
3649        assert_eq!(func[end].opcode, Opcode::PtrAdd, "asked at the end of the first access");
3650        let from = func[func[end].args][0];
3651        let first = super::inst_of(&func, from);
3652        assert_eq!(
3653            func[first].opcode,
3654            Opcode::PtrAdd,
3655            "past a first access that is a displacement"
3656        );
3657        assert_eq!(func[func[first].args][0], func[blocks[0]].params[0], "off the array");
3658        sound(&func, &mut names);
3659    }
3660
3661    #[test]
3662    fn a_loop_with_a_call_in_it_that_might_free_is_left_alone() {
3663        // The extent is asked once and believed for the whole of the fast half, so anything that
3664        // could hand the storage back in the middle makes the answer stale and the fast half has
3665        // nothing left in it to notice.
3666        let (_, mut func, _) = calling(Flags::NONE);
3667        let stats = split_up(&mut func);
3668        assert!(!stats.changed());
3669        assert_eq!(stats.count(Kind::Missed, super::A_CALL_INSIDE), 1);
3670    }
3671
3672    #[test]
3673    fn a_loop_with_a_call_in_it_that_cannot_free_is_split() {
3674        // Whether the storage can be handed back is a question about the callee, and `crate::nofree`
3675        // answers it before the pipeline starts. This is the largest row of the census by a long way,
3676        // and it is also the row where this pass and hoisting come apart the furthest: hoisting
3677        // refuses a call whatever it does, because it needs the loop to reach the end of what its
3678        // count says, and this never claims that.
3679        let (mut names, mut func, _) = calling(Flags::NOFREE);
3680        let stats = split_up(&mut func);
3681        assert_eq!(stats.count(Kind::Optimized, SPLIT), 1);
3682        assert_eq!(all(&func, Opcode::CheckBounds).len(), 1, "the fast half lost its check");
3683        assert_eq!(all(&func, Opcode::Call).len(), 2, "and both halves kept the call");
3684        sound(&func, &mut names);
3685    }
3686
3687    /// The loop with a call added to its latch, carrying whatever the caller says about it.
3688    fn calling(flags: Flags) -> (Interner, Func, Vec<Block>) {
3689        let (mut names, mut func, blocks) = leaving();
3690        let more = blocks[2];
3691        let term = func.terminator(more).expect("the latch branches");
3692        let callee = names.intern("somewhere");
3693        let signature = func.add_signature(Signature::new());
3694        let call = Builder::new(&mut func, more).call(callee, signature, &[]);
3695        func[call].flags |= flags;
3696        func.remove_inst(call);
3697        func.insert_before(call, term);
3698        (names, func, blocks)
3699    }
3700
3701    #[test]
3702    fn a_check_whose_address_does_not_move_is_taken_too() {
3703        // One check on the array itself, every time round, alongside the one that walks. Hoisting
3704        // would rather have the still one, but this loop has a second way out, so hoisting will not
3705        // touch it and the check is still here to be taken. A step of zero is what carries it: the
3706        // access fits on the first iteration or on none of them, so it puts no limit on the loop.
3707        let (mut names, mut func, _) = standing(false);
3708        let stats = split_up(&mut func);
3709        assert_eq!(stats.count(Kind::Optimized, SPLIT), 1);
3710        assert_eq!(all(&func, Opcode::CapExtent).len(), 1, "and both were sized by one question");
3711        assert_eq!(
3712            all(&func, Opcode::CheckBounds).len(),
3713            2,
3714            "the fast half lost both checks and the slow half kept both"
3715        );
3716        sound(&func, &mut names);
3717    }
3718
3719    #[test]
3720    fn the_window_is_worked_out_without_dividing_by_anything() {
3721        // The reason it counts bytes rather than iterations. Iterations came out of a division by
3722        // the step, which is a step of zero on a check whose address does not move, and on x86 that
3723        // is a fault rather than a wrong number, so tamnd/rucc#818 was a program dying on the way
3724        // into a loop it was never going to fail in. It is also why the claim could not be a rule:
3725        // the divide and the multiply that went with it are what z3 would not finish on. The plan
3726        // here has one check of each kind, which is the shape fifty six of SQLite's two hundred and
3727        // sixty eight split loops have.
3728        let (mut names, mut func, _) = standing(false);
3729        split_up(&mut func);
3730        for opcode in [Opcode::SDiv, Opcode::UDiv] {
3731            assert!(all(&func, opcode).is_empty(), "{opcode:?} is left in the window arithmetic");
3732        }
3733        sound(&func, &mut names);
3734    }
3735
3736    #[test]
3737    fn two_checks_that_walk_by_the_same_amount_share_one_offset() {
3738        // One value round the loop rather than one per check, which is what the common shape wants:
3739        // a loop that reads one array and writes another walks both by the same step, so they are
3740        // at the same offset on every iteration and the window is the smaller of the two.
3741        let (mut names, mut func, blocks) = twinned();
3742        let stats = split_up(&mut func);
3743        assert_eq!(stats.count(Kind::Optimized, SPLIT), 1);
3744        assert_eq!(all(&func, Opcode::CapExtent).len(), 2, "both addresses were sized in front");
3745
3746        let head = blocks[1];
3747        let cfg = crate::Cfg::new(&func);
3748        let into = cfg.predecessors(head);
3749        assert_eq!(into.len(), 1, "the guard is the only way into the header now");
3750        let guard = into[0];
3751        assert_eq!(
3752            func[guard].params.len(),
3753            func[head].params.len() + 1,
3754            "one offset, not one per check"
3755        );
3756        sound(&func, &mut names);
3757    }
3758
3759    /// The loop with a second walking check in it, on the element after the one it reads.
3760    ///
3761    /// Two checks that move by the same amount, which is what a loop that reads one array and writes
3762    /// another is, and what a loop that looks one element ahead is. The window arithmetic keeps one
3763    /// offset for the pair of them rather than one each, and this is the fixture that says so.
3764    fn twinned() -> (Interner, Func, Vec<Block>) {
3765        let (names, mut func, blocks) = leaving();
3766        let (entry, head) = (blocks[0], blocks[1]);
3767        let array = func[entry].params[0];
3768        let counter = func[head].params[0];
3769        let term = func.terminator(head).expect("the header branches");
3770        let mut build = Builder::new(&mut func, head);
3771        let by = build.iconst(Type::int(64), WIDTH);
3772        let scaled = build.binary(Opcode::Mul, counter, by, Flags::NSW);
3773        let ahead = build.binary(Opcode::Add, scaled, by, Flags::NSW);
3774        let args = build.func().push_values(&[array, ahead]);
3775        let pointer = build.value(InstData { args, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
3776        check(&mut build, pointer);
3777        let made: Vec<Inst> = func.insts(head).skip_while(|&inst| inst != term).skip(1).collect();
3778        for inst in made {
3779            func.remove_inst(inst);
3780            func.insert_before(inst, term);
3781        }
3782        (names, func, blocks)
3783    }
3784
3785    #[test]
3786    fn a_loop_where_nothing_moves_picks_its_half_once_and_counts_nothing() {
3787        // Half the loops this takes on SQLite are like this, and they need none of the machinery the
3788        // rest of them do. Which half runs is decided by the answer to a question asked in the
3789        // preheader, the answer does not change while the loop runs, so the way into the loop is
3790        // where the two halves are chosen between and there is no counter and no guard block.
3791        let (mut names, mut func, blocks) = standing(true);
3792        let stats = split_up(&mut func);
3793        assert_eq!(stats.count(Kind::Optimized, SPLIT), 1);
3794        assert_eq!(all(&func, Opcode::CapExtent).len(), 1);
3795        assert_eq!(all(&func, Opcode::CheckBounds).len(), 1, "the fast half lost its check");
3796
3797        let (entry, head) = (blocks[0], blocks[1]);
3798        let term = func.terminator(entry).expect("the preheader still ends in something");
3799        assert_eq!(func[term].opcode, Opcode::BrIf, "the way in is the choice");
3800        assert_eq!(func[head].params.len(), 1, "and the header took on no counter");
3801        sound(&func, &mut names);
3802    }
3803
3804    /// The loop with a check on the array itself added to its header, every time round.
3805    ///
3806    /// Hoisting would rather have that check, and it takes the ones in loops it is willing to touch.
3807    /// This loop has a second way out, so hoisting will not touch it and the check is still here.
3808    /// `alone` takes the walking check away, which leaves a loop where nothing moves at all.
3809    fn standing(alone: bool) -> (Interner, Func, Vec<Block>) {
3810        let (names, mut func, blocks) = leaving();
3811        let (entry, head) = (blocks[0], blocks[1]);
3812        let array = func[entry].params[0];
3813        let walking = all(&func, Opcode::CheckBounds);
3814        let term = func.terminator(head).expect("the header branches");
3815        let mut build = Builder::new(&mut func, head);
3816        check(&mut build, array);
3817        let made: Vec<Inst> = func.insts(head).skip_while(|&inst| inst != term).skip(1).collect();
3818        for inst in made {
3819            func.remove_inst(inst);
3820            func.insert_before(inst, term);
3821        }
3822        if alone {
3823            for (_, inst) in walking {
3824                func.remove_inst(inst);
3825            }
3826        }
3827        (names, func, blocks)
3828    }
3829
3830    #[test]
3831    fn a_loop_whose_count_is_an_expression_is_split_on_what_that_expression_says() {
3832        // How far to look is worked out in the preheader rather than written down, out of a value
3833        // the loop does not change. Nothing here promises the arithmetic stays inside sixty four
3834        // bits, and it does not have to: a limit that wrapped is still answered with a true count
3835        // of the bytes that belong to the object.
3836        let (mut names, mut func, _) = counting();
3837        let stats = split_up(&mut func);
3838        assert_eq!(stats.count(Kind::Optimized, SPLIT), 1);
3839        assert_eq!(all(&func, Opcode::CapExtent).len(), 1);
3840        assert_eq!(all(&func, Opcode::CheckBounds).len(), 1, "the fast half lost its check");
3841        sound(&func, &mut names);
3842    }
3843
3844    #[test]
3845    fn a_loop_nobody_counted_is_split_and_asks_for_as_much_as_the_arithmetic_carries() {
3846        // The difference from hoisting in one test. Hoisting refuses this loop, because the count
3847        // is what it sizes the check it writes with and a count nobody settled is not one it may
3848        // write a check from. Nothing here rests on the count: it is spent on how far to ask the
3849        // runtime to look, and the runtime answers with a true count of the bytes that belong to the
3850        // object whatever it was asked for.
3851        //
3852        // tamnd/rucc#871. What the ask used to be worked out from was a guess of ten iterations, and
3853        // that was a bound on how far the runtime would walk rather than anything the guard wanted.
3854        // tamnd/rucc#861 stopped it walking, so a loop nobody counted asks for everything and gets
3855        // the extent of the object at the same price a small ask would have cost.
3856        let (mut names, mut func, _) = uncounted();
3857        let mut an = crate::machine::fixtures::analyses();
3858        Canon.run(&mut func, &mut an, &mut Fuel::unlimited());
3859        let refused = crate::hoist::Hoist.run(&mut func, &mut an, &mut Fuel::unlimited());
3860        assert!(!refused.changed(), "hoisting will not size a check from a count nobody settled");
3861
3862        let stats = Split.run(&mut func, &mut an, &mut Fuel::unlimited());
3863        assert_eq!(stats.count(Kind::Optimized, SPLIT), 1);
3864        assert_eq!(all(&func, Opcode::CheckBounds).len(), 1, "the fast half lost its check");
3865
3866        let asked = all(&func, Opcode::CapExtent);
3867        assert_eq!(asked.len(), 1, "one question for the one check that was sized");
3868        let want = func[func[asked[0].1].args][2];
3869        assert_eq!(number(&func, want), Some(i128::from(i64::MAX)), "and it asked for everything");
3870        sound(&func, &mut names);
3871    }
3872
3873    #[test]
3874    fn the_pass_stops_when_the_fuel_runs_out() {
3875        // What `-fopt-fuel` is for, and the reason every transformation here goes through the
3876        // counter rather than round it.
3877        let (_, mut func, _) = leaving();
3878        let mut an = crate::machine::fixtures::analyses();
3879        Canon.run(&mut func, &mut an, &mut Fuel::unlimited());
3880        let stats = Split.run(&mut func, &mut an, &mut Fuel::of(0));
3881        assert!(!stats.changed());
3882        assert_eq!(stats.count(Kind::Missed, super::NO_FUEL), 1);
3883    }
3884}