Skip to content

perf: move insertion is quadratic in a block parameter's predecessors × the blocks it stays live across #286

Backlog

Description

@bytemaster

apply_allocations_and_insert_moves rescans a block parameter's blockparam_ins entries once for every block
that the parameter is live into. A parameter with T predecessors that is live across B later blocks costs T × B
steps; with L such parameters that is L × T × B. A function with two large merge points in sequence (B ≈ T) takes
time quadratic in T. This is what is left of #274 after #281: #281 stopped the walk from passing over earlier
vregs'
entries, and the walk still passes over the same vreg's entries again for every block.

Generated code is not affected, only compile time.

Reproduction

gen_repro.py (below, 40 lines, standard library only) writes a WebAssembly text module with one function:
LOCALS i64 locals and two merge points in sequence. Each merge point is reached over one edge on which every
local has just been written and over TARGETS more edges (the targets of one br_table) on which none has; all
locals are read after the last merge point. In SSA form every local is a block parameter of each merge block,
with TARGETS + 1 predecessors, and the parameters of the first merge block are live across the TARGETS edge
blocks of the second.

python3 gen_repro.py 256 1024 > repro.wat
time wasmtime compile repro.wat

With a released wasmtime this shows the whole of #274, because no regalloc2 release has #281 yet (0.15.3 is
the latest). Measured with the wasmtime 43.0.0 release binary, aarch64 macOS, user CPU seconds of
wasmtime compile, 256 locals, two merges:

targets 256 512 1,024 2,048
wasmtime compile 1.96 7.50 30.0 120.6

That is a factor of four per doubling. What this issue is about is the part that remains on main, which
needs a build of Wasmtime against regalloc2 main to see:

CPU seconds for Engine::precompile_module, Wasmtime 51.0.0 (Cranelift 0.138), default settings except
parallel_compilation(false), aarch64 macOS. "main" is regalloc2 at a45e355 (which has #281), "fix" is main with
the change below, "0.15.3" is the crates.io release (without #281), all selected with [patch.crates-io]:

locals × targets, merges module (wat) 0.15.3 main main + fix
128 × 128, 2 15 KB 0.14 0.009 0.007
256 × 256, 2 31 KB 2.21 0.041 0.028
512 × 512, 2 62 KB 34.7 0.23 0.11
512 × 1,024, 2 69 KB 0.68 0.24
512 × 2,048, 2 84 KB 2.26 0.49
512 × 4,096, 2 112 KB 8.11 1.03
1,024 × 1,024, 2 125 KB 1.49 0.51
2,048 × 1,024, 2 241 KB 2.92 1.05
2,047 × 4,096, 2 283 KB 33.5 4.47
512 × 2,048, 1 50 KB 0.27 0.27 0.27
512 × 2,048, 4 151 KB 6.31 0.95

On main, doubling the targets at 512 locals multiplies the time by 3.0 to 3.6; with the fix by 2.0 to 2.1. With a
single merge point nothing is live across a second set of edge blocks and the three columns agree. (Empty cells
were not run: 0.15.3 is quadratic in locals × targets here and would take from minutes to hours.) The same
ratio shows when targeting x86-64 (512 × 4,096: 9.5 s on main, 1.0 s with the fix).

The serialized compiled module is byte-identical between main and main + fix for all eleven modules on aarch64
and for the two checked on x86-64.

Cause

src/ion/moves.rs on main (a45e355), in Env::apply_allocations_and_insert_moves:

  • blockparam_ins is sorted by (to_vreg, to_block) (liveranges.rs:762).
  • For each vreg (:280), for each of its live ranges (:301), the loop at :482 visits every block whose entry
    the range covers, in increasing block order. For each such block, line :494 starts a walk at
    prev.blockparam_ins_idx() and runs to the first entry greater than (vreg, block) (:495–:533), collecting
    the entries equal to (vreg, block).
  • prev.blockparam_ins_idx() is the cursor buffered in PrevBuffer (:93–:163). It is deliberately held back:
    ranges of one vreg may overlap, so it only moves when a later range starts at a later point (advance, :141).
    It does not move while one range is being processed.

So within one range, every block's walk starts at the same position and steps over all of this vreg's entries for
earlier blocks before it reaches the first entry that could match. A vreg is the parameter of one block, so those
are all of its entries: one per predecessor of that block. The walk for each later block the range covers passes
over all of them and matches none.

In the reproduction, each of the L parameters of the first merge block has T + 1 entries and one range that covers
the T edge blocks of the second merge: L × T × (T + 1) steps, 8.6 × 10⁹ for 512 × 4,096.

Fix

Start the walk once per range instead of once per block, and let it continue from where the previous block's walk
stopped. Within a range blocks are visited in increasing order, so every entry the walk has stepped over is below
the key of every later block and cannot match it. For each block the walk therefore collects exactly the entries
it collected before, and stops at the same index, which is the value passed to update_blockparam_ins_idx; the
PrevBuffer protocol between ranges is untouched. This holds whether or not the buffered cursor is at or before
the block's first entry, so cases where a later, overlapping range starts past them behave as before as well.

diff --git a/src/ion/moves.rs b/src/ion/moves.rs
index ccac1f0..a1a0ff2 100644
--- a/src/ion/moves.rs
+++ b/src/ion/moves.rs
@@ -479,6 +479,17 @@ impl<'a, F: Function> Env<'a, F> {
                 if self.cfginfo.block_entry[block.index()] < range.from {
                     block = block.next();
                 }
+                // The walk of `blockparam_ins` starts from the buffered
+                // cursor once per range: ranges of one vreg can overlap, so
+                // a later range may need entries that an earlier one already
+                // passed. It must not start again for every block of the
+                // range, though. Blocks are visited in increasing order and
+                // the entries are sorted by (vreg, block), so everything the
+                // walk for one block steps over is below the key of every
+                // later block and cannot match it; starting again only
+                // rescans this vreg's entries once per block the range
+                // covers.
+                let mut idx = prev.blockparam_ins_idx();
                 while block.is_valid() && block.index() < self.func.num_blocks() {
                     if self.cfginfo.block_entry[block.index()] >= range.to {
                         break;
@@ -489,9 +500,8 @@ impl<'a, F: Function> Env<'a, F> {
                         "scanning blockparam_ins at vreg {} block {}: blockparam_in_idx = {}",
                         vreg.index(),
                         block.index(),
-                        prev.prev_ins_idx,
+                        idx,
                     );
-                    let mut idx = prev.blockparam_ins_idx();
                     while idx < self.blockparam_ins.len() {
                         let BlockparamIn {
                             from_block,

Checked with this change on top of main:

  • cargo test --all --all-features passes (14 tests, including the ion fuzz smoke test with the checker).
  • A differential run of the fuzzing::func generator (the ion fuzz target's options; random inputs of 256 bytes
    to 64 KiB): for every generated function, regalloc2::run on main and on main + fix return equal Outputs
    (compared through Debug: allocations, edits, stack slots, debug locations) or the same error, and the
    checker accepts the result. Seeds 0 to 399,999 gave 184,157 functions:
    146,184 allocated identically (5.7 million blocks, 1.2 million edits) and 37,973 refused identically.
  • The byte-identical compiled modules above.

I can open a PR with this change if that is welcome.

gen_repro.py

#!/usr/bin/env python3
"""Writes a WebAssembly text module that makes regalloc2's move insertion
quadratic.

    gen_repro.py LOCALS TARGETS [MERGES] > repro.wat
    wasmtime compile repro.wat          # or: time wasmtime compile ...

The module has one function. It declares LOCALS i64 locals and contains
MERGES (default 2) merge points in sequence. Each merge point is reached
over one edge on which every local has just been written, and over TARGETS
more edges (the targets of one `br_table`) on which none has. After the last
merge point every local is read.

In SSA form each local therefore becomes a block parameter of each merge
block, with TARGETS + 1 predecessors, and the parameters of the first merge
block stay live across the TARGETS edge blocks of the second.
"""
import sys

def module(locals_, targets, merges=2):
    out = ['(module (func (export "f") (param i32) (result i64)']
    out.append('  (local' + ' i64' * locals_ + ')')
    for k in range(merges):
        out.append('  (block $merge (block $out')
        out.append('    (if (local.get 0) (then')
        for i in range(1, locals_ + 1):
            out.append('      (local.set %d (i64.const %d))' % (i, i + k))
        out.append('      (br $merge)))')
        out.append('    (br_table' + ' $merge' * targets + ' $out (local.get 0))))')
    out.append('  (local.get 1)')
    for i in range(2, locals_ + 1):
        out.append('  (i64.add (local.get %d))' % i)
    out.append('))')
    return '\n'.join(out) + '\n'

if __name__ == '__main__':
    if len(sys.argv) < 3:
        sys.exit(__doc__)
    sys.stdout.write(module(int(sys.argv[1]), int(sys.argv[2]),
                            int(sys.argv[3]) if len(sys.argv) > 3 else 2))

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions