]> git.proxmox.com Git - rustc.git/blob - src/librustc_mir/transform/copy_prop.rs
New upstream version 1.20.0+dfsg1
[rustc.git] / src / librustc_mir / transform / copy_prop.rs
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.
4 //
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.
10
11 //! Trivial copy propagation pass.
12 //!
13 //! This uses def-use analysis to remove values that have exactly one def and one use, which must
14 //! be an assignment.
15 //!
16 //! To give an example, we look for patterns that look like:
17 //!
18 //! DEST = SRC
19 //! ...
20 //! USE(DEST)
21 //!
22 //! where `DEST` and `SRC` are both locals of some form. We replace that with:
23 //!
24 //! NOP
25 //! ...
26 //! USE(SRC)
27 //!
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
30 //! future.
31
32 use rustc::mir::{Constant, Local, LocalKind, Location, Lvalue, Mir, Operand, Rvalue, StatementKind};
33 use rustc::mir::transform::{MirPass, MirSource};
34 use rustc::mir::visit::MutVisitor;
35 use rustc::ty::TyCtxt;
36 use util::def_use::DefUseAnalysis;
37
38 pub struct CopyPropagation;
39
40 impl MirPass for CopyPropagation {
41 fn run_pass<'a, 'tcx>(&self,
42 tcx: TyCtxt<'a, 'tcx, 'tcx>,
43 source: MirSource,
44 mir: &mut Mir<'tcx>) {
45 match source {
46 MirSource::Const(_) => {
47 // Don't run on constants, because constant qualification might reject the
48 // optimized IR.
49 return
50 }
51 MirSource::Static(..) | MirSource::Promoted(..) => {
52 // Don't run on statics and promoted statics, because trans might not be able to
53 // evaluate the optimized IR.
54 return
55 }
56 MirSource::Fn(function_node_id) => {
57 if tcx.is_const_fn(tcx.hir.local_def_id(function_node_id)) {
58 // Don't run on const functions, as, again, trans might not be able to evaluate
59 // the optimized IR.
60 return
61 }
62 }
63 }
64
65 // We only run when the MIR optimization level is > 1.
66 // This avoids a slow pass, and messing up debug info.
67 if tcx.sess.opts.debugging_opts.mir_opt_level <= 1 {
68 return;
69 }
70
71 loop {
72 let mut def_use_analysis = DefUseAnalysis::new(mir);
73 def_use_analysis.analyze(mir);
74
75 let mut changed = false;
76 for dest_local in mir.local_decls.indices() {
77 debug!("Considering destination local: {:?}", dest_local);
78
79 let action;
80 let location;
81 {
82 // The destination must have exactly one def.
83 let dest_use_info = def_use_analysis.local_info(dest_local);
84 let dest_def_count = dest_use_info.def_count_not_including_drop();
85 if dest_def_count == 0 {
86 debug!(" Can't copy-propagate local: dest {:?} undefined",
87 dest_local);
88 continue
89 }
90 if dest_def_count > 1 {
91 debug!(" Can't copy-propagate local: dest {:?} defined {} times",
92 dest_local,
93 dest_use_info.def_count());
94 continue
95 }
96 if dest_use_info.use_count() == 0 {
97 debug!(" Can't copy-propagate local: dest {:?} unused",
98 dest_local);
99 continue
100 }
101 let dest_lvalue_def = dest_use_info.defs_and_uses.iter().filter(|lvalue_def| {
102 lvalue_def.context.is_mutating_use() && !lvalue_def.context.is_drop()
103 }).next().unwrap();
104 location = dest_lvalue_def.location;
105
106 let basic_block = &mir[location.block];
107 let statement_index = location.statement_index;
108 let statement = match basic_block.statements.get(statement_index) {
109 Some(statement) => statement,
110 None => {
111 debug!(" Can't copy-propagate local: used in terminator");
112 continue
113 }
114 };
115
116 // That use of the source must be an assignment.
117 match statement.kind {
118 StatementKind::Assign(Lvalue::Local(local), Rvalue::Use(ref operand)) if
119 local == dest_local => {
120 let maybe_action = match *operand {
121 Operand::Consume(ref src_lvalue) => {
122 Action::local_copy(&mir, &def_use_analysis, src_lvalue)
123 }
124 Operand::Constant(ref src_constant) => {
125 Action::constant(src_constant)
126 }
127 };
128 match maybe_action {
129 Some(this_action) => action = this_action,
130 None => continue,
131 }
132 }
133 _ => {
134 debug!(" Can't copy-propagate local: source use is not an \
135 assignment");
136 continue
137 }
138 }
139 }
140
141 changed = action.perform(mir, &def_use_analysis, dest_local, location) || changed;
142 // FIXME(pcwalton): Update the use-def chains to delete the instructions instead of
143 // regenerating the chains.
144 break
145 }
146 if !changed {
147 break
148 }
149 }
150 }
151 }
152
153 enum Action<'tcx> {
154 PropagateLocalCopy(Local),
155 PropagateConstant(Constant<'tcx>),
156 }
157
158 impl<'tcx> Action<'tcx> {
159 fn local_copy(mir: &Mir<'tcx>, def_use_analysis: &DefUseAnalysis, src_lvalue: &Lvalue<'tcx>)
160 -> Option<Action<'tcx>> {
161 // The source must be a local.
162 let src_local = if let Lvalue::Local(local) = *src_lvalue {
163 local
164 } else {
165 debug!(" Can't copy-propagate local: source is not a local");
166 return None;
167 };
168
169 // We're trying to copy propagate a local.
170 // There must be exactly one use of the source used in a statement (not in a terminator).
171 let src_use_info = def_use_analysis.local_info(src_local);
172 let src_use_count = src_use_info.use_count();
173 if src_use_count == 0 {
174 debug!(" Can't copy-propagate local: no uses");
175 return None
176 }
177 if src_use_count != 1 {
178 debug!(" Can't copy-propagate local: {} uses", src_use_info.use_count());
179 return None
180 }
181
182 // Verify that the source doesn't change in between. This is done conservatively for now,
183 // by ensuring that the source has exactly one mutation. The goal is to prevent things
184 // like:
185 //
186 // DEST = SRC;
187 // SRC = X;
188 // USE(DEST);
189 //
190 // From being misoptimized into:
191 //
192 // SRC = X;
193 // USE(SRC);
194 let src_def_count = src_use_info.def_count_not_including_drop();
195 // allow function arguments to be propagated
196 if src_def_count > 1 ||
197 (src_def_count == 0 && mir.local_kind(src_local) != LocalKind::Arg) {
198 debug!(" Can't copy-propagate local: {} defs of src",
199 src_use_info.def_count_not_including_drop());
200 return None
201 }
202
203 Some(Action::PropagateLocalCopy(src_local))
204 }
205
206 fn constant(src_constant: &Constant<'tcx>) -> Option<Action<'tcx>> {
207 Some(Action::PropagateConstant((*src_constant).clone()))
208 }
209
210 fn perform(self,
211 mir: &mut Mir<'tcx>,
212 def_use_analysis: &DefUseAnalysis<'tcx>,
213 dest_local: Local,
214 location: Location)
215 -> bool {
216 match self {
217 Action::PropagateLocalCopy(src_local) => {
218 // Eliminate the destination and the assignment.
219 //
220 // First, remove all markers.
221 //
222 // FIXME(pcwalton): Don't do this. Merge live ranges instead.
223 debug!(" Replacing all uses of {:?} with {:?} (local)",
224 dest_local,
225 src_local);
226 for lvalue_use in &def_use_analysis.local_info(dest_local).defs_and_uses {
227 if lvalue_use.context.is_storage_marker() {
228 mir.make_statement_nop(lvalue_use.location)
229 }
230 }
231 for lvalue_use in &def_use_analysis.local_info(src_local).defs_and_uses {
232 if lvalue_use.context.is_storage_marker() {
233 mir.make_statement_nop(lvalue_use.location)
234 }
235 }
236
237 // Replace all uses of the destination local with the source local.
238 let src_lvalue = Lvalue::Local(src_local);
239 def_use_analysis.replace_all_defs_and_uses_with(dest_local, mir, src_lvalue);
240
241 // Finally, zap the now-useless assignment instruction.
242 debug!(" Deleting assignment");
243 mir.make_statement_nop(location);
244
245 true
246 }
247 Action::PropagateConstant(src_constant) => {
248 // First, remove all markers.
249 //
250 // FIXME(pcwalton): Don't do this. Merge live ranges instead.
251 debug!(" Replacing all uses of {:?} with {:?} (constant)",
252 dest_local,
253 src_constant);
254 let dest_local_info = def_use_analysis.local_info(dest_local);
255 for lvalue_use in &dest_local_info.defs_and_uses {
256 if lvalue_use.context.is_storage_marker() {
257 mir.make_statement_nop(lvalue_use.location)
258 }
259 }
260
261 // Replace all uses of the destination local with the constant.
262 let mut visitor = ConstantPropagationVisitor::new(dest_local,
263 src_constant);
264 for dest_lvalue_use in &dest_local_info.defs_and_uses {
265 visitor.visit_location(mir, dest_lvalue_use.location)
266 }
267
268 // Zap the assignment instruction if we eliminated all the uses. We won't have been
269 // able to do that if the destination was used in a projection, because projections
270 // must have lvalues on their LHS.
271 let use_count = dest_local_info.use_count();
272 if visitor.uses_replaced == use_count {
273 debug!(" {} of {} use(s) replaced; deleting assignment",
274 visitor.uses_replaced,
275 use_count);
276 mir.make_statement_nop(location);
277 true
278 } else if visitor.uses_replaced == 0 {
279 debug!(" No uses replaced; not deleting assignment");
280 false
281 } else {
282 debug!(" {} of {} use(s) replaced; not deleting assignment",
283 visitor.uses_replaced,
284 use_count);
285 true
286 }
287 }
288 }
289 }
290 }
291
292 struct ConstantPropagationVisitor<'tcx> {
293 dest_local: Local,
294 constant: Constant<'tcx>,
295 uses_replaced: usize,
296 }
297
298 impl<'tcx> ConstantPropagationVisitor<'tcx> {
299 fn new(dest_local: Local, constant: Constant<'tcx>)
300 -> ConstantPropagationVisitor<'tcx> {
301 ConstantPropagationVisitor {
302 dest_local: dest_local,
303 constant: constant,
304 uses_replaced: 0,
305 }
306 }
307 }
308
309 impl<'tcx> MutVisitor<'tcx> for ConstantPropagationVisitor<'tcx> {
310 fn visit_operand(&mut self, operand: &mut Operand<'tcx>, location: Location) {
311 self.super_operand(operand, location);
312
313 match *operand {
314 Operand::Consume(Lvalue::Local(local)) if local == self.dest_local => {}
315 _ => return,
316 }
317
318 *operand = Operand::Constant(box self.constant.clone());
319 self.uses_replaced += 1
320 }
321 }