A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
Fix a bug in elaborartion that led to missed LICM hoisting (#14383)
Nick Fitzgerald63edc9e1e1e9
diff --git a/cranelift/codegen/src/egraph/elaborate.rs b/cranelift/codegen/src/egraph/elaborate.rsindex 86443e5cb1..8133206634 100644--- a/cranelift/codegen/src/egraph/elaborate.rs+++ b/cranelift/codegen/src/egraph/elaborate.rs@@ -47,8 +47,32 @@ pub(crate) struct Elaborator<'a> {/// Map from Value to the best (lowest-cost) Value in its eclass/// (tree of union value-nodes).value_to_best_value: SecondaryMap<Value, BestEntry>,- /// Stack of blocks and loops in current elaboration path.+ /// Stack of loops whose headers dominate the current elaboration+ /// path, outermost first.loop_stack: SmallVec<[LoopStackEntry; 8]>,+ /// How many of the entries in `loop_stack` actually contain the current+ /// block in their loop.+ ///+ /// Valid LICM hoisting targets are `loop_stack[..active_loop_depth]`.+ ///+ /// This is not *strictly* necessary for correctness, and we could hoist to+ /// anything in `loop_stack` because they all dominate the block we are+ /// currently elaborating, but this prevents us from hoisting instructions+ /// from loop-exit blocks to loop-header blocks, which (1) wouldn't cut down+ /// on the number of times they're executed, and in fact could make them go+ /// from being executed zero times (if we exit the loop through a different+ /// loop-exit block) to executed once in the header, and (2) would make us+ /// hoist cold code out of blocks that terminate with a trap into loop+ /// headers.+ active_loop_depth: usize,+ /// For each loop currently on `loop_stack`, its index in that stack;+ /// `NOT_ON_LOOP_STACK` for every other loop.+ ///+ /// This lets us compute `active_loop_depth` with a single walk up the loop+ /// tree, rather than testing each entry of `loop_stack` for membership in+ /// turn, which would be quadratic in the depth of the loop nest because+ /// `LoopAnalysis::is_in_loop` itself walks the loop tree.+ loop_stack_index: SecondaryMap<Loop, u32>,/// The current block into which we are elaborating.cur_block: Block,/// Values that opt rules have indicated should be rematerialized@@ -71,6 +95,10 @@ pub(crate) struct Elaborator<'a> {ctrl_plane: &'a mut ControlPlane,}+/// Sentinel for `Elaborator::loop_stack_index`: this loop is not currently on+/// the loop stack.+const NOT_ON_LOOP_STACK: u32 = u32::MAX;+#[derive(Clone, Copy, Debug, PartialEq, Eq)]struct BestEntry(Cost, Value);@@ -133,8 +161,15 @@ enum ElabStackEntry {#[derive(Clone, Debug)]enum BlockStackEntry {+ /// Elaborate the given block.Elaborate { block: Block, idom: Option<Block> },- Pop,++ /// Leave the subtree we just finished elaborating.+ Pop {+ /// Truncate `loop_stack` back to `loop_depth`, the depth it had when we+ /// entered this subtree.+ loop_depth: usize,+ },}impl<'a> Elaborator<'a> {@@ -157,6 +192,8 @@ impl<'a> Elaborator<'a> {value_to_elaborated_value: ScopedHashMap::with_capacity(num_values),value_to_best_value,loop_stack: smallvec![],+ active_loop_depth: 0,+ loop_stack_index: SecondaryMap::with_default(NOT_ON_LOOP_STACK),cur_block: Block::reserved_value(),remat_values,elab_stack: vec![],@@ -177,14 +214,6 @@ impl<'a> Elaborator<'a> {self.value_to_elaborated_value.depth());- // Pop any loop levels we're no longer in.- while let Some(inner_loop) = self.loop_stack.last() {- if self.loop_analysis.is_in_loop(block, inner_loop.lp) {- break;- }- self.loop_stack.pop();- }-// Note that if the *entry* block is a loop header, we will// not make note of the loop here because it will not have an// immediate dominator. We must disallow this case because we@@ -202,6 +231,10 @@ impl<'a> Elaborator<'a> {hoist_block: idom,scope_depth: (self.value_to_elaborated_value.depth() - 1) as u32,});++ debug_assert_eq!(self.loop_stack_index[lp], NOT_ON_LOOP_STACK);+ self.loop_stack_index[lp] = u32::try_from(self.loop_stack.len() - 1).unwrap();+trace!(" -> loop header, pushing; depth now {}",self.loop_stack.len()@@ -214,11 +247,38 @@ impl<'a> Elaborator<'a> {);}- trace!("block {}: loop stack is {:?}", block, self.loop_stack);+ self.active_loop_depth = self.find_active_loop_depth(block);++ trace!(+ "block {}: loop stack is {:?}, active depth {}",+ block, self.loop_stack, self.active_loop_depth+ );self.cur_block = block;}+ /// Find the active loop depth for a new block.+ ///+ /// Not every block dominated by a loop header is inside that loop: a block+ /// that cannot reach the backedge, such as one that only traps or returns,+ /// is dominated by the header but is not a member of the natural loop. This+ /// function finds how much of the loop stack actually contains this block;+ /// the rest is not available to hoist out of.+ ///+ /// Returns `depth` where every loop in `self.loop_stack[..depth]` contains+ /// `block`.+ fn find_active_loop_depth(&self, block: Block) -> usize {+ let mut lp = self.loop_analysis.innermost_loop(block);+ while let Some(l) = lp {+ let index = self.loop_stack_index[l];+ if index != NOT_ON_LOOP_STACK {+ return index as usize + 1;+ }+ lp = self.loop_analysis.loop_parent(l);+ }+ 0+ }+fn topo_sorted_values(&self) -> Vec<Value> {#[derive(Debug)]enum Event {@@ -559,20 +619,21 @@ impl<'a> Elaborator<'a> {// placing too much register pressure on the entire// function. This is modeled with the `.saturating_sub(1)`// as the default if there's otherwise no maximum.+ let active_loop_depth = self.active_loop_depth;let loop_hoist_level = arg_values.iter().map(|&value| {- // Find the outermost loop level at which- // the value's defining block *is not* a- // member. This is the loop-nest level- // whose hoist-block we hoist to.- let hoist_level = self- .loop_stack+ // Find the outermost loop level whose+ // hoist-block this value is already+ // available at. This is the loop-nest+ // level whose hoist-block we hoist to.+ let hoist_level = self.loop_stack[..active_loop_depth].iter().position(|loop_entry| {- !self.loop_analysis.is_in_loop(value.in_block, loop_entry.lp)+ self.domtree+ .block_dominates(value.in_block, loop_entry.hoist_block)})- .unwrap_or(self.loop_stack.len());+ .unwrap_or(active_loop_depth);trace!(" -> arg: elab_value {:?} hoist level {:?}",value, hoist_level@@ -580,12 +641,10 @@ impl<'a> Elaborator<'a> {hoist_level}).max()- .unwrap_or(self.loop_stack.len().saturating_sub(1));+ .unwrap_or(active_loop_depth.saturating_sub(1));trace!(" -> loop hoist level: {:?}; cur loop depth: {:?}, loop_stack: {:?}",- loop_hoist_level,- self.loop_stack.len(),- self.loop_stack,+ loop_hoist_level, active_loop_depth, self.loop_stack,);// We know that this is a pure inst, because@@ -598,7 +657,7 @@ impl<'a> Elaborator<'a> {// block *unless* we hoist above a loop when all// args are loop-invariant (and this op is pure).let (scope_depth, before, insert_block) = if loop_hoist_level- == self.loop_stack.len()+ >= active_loop_depth{// Depends on some value at the current// loop depth, or remat forces it here:@@ -829,7 +888,9 @@ impl<'a> Elaborator<'a> {while let Some(top) = self.block_stack.pop() {match top {BlockStackEntry::Elaborate { block, idom } => {- self.block_stack.push(BlockStackEntry::Pop);+ self.block_stack.push(BlockStackEntry::Pop {+ loop_depth: self.loop_stack.len(),+ });self.value_to_elaborated_value.increment_depth();self.elaborate_block(&mut elab_values, idom, block);@@ -850,8 +911,12 @@ impl<'a> Elaborator<'a> {// we can't `.rev()` above.)self.block_stack[block_stack_end..].reverse();}- BlockStackEntry::Pop => {+ BlockStackEntry::Pop { loop_depth } => {self.value_to_elaborated_value.decrement_depth();+ for entry in &self.loop_stack[loop_depth..] {+ self.loop_stack_index[entry.lp] = NOT_ON_LOOP_STACK;+ }+ self.loop_stack.truncate(loop_depth);}}}diff --git a/cranelift/filetests/filetests/egraph/licm-trap-block.clif b/cranelift/filetests/filetests/egraph/licm-trap-block.clifnew file mode 100644index 0000000000..f238693331--- /dev/null+++ b/cranelift/filetests/filetests/egraph/licm-trap-block.clif@@ -0,0 +1,154 @@+test optimize precise-output+set opt_level=speed+target x86_64++;; We can LICM values before and after a block that always traps inside the+;; middle of a loop.+function %licm_after_trap_block(i64, i64) -> i64 {+block0(v0: i64, v1: i64):+ v2 = iconst.i64 0+ jump block1(v2)++block1(v3: i64):+ ;; v20 is loop invariant, and should be hoisted into `block0`.+ v20 = load.i64 notrap aligned readonly can_move v0+232+ v21 = load.i32 notrap aligned v20+ brif v21, block10, block99++block99:+ trap user26++block10:+ ;; v4/v5/v6 are all loop invariant, and should be hoised into `block0`.+ v4 = load.i64 notrap aligned readonly can_move v0+72+ v5 = load.i64 notrap aligned readonly can_move v4+8+ v6 = load.i64 notrap aligned readonly can_move v5+104+ v7 = iadd v3, v6+ v8 = icmp ult v7, v1+ brif v8, block1(v7), block2++block2:+ return v7+}++; function %licm_after_trap_block(i64, i64) -> i64 fast {+; block0(v0: i64, v1: i64):+; v2 = iconst.i64 0+; v20 = load.i64 notrap aligned readonly can_move v0+232+; v4 = load.i64 notrap aligned readonly can_move v0+72+; v5 = load.i64 notrap aligned readonly can_move v4+8+; v6 = load.i64 notrap aligned readonly can_move v5+104+; jump block1(v2) ; v2 = 0+;+; block1(v3: i64):+; v21 = load.i32 notrap aligned v20+; trapz v21, user26+; jump block10+;+; block10:+; v7 = iadd.i64 v3, v6+; v8 = icmp ult v7, v1+; brif v8, block1(v7), block2+;+; block2:+; return v7+; }++;; Same, but with the layout order of the trapping and non-trapping loop blocks+;; swapped.+function %licm_after_trap_block_layout_reordered(i64, i64) -> i64 {+block0(v0: i64, v1: i64):+ v2 = iconst.i64 0+ jump block1(v2)++block1(v3: i64):+ v20 = load.i64 notrap aligned readonly can_move v0+232+ v21 = load.i32 notrap aligned v20+ brif v21, block10, block99++block10:+ v4 = load.i64 notrap aligned readonly can_move v0+72+ v5 = load.i64 notrap aligned readonly can_move v4+8+ v6 = load.i64 notrap aligned readonly can_move v5+104+ v7 = iadd v3, v6+ v8 = icmp ult v7, v1+ brif v8, block1(v7), block2++block99:+ trap user26++block2:+ return v7+}++; function %licm_after_trap_block_layout_reordered(i64, i64) -> i64 fast {+; block0(v0: i64, v1: i64):+; v2 = iconst.i64 0+; v20 = load.i64 notrap aligned readonly can_move v0+232+; v4 = load.i64 notrap aligned readonly can_move v0+72+; v5 = load.i64 notrap aligned readonly can_move v4+8+; v6 = load.i64 notrap aligned readonly can_move v5+104+; jump block1(v2) ; v2 = 0+;+; block1(v3: i64):+; v21 = load.i32 notrap aligned v20+; trapz v21, user26+; jump block10+;+; block10:+; v7 = iadd.i64 v3, v6+; v8 = icmp ult v7, v1+; brif v8, block1(v7), block2+;+; block2:+; return v7+; }++;; Same but witht he `brif` successors swapped.+function %licm_after_trap_block(i64, i64) -> i64 {+block0(v0: i64, v1: i64):+ v2 = iconst.i64 0+ jump block1(v2)++block1(v3: i64):+ v20 = load.i64 notrap aligned readonly can_move v0+232+ v21 = load.i32 notrap aligned v20+ brif v21, block99, block10++block99:+ trap user26++block10:+ v4 = load.i64 notrap aligned readonly can_move v0+72+ v5 = load.i64 notrap aligned readonly can_move v4+8+ v6 = load.i64 notrap aligned readonly can_move v5+104+ v7 = iadd v3, v6+ v8 = icmp ult v7, v1+ brif v8, block1(v7), block2++block2:+ return v7+}++; function %licm_after_trap_block(i64, i64) -> i64 fast {+; block0(v0: i64, v1: i64):+; v2 = iconst.i64 0+; v20 = load.i64 notrap aligned readonly can_move v0+232+; v4 = load.i64 notrap aligned readonly can_move v0+72+; v5 = load.i64 notrap aligned readonly can_move v4+8+; v6 = load.i64 notrap aligned readonly can_move v5+104+; jump block1(v2) ; v2 = 0+;+; block1(v3: i64):+; v21 = load.i32 notrap aligned v20+; trapnz v21, user26+; jump block10+;+; block10:+; v7 = iadd.i64 v3, v6+; v8 = icmp ult v7, v1+; brif v8, block1(v7), block2+;+; block2:+; return v7+; }diff --git a/tests/disas/stack-switching/resume-suspend-data-passing.wat b/tests/disas/stack-switching/resume-suspend-data-passing.watindex 1dcad97b8d..fc0ccbfadb 100644--- a/tests/disas/stack-switching/resume-suspend-data-passing.wat+++ b/tests/disas/stack-switching/resume-suspend-data-passing.wat@@ -234,6 +234,9 @@;; @0062 v61 = iconst.i64 96;; @0062 v64 = iconst.i64 -24;; v143 = iconst.i64 0x0001_0000_0000+;; @0062 v59 = iconst.i64 32+;; @0062 v77 = iconst.i64 4+;; @0062 v119 = iconst.i64 144;; @005c jump block2(v14);;;; block2(v15: i128):@@ -309,11 +312,11 @@;; @0062 brif v66, block9, block6;;;; block9:-;; @0062 v59 = iconst.i64 32-;; @0062 v76 = ushr.i64 v66, v59 ; v59 = 32-;; @0062 v77 = iconst.i64 4-;; @0062 v78 = icmp eq v76, v77 ; v77 = 4-;; @0062 brif v78, block8, block7+;; v165 = iconst.i64 32+;; v166 = ushr.i64 v66, v165 ; v165 = 32+;; v167 = iconst.i64 4+;; v168 = icmp eq v166, v167 ; v167 = 4+;; @0062 brif v168, block8, block7;;;; block8 cold:;; @0062 v81 = iconst.i32 5@@ -326,18 +329,18 @@;; @0062 store notrap aligned region8 v86, v26+64;; @0062 v87 = load.i64 notrap aligned region12 v28+24;; @0062 store notrap aligned region9 v87, v26+80-;; v168 = iconst.i32 0-;; v169 = iconst.i64 120-;; v170 = iadd.i64 v69, v169 ; v169 = 120-;; @0062 store notrap aligned region17 v168, v170 ; v168 = 0-;; @0062 store notrap aligned region14 v168, v170+4 ; v168 = 0-;; v171 = iconst.i64 0-;; @0062 store notrap aligned region15 v171, v170+8 ; v171 = 0-;; v172 = iconst.i64 144-;; v173 = iadd.i64 v69, v172 ; v172 = 144-;; @0062 store notrap aligned region17 v168, v173 ; v168 = 0-;; @0062 store notrap aligned region14 v168, v173+4 ; v168 = 0-;; @0062 store notrap aligned region15 v171, v173+8 ; v171 = 0+;; v174 = iconst.i32 0+;; v175 = iconst.i64 120+;; v176 = iadd.i64 v69, v175 ; v175 = 120+;; @0062 store notrap aligned region17 v174, v176 ; v174 = 0+;; @0062 store notrap aligned region14 v174, v176+4 ; v174 = 0+;; v177 = iconst.i64 0+;; @0062 store notrap aligned region15 v177, v176+8 ; v177 = 0+;; v178 = iconst.i64 144+;; v179 = iadd.i64 v69, v178 ; v178 = 144+;; @0062 store notrap aligned region17 v174, v179 ; v174 = 0+;; @0062 store notrap aligned region14 v174, v179+4 ; v174 = 0+;; @0062 store notrap aligned region15 v177, v179+8 ; v177 = 0;; @0062 try_call fn2(v0), sig2, block11, [ context v0 ];;;; block11:@@ -365,12 +368,12 @@;; @0062 trap user12;;;; block13:-;; @0062 v119 = iconst.i64 144-;; @0062 v120 = iadd.i64 v69, v119 ; v119 = 144-;; @0062 v121 = load.i64 notrap aligned region15 v120+8+;; v169 = iconst.i64 144+;; v170 = iadd.i64 v69, v169 ; v169 = 144+;; @0062 v121 = load.i64 notrap aligned region15 v170+8;; @0062 v122 = load.i32 notrap aligned region16 v121-;; v165 = iconst.i32 0-;; @0062 store notrap aligned region17 v165, v120 ; v165 = 0+;; v171 = iconst.i32 0+;; @0062 store notrap aligned region17 v171, v170 ; v171 = 0;; @0062 jump block4;;;; block10:@@ -400,9 +403,9 @@;;;; block4:;; @0062 v114 = uextend.i128 v112-;; v166 = iconst.i64 64-;; v167 = ishl v114, v166 ; v166 = 64+;; v172 = iconst.i64 64+;; v173 = ishl v114, v172 ; v172 = 64;; @0062 v113 = uextend.i128 v69-;; @0062 v118 = bor v167, v113+;; @0062 v118 = bor v173, v113;; @006d jump block2(v118);; }