]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir/src/transform/simplify_branches.rs
Refactor how SwitchInt stores jump targets
[rust.git] / compiler / rustc_mir / src / transform / simplify_branches.rs
1 //! A pass that simplifies branches when their condition is known.
2
3 use crate::transform::MirPass;
4 use rustc_middle::mir::*;
5 use rustc_middle::ty::TyCtxt;
6
7 use std::borrow::Cow;
8
9 pub struct SimplifyBranches {
10     label: String,
11 }
12
13 impl SimplifyBranches {
14     pub fn new(label: &str) -> Self {
15         SimplifyBranches { label: format!("SimplifyBranches-{}", label) }
16     }
17 }
18
19 impl<'tcx> MirPass<'tcx> for SimplifyBranches {
20     fn name(&self) -> Cow<'_, str> {
21         Cow::Borrowed(&self.label)
22     }
23
24     fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
25         let param_env = tcx.param_env(body.source.def_id());
26         for block in body.basic_blocks_mut() {
27             let terminator = block.terminator_mut();
28             terminator.kind = match terminator.kind {
29                 TerminatorKind::SwitchInt {
30                     discr: Operand::Constant(ref c),
31                     switch_ty,
32                     ref targets,
33                     ..
34                 } => {
35                     let constant = c.literal.try_eval_bits(tcx, param_env, switch_ty);
36                     if let Some(constant) = constant {
37                         let otherwise = targets.otherwise();
38                         let mut ret = TerminatorKind::Goto { target: otherwise };
39                         for (v, t) in targets.iter() {
40                             if v == constant {
41                                 ret = TerminatorKind::Goto { target: t };
42                                 break;
43                             }
44                         }
45                         ret
46                     } else {
47                         continue;
48                     }
49                 }
50                 TerminatorKind::Assert {
51                     target, cond: Operand::Constant(ref c), expected, ..
52                 } if (c.literal.try_eval_bool(tcx, param_env) == Some(true)) == expected => {
53                     TerminatorKind::Goto { target }
54                 }
55                 TerminatorKind::FalseEdge { real_target, .. } => {
56                     TerminatorKind::Goto { target: real_target }
57                 }
58                 TerminatorKind::FalseUnwind { real_target, .. } => {
59                     TerminatorKind::Goto { target: real_target }
60                 }
61                 _ => continue,
62             };
63         }
64     }
65 }