2020-12-31 18:53:25 -06:00
|
|
|
use crate::MirPass;
|
2020-03-29 09:41:09 -05:00
|
|
|
use rustc_middle::mir::*;
|
|
|
|
use rustc_middle::ty::TyCtxt;
|
2016-06-08 16:10:15 -05:00
|
|
|
|
2017-04-25 17:23:33 -05:00
|
|
|
use std::borrow::Cow;
|
2016-06-08 16:10:15 -05:00
|
|
|
|
2021-11-30 12:14:50 -06:00
|
|
|
/// A pass that replaces a branch with a goto when its condition is known.
|
|
|
|
pub struct SimplifyConstCondition {
|
2017-04-25 17:23:33 -05:00
|
|
|
label: String,
|
|
|
|
}
|
2016-06-08 16:10:15 -05:00
|
|
|
|
2021-11-30 12:14:50 -06:00
|
|
|
impl SimplifyConstCondition {
|
2017-04-25 17:23:33 -05:00
|
|
|
pub fn new(label: &str) -> Self {
|
2021-11-30 12:14:50 -06:00
|
|
|
SimplifyConstCondition { label: format!("SimplifyConstCondition-{}", label) }
|
2016-06-08 16:10:15 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-30 12:14:50 -06:00
|
|
|
impl<'tcx> MirPass<'tcx> for SimplifyConstCondition {
|
2019-06-21 11:12:39 -05:00
|
|
|
fn name(&self) -> Cow<'_, str> {
|
2017-04-25 17:23:33 -05:00
|
|
|
Cow::Borrowed(&self.label)
|
|
|
|
}
|
|
|
|
|
2020-10-04 13:01:38 -05:00
|
|
|
fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
|
|
|
|
let param_env = tcx.param_env(body.source.def_id());
|
2019-11-06 11:00:46 -06:00
|
|
|
for block in body.basic_blocks_mut() {
|
2019-10-03 23:55:28 -05:00
|
|
|
let terminator = block.terminator_mut();
|
2016-06-08 16:10:15 -05:00
|
|
|
terminator.kind = match terminator.kind {
|
2018-07-21 18:01:07 -05:00
|
|
|
TerminatorKind::SwitchInt {
|
|
|
|
discr: Operand::Constant(ref c),
|
|
|
|
switch_ty,
|
|
|
|
ref targets,
|
|
|
|
..
|
|
|
|
} => {
|
2019-03-31 11:35:39 -05:00
|
|
|
let constant = c.literal.try_eval_bits(tcx, param_env, switch_ty);
|
2018-12-13 04:15:18 -06:00
|
|
|
if let Some(constant) = constant {
|
2021-11-26 20:18:14 -06:00
|
|
|
let target = targets.target_for_value(constant);
|
|
|
|
TerminatorKind::Goto { target }
|
2017-02-02 00:41:01 -06:00
|
|
|
} else {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
}
|
2018-07-21 18:01:07 -05:00
|
|
|
TerminatorKind::Assert {
|
|
|
|
target, cond: Operand::Constant(ref c), expected, ..
|
2020-10-20 19:00:00 -05:00
|
|
|
} => match c.literal.try_eval_bool(tcx, param_env) {
|
|
|
|
Some(v) if v == expected => TerminatorKind::Goto { target },
|
|
|
|
_ => continue,
|
|
|
|
},
|
2016-06-08 16:10:15 -05:00
|
|
|
_ => continue,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|