]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_mir/src/transform/simplify_branches.rs
New upstream version 1.49.0+dfsg1
[rustc.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 } => match c.literal.try_eval_bool(tcx, param_env) {
53 Some(v) if v == expected => TerminatorKind::Goto { target },
54 _ => continue,
55 },
56 TerminatorKind::FalseEdge { real_target, .. } => {
57 TerminatorKind::Goto { target: real_target }
58 }
59 TerminatorKind::FalseUnwind { real_target, .. } => {
60 TerminatorKind::Goto { target: real_target }
61 }
62 _ => continue,
63 };
64 }
65 }
66 }