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