]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir/src/transform/match_branches.rs
Rollup merge of #81904 - jhpratt:const_int_fn-stabilization, r=jyn514
[rust.git] / compiler / rustc_mir / src / transform / match_branches.rs
1 use crate::transform::MirPass;
2 use rustc_middle::mir::*;
3 use rustc_middle::ty::TyCtxt;
4
5 pub struct MatchBranchSimplification;
6
7 /// If a source block is found that switches between two blocks that are exactly
8 /// the same modulo const bool assignments (e.g., one assigns true another false
9 /// to the same place), merge a target block statements into the source block,
10 /// using Eq / Ne comparison with switch value where const bools value differ.
11 ///
12 /// For example:
13 ///
14 /// ```rust
15 /// bb0: {
16 ///     switchInt(move _3) -> [42_isize: bb1, otherwise: bb2];
17 /// }
18 ///
19 /// bb1: {
20 ///     _2 = const true;
21 ///     goto -> bb3;
22 /// }
23 ///
24 /// bb2: {
25 ///     _2 = const false;
26 ///     goto -> bb3;
27 /// }
28 /// ```
29 ///
30 /// into:
31 ///
32 /// ```rust
33 /// bb0: {
34 ///    _2 = Eq(move _3, const 42_isize);
35 ///    goto -> bb3;
36 /// }
37 /// ```
38
39 impl<'tcx> MirPass<'tcx> for MatchBranchSimplification {
40     fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
41         if tcx.sess.opts.debugging_opts.mir_opt_level <= 1 {
42             return;
43         }
44
45         let param_env = tcx.param_env(body.source.def_id());
46         let def_id = body.source.def_id();
47         let (bbs, local_decls) = body.basic_blocks_and_local_decls_mut();
48         'outer: for bb_idx in bbs.indices() {
49             if !tcx.consider_optimizing(|| format!("MatchBranchSimplification {:?} ", def_id)) {
50                 continue;
51             }
52
53             let (discr, val, switch_ty, first, second) = match bbs[bb_idx].terminator().kind {
54                 TerminatorKind::SwitchInt {
55                     discr: ref discr @ (Operand::Copy(_) | Operand::Move(_)),
56                     switch_ty,
57                     ref targets,
58                     ..
59                 } if targets.iter().len() == 1 => {
60                     let (value, target) = targets.iter().next().unwrap();
61                     if target == targets.otherwise() {
62                         continue;
63                     }
64                     (discr, value, switch_ty, target, targets.otherwise())
65                 }
66                 // Only optimize switch int statements
67                 _ => continue,
68             };
69
70             // Check that destinations are identical, and if not, then don't optimize this block
71             if bbs[first].terminator().kind != bbs[second].terminator().kind {
72                 continue;
73             }
74
75             // Check that blocks are assignments of consts to the same place or same statement,
76             // and match up 1-1, if not don't optimize this block.
77             let first_stmts = &bbs[first].statements;
78             let scnd_stmts = &bbs[second].statements;
79             if first_stmts.len() != scnd_stmts.len() {
80                 continue;
81             }
82             for (f, s) in first_stmts.iter().zip(scnd_stmts.iter()) {
83                 match (&f.kind, &s.kind) {
84                     // If two statements are exactly the same, we can optimize.
85                     (f_s, s_s) if f_s == s_s => {}
86
87                     // If two statements are const bool assignments to the same place, we can optimize.
88                     (
89                         StatementKind::Assign(box (lhs_f, Rvalue::Use(Operand::Constant(f_c)))),
90                         StatementKind::Assign(box (lhs_s, Rvalue::Use(Operand::Constant(s_c)))),
91                     ) if lhs_f == lhs_s
92                         && f_c.literal.ty.is_bool()
93                         && s_c.literal.ty.is_bool()
94                         && f_c.literal.try_eval_bool(tcx, param_env).is_some()
95                         && s_c.literal.try_eval_bool(tcx, param_env).is_some() => {}
96
97                     // Otherwise we cannot optimize. Try another block.
98                     _ => continue 'outer,
99                 }
100             }
101             // Take ownership of items now that we know we can optimize.
102             let discr = discr.clone();
103
104             // Introduce a temporary for the discriminant value.
105             let source_info = bbs[bb_idx].terminator().source_info;
106             let discr_local = local_decls.push(LocalDecl::new(switch_ty, source_info.span));
107
108             // We already checked that first and second are different blocks,
109             // and bb_idx has a different terminator from both of them.
110             let (from, first, second) = bbs.pick3_mut(bb_idx, first, second);
111
112             let new_stmts = first.statements.iter().zip(second.statements.iter()).map(|(f, s)| {
113                 match (&f.kind, &s.kind) {
114                     (f_s, s_s) if f_s == s_s => (*f).clone(),
115
116                     (
117                         StatementKind::Assign(box (lhs, Rvalue::Use(Operand::Constant(f_c)))),
118                         StatementKind::Assign(box (_, Rvalue::Use(Operand::Constant(s_c)))),
119                     ) => {
120                         // From earlier loop we know that we are dealing with bool constants only:
121                         let f_b = f_c.literal.try_eval_bool(tcx, param_env).unwrap();
122                         let s_b = s_c.literal.try_eval_bool(tcx, param_env).unwrap();
123                         if f_b == s_b {
124                             // Same value in both blocks. Use statement as is.
125                             (*f).clone()
126                         } else {
127                             // Different value between blocks. Make value conditional on switch condition.
128                             let size = tcx.layout_of(param_env.and(switch_ty)).unwrap().size;
129                             let const_cmp = Operand::const_from_scalar(
130                                 tcx,
131                                 switch_ty,
132                                 crate::interpret::Scalar::from_uint(val, size),
133                                 rustc_span::DUMMY_SP,
134                             );
135                             let op = if f_b { BinOp::Eq } else { BinOp::Ne };
136                             let rhs = Rvalue::BinaryOp(
137                                 op,
138                                 Operand::Copy(Place::from(discr_local)),
139                                 const_cmp,
140                             );
141                             Statement {
142                                 source_info: f.source_info,
143                                 kind: StatementKind::Assign(box (*lhs, rhs)),
144                             }
145                         }
146                     }
147
148                     _ => unreachable!(),
149                 }
150             });
151
152             from.statements
153                 .push(Statement { source_info, kind: StatementKind::StorageLive(discr_local) });
154             from.statements.push(Statement {
155                 source_info,
156                 kind: StatementKind::Assign(box (Place::from(discr_local), Rvalue::Use(discr))),
157             });
158             from.statements.extend(new_stmts);
159             from.statements
160                 .push(Statement { source_info, kind: StatementKind::StorageDead(discr_local) });
161             from.terminator_mut().kind = first.terminator().kind.clone();
162         }
163     }
164 }