1 //! A pass that simplifies branches when their condition is known.
3 use rustc::ty::{TyCtxt, ParamEnv};
5 use crate::transform::{MirPass, MirSource};
9 pub struct SimplifyBranches { label: String }
11 impl SimplifyBranches {
12 pub fn new(label: &str) -> Self {
13 SimplifyBranches { label: format!("SimplifyBranches-{}", label) }
17 impl MirPass for SimplifyBranches {
18 fn name<'a>(&'a self) -> Cow<'a, str> {
19 Cow::Borrowed(&self.label)
22 fn run_pass<'a, 'tcx>(&self,
23 tcx: TyCtxt<'a, 'tcx, 'tcx>,
24 _src: MirSource<'tcx>,
25 mir: &mut Mir<'tcx>) {
26 for block in mir.basic_blocks_mut() {
27 let terminator = block.terminator_mut();
28 terminator.kind = match terminator.kind {
29 TerminatorKind::SwitchInt {
30 discr: Operand::Constant(ref c), switch_ty, ref values, ref targets, ..
32 let switch_ty = ParamEnv::empty().and(switch_ty);
33 let constant = c.literal.assert_bits(tcx, switch_ty);
34 if let Some(constant) = constant {
35 let (otherwise, targets) = targets.split_last().unwrap();
36 let mut ret = TerminatorKind::Goto { target: *otherwise };
37 for (&v, t) in values.iter().zip(targets.iter()) {
39 ret = TerminatorKind::Goto { target: *t };
48 TerminatorKind::Assert {
49 target, cond: Operand::Constant(ref c), expected, ..
50 } if (c.literal.assert_bool(tcx) == Some(true)) == expected =>
51 TerminatorKind::Goto { target },
52 TerminatorKind::FalseEdges { real_target, .. } => {
53 TerminatorKind::Goto { target: real_target }
55 TerminatorKind::FalseUnwind { real_target, .. } => {
56 TerminatorKind::Goto { target: real_target }