1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Trivial copy propagation pass.
13 //! This uses def-use analysis to remove values that have exactly one def and one use, which must
16 //! To give an example, we look for patterns that look like:
22 //! where `DEST` and `SRC` are both locals of some form. We replace that with:
28 //! The assignment `DEST = SRC` must be (a) the only mutation of `DEST` and (b) the only
29 //! (non-mutating) use of `SRC`. These restrictions are conservative and may be relaxed in the
32 use rustc::mir::{Constant, Local, LocalKind, Location, Place, Mir, Operand, Rvalue, StatementKind};
33 use rustc::mir::visit::MutVisitor;
34 use rustc::ty::TyCtxt;
35 use transform::{MirPass, MirSource};
36 use util::def_use::DefUseAnalysis;
38 pub struct CopyPropagation;
40 impl MirPass for CopyPropagation {
41 fn run_pass<'a, 'tcx>(&self,
42 tcx: TyCtxt<'a, 'tcx, 'tcx>,
44 mir: &mut Mir<'tcx>) {
45 // We only run when the MIR optimization level is > 1.
46 // This avoids a slow pass, and messing up debug info.
47 if tcx.sess.opts.debugging_opts.mir_opt_level <= 1 {
51 let mut def_use_analysis = DefUseAnalysis::new(mir);
53 def_use_analysis.analyze(mir);
55 if eliminate_self_assignments(mir, &def_use_analysis) {
56 def_use_analysis.analyze(mir);
59 let mut changed = false;
60 for dest_local in mir.local_decls.indices() {
61 debug!("Considering destination local: {:?}", dest_local);
66 // The destination must have exactly one def.
67 let dest_use_info = def_use_analysis.local_info(dest_local);
68 let dest_def_count = dest_use_info.def_count_not_including_drop();
69 if dest_def_count == 0 {
70 debug!(" Can't copy-propagate local: dest {:?} undefined",
74 if dest_def_count > 1 {
75 debug!(" Can't copy-propagate local: dest {:?} defined {} times",
77 dest_use_info.def_count());
80 if dest_use_info.use_count() == 0 {
81 debug!(" Can't copy-propagate local: dest {:?} unused",
85 // Conservatively gives up if the dest is an argument,
86 // because there may be uses of the original argument value.
87 if mir.local_kind(dest_local) == LocalKind::Arg {
88 debug!(" Can't copy-propagate local: dest {:?} (argument)",
92 let dest_place_def = dest_use_info.defs_not_including_drop().next().unwrap();
93 location = dest_place_def.location;
95 let basic_block = &mir[location.block];
96 let statement_index = location.statement_index;
97 let statement = match basic_block.statements.get(statement_index) {
98 Some(statement) => statement,
100 debug!(" Can't copy-propagate local: used in terminator");
105 // That use of the source must be an assignment.
106 match statement.kind {
107 StatementKind::Assign(Place::Local(local), Rvalue::Use(ref operand)) if
108 local == dest_local => {
109 let maybe_action = match *operand {
110 Operand::Copy(ref src_place) |
111 Operand::Move(ref src_place) => {
112 Action::local_copy(&mir, &def_use_analysis, src_place)
114 Operand::Constant(ref src_constant) => {
115 Action::constant(src_constant)
119 Some(this_action) => action = this_action,
124 debug!(" Can't copy-propagate local: source use is not an \
131 changed = action.perform(mir, &def_use_analysis, dest_local, location) || changed;
132 // FIXME(pcwalton): Update the use-def chains to delete the instructions instead of
133 // regenerating the chains.
143 fn eliminate_self_assignments<'tcx>(
145 def_use_analysis: &DefUseAnalysis<'tcx>,
147 let mut changed = false;
149 for dest_local in mir.local_decls.indices() {
150 let dest_use_info = def_use_analysis.local_info(dest_local);
152 for def in dest_use_info.defs_not_including_drop() {
153 let location = def.location;
154 if let Some(stmt) = mir[location.block].statements.get(location.statement_index) {
156 StatementKind::Assign(
158 Rvalue::Use(Operand::Copy(Place::Local(src_local))),
160 StatementKind::Assign(
162 Rvalue::Use(Operand::Move(Place::Local(src_local))),
163 ) if local == dest_local && dest_local == src_local => {}
171 debug!("Deleting a self-assignment for {:?}", dest_local);
172 mir.make_statement_nop(location);
181 PropagateLocalCopy(Local),
182 PropagateConstant(Constant<'tcx>),
185 impl<'tcx> Action<'tcx> {
186 fn local_copy(mir: &Mir<'tcx>, def_use_analysis: &DefUseAnalysis, src_place: &Place<'tcx>)
187 -> Option<Action<'tcx>> {
188 // The source must be a local.
189 let src_local = if let Place::Local(local) = *src_place {
192 debug!(" Can't copy-propagate local: source is not a local");
196 // We're trying to copy propagate a local.
197 // There must be exactly one use of the source used in a statement (not in a terminator).
198 let src_use_info = def_use_analysis.local_info(src_local);
199 let src_use_count = src_use_info.use_count();
200 if src_use_count == 0 {
201 debug!(" Can't copy-propagate local: no uses");
204 if src_use_count != 1 {
205 debug!(" Can't copy-propagate local: {} uses", src_use_info.use_count());
209 // Verify that the source doesn't change in between. This is done conservatively for now,
210 // by ensuring that the source has exactly one mutation. The goal is to prevent things
217 // From being misoptimized into:
221 let src_def_count = src_use_info.def_count_not_including_drop();
222 // allow function arguments to be propagated
223 let is_arg = mir.local_kind(src_local) == LocalKind::Arg;
224 if (is_arg && src_def_count != 0) || (!is_arg && src_def_count != 1) {
226 " Can't copy-propagate local: {} defs of src{}",
228 if is_arg { " (argument)" } else { "" },
233 Some(Action::PropagateLocalCopy(src_local))
236 fn constant(src_constant: &Constant<'tcx>) -> Option<Action<'tcx>> {
237 Some(Action::PropagateConstant((*src_constant).clone()))
242 def_use_analysis: &DefUseAnalysis<'tcx>,
247 Action::PropagateLocalCopy(src_local) => {
248 // Eliminate the destination and the assignment.
250 // First, remove all markers.
252 // FIXME(pcwalton): Don't do this. Merge live ranges instead.
253 debug!(" Replacing all uses of {:?} with {:?} (local)",
256 for place_use in &def_use_analysis.local_info(dest_local).defs_and_uses {
257 if place_use.context.is_storage_marker() {
258 mir.make_statement_nop(place_use.location)
261 for place_use in &def_use_analysis.local_info(src_local).defs_and_uses {
262 if place_use.context.is_storage_marker() {
263 mir.make_statement_nop(place_use.location)
267 // Replace all uses of the destination local with the source local.
268 def_use_analysis.replace_all_defs_and_uses_with(dest_local, mir, src_local);
270 // Finally, zap the now-useless assignment instruction.
271 debug!(" Deleting assignment");
272 mir.make_statement_nop(location);
276 Action::PropagateConstant(src_constant) => {
277 // First, remove all markers.
279 // FIXME(pcwalton): Don't do this. Merge live ranges instead.
280 debug!(" Replacing all uses of {:?} with {:?} (constant)",
283 let dest_local_info = def_use_analysis.local_info(dest_local);
284 for place_use in &dest_local_info.defs_and_uses {
285 if place_use.context.is_storage_marker() {
286 mir.make_statement_nop(place_use.location)
290 // Replace all uses of the destination local with the constant.
291 let mut visitor = ConstantPropagationVisitor::new(dest_local,
293 for dest_place_use in &dest_local_info.defs_and_uses {
294 visitor.visit_location(mir, dest_place_use.location)
297 // Zap the assignment instruction if we eliminated all the uses. We won't have been
298 // able to do that if the destination was used in a projection, because projections
299 // must have places on their LHS.
300 let use_count = dest_local_info.use_count();
301 if visitor.uses_replaced == use_count {
302 debug!(" {} of {} use(s) replaced; deleting assignment",
303 visitor.uses_replaced,
305 mir.make_statement_nop(location);
307 } else if visitor.uses_replaced == 0 {
308 debug!(" No uses replaced; not deleting assignment");
311 debug!(" {} of {} use(s) replaced; not deleting assignment",
312 visitor.uses_replaced,
321 struct ConstantPropagationVisitor<'tcx> {
323 constant: Constant<'tcx>,
324 uses_replaced: usize,
327 impl<'tcx> ConstantPropagationVisitor<'tcx> {
328 fn new(dest_local: Local, constant: Constant<'tcx>)
329 -> ConstantPropagationVisitor<'tcx> {
330 ConstantPropagationVisitor {
338 impl<'tcx> MutVisitor<'tcx> for ConstantPropagationVisitor<'tcx> {
339 fn visit_operand(&mut self, operand: &mut Operand<'tcx>, location: Location) {
340 self.super_operand(operand, location);
343 Operand::Copy(Place::Local(local)) |
344 Operand::Move(Place::Local(local)) if local == self.dest_local => {}
348 *operand = Operand::Constant(box self.constant.clone());
349 self.uses_replaced += 1