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