]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_mir_transform/src/simplify_branches.rs
New upstream version 1.59.0+dfsg1
[rustc.git] / compiler / rustc_mir_transform / src / simplify_branches.rs
CommitLineData
c295e0f8 1use crate::MirPass;
ba9703b0
XL
2use rustc_middle::mir::*;
3use rustc_middle::ty::TyCtxt;
3157f602 4
7cac9316 5use std::borrow::Cow;
3157f602 6
a2a8927a
XL
7/// A pass that replaces a branch with a goto when its condition is known.
8pub struct SimplifyConstCondition {
dfeec247
XL
9 label: String,
10}
3157f602 11
a2a8927a 12impl SimplifyConstCondition {
7cac9316 13 pub fn new(label: &str) -> Self {
a2a8927a 14 SimplifyConstCondition { label: format!("SimplifyConstCondition-{}", label) }
3157f602
XL
15 }
16}
17
a2a8927a 18impl<'tcx> MirPass<'tcx> for SimplifyConstCondition {
416331ca 19 fn name(&self) -> Cow<'_, str> {
7cac9316
XL
20 Cow::Borrowed(&self.label)
21 }
22
29967ef6
XL
23 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
24 let param_env = tcx.param_env(body.source.def_id());
dc9dc135 25 for block in body.basic_blocks_mut() {
3157f602
XL
26 let terminator = block.terminator_mut();
27 terminator.kind = match terminator.kind {
8faf50e0 28 TerminatorKind::SwitchInt {
dfeec247
XL
29 discr: Operand::Constant(ref c),
30 switch_ty,
dfeec247
XL
31 ref targets,
32 ..
8faf50e0 33 } => {
416331ca 34 let constant = c.literal.try_eval_bits(tcx, param_env, switch_ty);
0731742a 35 if let Some(constant) = constant {
a2a8927a
XL
36 let target = targets.target_for_value(constant);
37 TerminatorKind::Goto { target }
3157f602 38 } else {
dfeec247 39 continue;
3157f602 40 }
dfeec247 41 }
8faf50e0
XL
42 TerminatorKind::Assert {
43 target, cond: Operand::Constant(ref c), expected, ..
29967ef6
XL
44 } => match c.literal.try_eval_bool(tcx, param_env) {
45 Some(v) if v == expected => TerminatorKind::Goto { target },
46 _ => continue,
47 },
dfeec247 48 _ => continue,
3157f602
XL
49 };
50 }
51 }
52}