]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_transform/src/const_goto.rs
Rollup merge of #105286 - willcrichton:maximal-hir-to-mir-coverage, r=cjgillot
[rust.git] / compiler / rustc_mir_transform / src / const_goto.rs
1 //! This pass optimizes the following sequence
2 //! ```rust,ignore (example)
3 //! bb2: {
4 //!     _2 = const true;
5 //!     goto -> bb3;
6 //! }
7 //!
8 //! bb3: {
9 //!     switchInt(_2) -> [false: bb4, otherwise: bb5];
10 //! }
11 //! ```
12 //! into
13 //! ```rust,ignore (example)
14 //! bb2: {
15 //!     _2 = const true;
16 //!     goto -> bb5;
17 //! }
18 //! ```
19
20 use crate::MirPass;
21 use rustc_middle::mir::*;
22 use rustc_middle::ty::TyCtxt;
23 use rustc_middle::{mir::visit::Visitor, ty::ParamEnv};
24
25 use super::simplify::{simplify_cfg, simplify_locals};
26
27 pub struct ConstGoto;
28
29 impl<'tcx> MirPass<'tcx> for ConstGoto {
30     fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
31         sess.mir_opt_level() >= 4
32     }
33
34     fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
35         trace!("Running ConstGoto on {:?}", body.source);
36         let param_env = tcx.param_env_reveal_all_normalized(body.source.def_id());
37         let mut opt_finder =
38             ConstGotoOptimizationFinder { tcx, body, optimizations: vec![], param_env };
39         opt_finder.visit_body(body);
40         let should_simplify = !opt_finder.optimizations.is_empty();
41         for opt in opt_finder.optimizations {
42             let block = &mut body.basic_blocks_mut()[opt.bb_with_goto];
43             block.statements.extend(opt.stmts_move_up);
44             let terminator = block.terminator_mut();
45             let new_goto = TerminatorKind::Goto { target: opt.target_to_use_in_goto };
46             debug!("SUCCESS: replacing `{:?}` with `{:?}`", terminator.kind, new_goto);
47             terminator.kind = new_goto;
48         }
49
50         // if we applied optimizations, we potentially have some cfg to cleanup to
51         // make it easier for further passes
52         if should_simplify {
53             simplify_cfg(tcx, body);
54             simplify_locals(body, tcx);
55         }
56     }
57 }
58
59 impl<'tcx> Visitor<'tcx> for ConstGotoOptimizationFinder<'_, 'tcx> {
60     fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
61         let _: Option<_> = try {
62             let target = terminator.kind.as_goto()?;
63             // We only apply this optimization if the last statement is a const assignment
64             let last_statement = self.body.basic_blocks[location.block].statements.last()?;
65
66             if let (place, Rvalue::Use(Operand::Constant(_const))) =
67                 last_statement.kind.as_assign()?
68             {
69                 // We found a constant being assigned to `place`.
70                 // Now check that the target of this Goto switches on this place.
71                 let target_bb = &self.body.basic_blocks[target];
72
73                 // The `StorageDead(..)` statement does not affect the functionality of mir.
74                 // We can move this part of the statement up to the predecessor.
75                 let mut stmts_move_up = Vec::new();
76                 for stmt in &target_bb.statements {
77                     if let StatementKind::StorageDead(..) = stmt.kind {
78                         stmts_move_up.push(stmt.clone())
79                     } else {
80                         None?;
81                     }
82                 }
83
84                 let target_bb_terminator = target_bb.terminator();
85                 let (discr, switch_ty, targets) = target_bb_terminator.kind.as_switch()?;
86                 if discr.place() == Some(*place) {
87                     // We now know that the Switch matches on the const place, and it is statementless
88                     // Now find which value in the Switch matches the const value.
89                     let const_value =
90                         _const.literal.try_eval_bits(self.tcx, self.param_env, switch_ty)?;
91                     let target_to_use_in_goto = targets.target_for_value(const_value);
92                     self.optimizations.push(OptimizationToApply {
93                         bb_with_goto: location.block,
94                         target_to_use_in_goto,
95                         stmts_move_up,
96                     });
97                 }
98             }
99             Some(())
100         };
101
102         self.super_terminator(terminator, location);
103     }
104 }
105
106 struct OptimizationToApply<'tcx> {
107     bb_with_goto: BasicBlock,
108     target_to_use_in_goto: BasicBlock,
109     stmts_move_up: Vec<Statement<'tcx>>,
110 }
111
112 pub struct ConstGotoOptimizationFinder<'a, 'tcx> {
113     tcx: TyCtxt<'tcx>,
114     body: &'a Body<'tcx>,
115     param_env: ParamEnv<'tcx>,
116     optimizations: Vec<OptimizationToApply<'tcx>>,
117 }