rust/compiler/rustc_mir/src/transform/simplify_branches.rs

66 lines
2.3 KiB
Rust
Raw Normal View History

//! A pass that simplifies branches when their condition is known.
use crate::transform::MirPass;
2020-03-29 14:41:09 +00:00
use rustc_middle::mir::*;
use rustc_middle::ty::TyCtxt;
use std::borrow::Cow;
2019-12-22 22:42:04 +00:00
pub struct SimplifyBranches {
label: String,
}
impl SimplifyBranches {
pub fn new(label: &str) -> Self {
SimplifyBranches { label: format!("SimplifyBranches-{}", label) }
}
}
2019-08-04 20:20:00 +00:00
impl<'tcx> MirPass<'tcx> for SimplifyBranches {
2019-06-21 16:12:39 +00:00
fn name(&self) -> Cow<'_, str> {
Cow::Borrowed(&self.label)
}
fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
let param_env = tcx.param_env(body.source.def_id());
for block in body.basic_blocks_mut() {
let terminator = block.terminator_mut();
terminator.kind = match terminator.kind {
TerminatorKind::SwitchInt {
2019-12-22 22:42:04 +00:00
discr: Operand::Constant(ref c),
switch_ty,
ref targets,
..
} => {
let constant = c.literal.try_eval_bits(tcx, param_env, switch_ty);
2018-12-13 10:15:18 +00:00
if let Some(constant) = constant {
let otherwise = targets.otherwise();
let mut ret = TerminatorKind::Goto { target: otherwise };
for (v, t) in targets.iter() {
2018-12-13 10:15:18 +00:00
if v == constant {
ret = TerminatorKind::Goto { target: t };
2018-12-13 10:15:18 +00:00
break;
}
}
2018-12-13 10:15:18 +00:00
ret
} else {
2019-12-22 22:42:04 +00:00
continue;
}
2019-12-22 22:42:04 +00:00
}
TerminatorKind::Assert {
target, cond: Operand::Constant(ref c), expected, ..
2019-12-22 22:42:04 +00:00
} if (c.literal.try_eval_bool(tcx, param_env) == Some(true)) == expected => {
TerminatorKind::Goto { target }
}
2020-06-02 07:15:24 +00:00
TerminatorKind::FalseEdge { real_target, .. } => {
TerminatorKind::Goto { target: real_target }
2019-12-22 22:42:04 +00:00
}
TerminatorKind::FalseUnwind { real_target, .. } => {
TerminatorKind::Goto { target: real_target }
2019-12-22 22:42:04 +00:00
}
_ => continue,
};
}
}
}