Skip to content

Commit 76bc6c3

Browse files
committed
Reimplement simplify_cfg for SwitchInt
First example of optimisation that applies to many more cases than originally.
1 parent 3393584 commit 76bc6c3

File tree

1 file changed

+18
-14
lines changed

1 file changed

+18
-14
lines changed

src/librustc_mir/transform/simplify_branches.rs

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -30,26 +30,30 @@ impl<'l, 'tcx> MirPass<'tcx> for SimplifyBranches<'l> {
3030
for block in mir.basic_blocks_mut() {
3131
let terminator = block.terminator_mut();
3232
terminator.kind = match terminator.kind {
33-
// TerminatorKind::If { ref targets, cond: Operand::Constant(Constant {
34-
// literal: Literal::Value {
35-
// value: ConstVal::Bool(cond)
36-
// }, ..
37-
// }) } => {
38-
// if cond {
39-
// TerminatorKind::Goto { target: targets.0 }
40-
// } else {
41-
// TerminatorKind::Goto { target: targets.1 }
42-
// }
43-
// }
44-
33+
TerminatorKind::SwitchInt { discr: Operand::Constant(Constant {
34+
literal: Literal::Value { ref value }, ..
35+
}), ref values, ref targets, .. } => {
36+
if let Some(ref constint) = value.to_const_int() {
37+
let (otherwise, targets) = targets.split_last().unwrap();
38+
let mut ret = TerminatorKind::Goto { target: *otherwise };
39+
for (v, t) in values.iter().zip(targets.iter()) {
40+
if v == constint {
41+
ret = TerminatorKind::Goto { target: *t };
42+
break;
43+
}
44+
}
45+
ret
46+
} else {
47+
continue
48+
}
49+
},
4550
TerminatorKind::Assert { target, cond: Operand::Constant(Constant {
4651
literal: Literal::Value {
4752
value: ConstVal::Bool(cond)
4853
}, ..
4954
}), expected, .. } if cond == expected => {
5055
TerminatorKind::Goto { target: target }
51-
}
52-
56+
},
5357
_ => continue
5458
};
5559
}

0 commit comments

Comments
 (0)