1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! A pass that simplifies branches when their condition is known.
13 use rustc::ty::{TyCtxt, ParamEnv};
15 use transform::{MirPass, MirSource};
19 pub struct SimplifyBranches { label: String }
21 impl SimplifyBranches {
22 pub fn new(label: &str) -> Self {
23 SimplifyBranches { label: format!("SimplifyBranches-{}", label) }
27 impl MirPass for SimplifyBranches {
28 fn name<'a>(&'a self) -> Cow<'a, str> {
29 Cow::Borrowed(&self.label)
32 fn run_pass<'a, 'tcx>(&self,
33 tcx: TyCtxt<'a, 'tcx, 'tcx>,
35 mir: &mut Mir<'tcx>) {
36 for block in mir.basic_blocks_mut() {
37 let terminator = block.terminator_mut();
38 terminator.kind = match terminator.kind {
39 TerminatorKind::SwitchInt {
40 discr: Operand::Constant(ref c), switch_ty, ref values, ref targets, ..
42 let switch_ty = ParamEnv::empty().and(switch_ty);
43 if let Some(constint) = c.literal.assert_bits(tcx, switch_ty) {
44 let (otherwise, targets) = targets.split_last().unwrap();
45 let mut ret = TerminatorKind::Goto { target: *otherwise };
46 for (&v, t) in values.iter().zip(targets.iter()) {
48 ret = TerminatorKind::Goto { target: *t };
57 TerminatorKind::Assert {
58 target, cond: Operand::Constant(ref c), expected, ..
59 } if (c.literal.assert_bool(tcx) == Some(true)) == expected => {
60 TerminatorKind::Goto { target: target }
62 TerminatorKind::FalseEdges { real_target, .. } => {
63 TerminatorKind::Goto { target: real_target }
65 TerminatorKind::FalseUnwind { real_target, .. } => {
66 TerminatorKind::Goto { target: real_target }