1 //! Propagates assignment destinations backwards in the CFG to eliminate redundant assignments.
5 //! MIR building can insert a lot of redundant copies, and Rust code in general often tends to move
6 //! values around a lot. The result is a lot of assignments of the form `dest = {move} src;` in MIR.
7 //! MIR building for constants in particular tends to create additional locals that are only used
8 //! inside a single block to shuffle a value around unnecessarily.
10 //! LLVM by itself is not good enough at eliminating these redundant copies (eg. see
11 //! <https://github.com/rust-lang/rust/issues/32966>), so this leaves some performance on the table
12 //! that we can regain by implementing an optimization for removing these assign statements in rustc
13 //! itself. When this optimization runs fast enough, it can also speed up the constant evaluation
14 //! and code generation phases of rustc due to the reduced number of statements and locals.
16 //! # The Optimization
18 //! Conceptually, this optimization is "destination propagation". It is similar to the Named Return
19 //! Value Optimization, or NRVO, known from the C++ world, except that it isn't limited to return
20 //! values or the return place `_0`. On a very high level, independent of the actual implementation
21 //! details, it does the following:
23 //! 1) Identify `dest = src;` statements that can be soundly eliminated.
24 //! 2) Replace all mentions of `src` with `dest` ("unifying" them and propagating the destination
26 //! 3) Delete the `dest = src;` statement (by making it a `nop`).
28 //! Step 1) is by far the hardest, so it is explained in more detail below.
32 //! Given an `Assign` statement `dest = src;`, where `dest` is a `Place` and `src` is an `Rvalue`,
33 //! there are a few requirements that must hold for the optimization to be sound:
35 //! * `dest` must not contain any *indirection* through a pointer. It must access part of the base
36 //! local. Otherwise it might point to arbitrary memory that is hard to track.
38 //! It must also not contain any indexing projections, since those take an arbitrary `Local` as
39 //! the index, and that local might only be initialized shortly before `dest` is used.
41 //! Subtle case: If `dest` is a, or projects through a union, then we have to make sure that there
42 //! remains an assignment to it, since that sets the "active field" of the union. But if `src` is
43 //! a ZST, it might not be initialized, so there might not be any use of it before the assignment,
44 //! and performing the optimization would simply delete the assignment, leaving `dest`
47 //! * `src` must be a bare `Local` without any indirections or field projections (FIXME: Is this a
48 //! fundamental restriction or just current impl state?). It can be copied or moved by the
51 //! * The `dest` and `src` locals must never be [*live*][liveness] at the same time. If they are, it
52 //! means that they both hold a (potentially different) value that is needed by a future use of
53 //! the locals. Unifying them would overwrite one of the values.
55 //! Note that computing liveness of locals that have had their address taken is more difficult:
56 //! Short of doing full escape analysis on the address/pointer/reference, the pass would need to
57 //! assume that any operation that can potentially involve opaque user code (such as function
58 //! calls, destructors, and inline assembly) may access any local that had its address taken
59 //! before that point.
61 //! Here, the first two conditions are simple structural requirements on the `Assign` statements
62 //! that can be trivially checked. The liveness requirement however is more difficult and costly to
67 //! A [previous attempt] at implementing an optimization like this turned out to be a significant
68 //! regression in compiler performance. Fixing the regressions introduced a lot of undesirable
69 //! complexity to the implementation.
71 //! A [subsequent approach] tried to avoid the costly computation by limiting itself to acyclic
72 //! CFGs, but still turned out to be far too costly to run due to suboptimal performance within
73 //! individual basic blocks, requiring a walk across the entire block for every assignment found
74 //! within the block. For the `tuple-stress` benchmark, which has 458745 statements in a single
75 //! block, this proved to be far too costly.
77 //! Since the first attempt at this, the compiler has improved dramatically, and new analysis
78 //! frameworks have been added that should make this approach viable without requiring a limited
79 //! approach that only works for some classes of CFGs:
80 //! - rustc now has a powerful dataflow analysis framework that can handle forwards and backwards
81 //! analyses efficiently.
82 //! - Layout optimizations for generators have been added to improve code generation for
83 //! async/await, which are very similar in spirit to what this optimization does. Both walk the
84 //! MIR and record conflicting uses of locals in a `BitMatrix`.
86 //! Also, rustc now has a simple NRVO pass (see `nrvo.rs`), which handles a subset of the cases that
87 //! this destination propagation pass handles, proving that similar optimizations can be performed
90 //! ## Pre/Post Optimization
92 //! It is recommended to run `SimplifyCfg` and then `SimplifyLocals` some time after this pass, as
93 //! it replaces the eliminated assign statements with `nop`s and leaves unused locals behind.
95 //! [liveness]: https://en.wikipedia.org/wiki/Live_variable_analysis
96 //! [previous attempt]: https://github.com/rust-lang/rust/pull/47954
97 //! [subsequent approach]: https://github.com/rust-lang/rust/pull/71003
99 use crate::dataflow::impls::{MaybeInitializedLocals, MaybeLiveLocals};
100 use crate::dataflow::Analysis;
103 util::{dump_mir, PassWhere},
105 use itertools::Itertools;
106 use rustc_data_structures::unify::{InPlaceUnificationTable, UnifyKey};
108 bit_set::{BitMatrix, BitSet},
111 use rustc_middle::mir::tcx::PlaceTy;
112 use rustc_middle::mir::visit::{MutVisitor, PlaceContext, Visitor};
113 use rustc_middle::mir::{
114 traversal, Body, InlineAsmOperand, Local, LocalKind, Location, Operand, Place, PlaceElem,
115 Rvalue, Statement, StatementKind, Terminator, TerminatorKind,
117 use rustc_middle::ty::{self, Ty, TyCtxt};
119 // Empirical measurements have resulted in some observations:
120 // - Running on a body with a single block and 500 locals takes barely any time
121 // - Running on a body with ~400 blocks and ~300 relevant locals takes "too long"
122 // ...so we just limit both to somewhat reasonable-ish looking values.
123 const MAX_LOCALS: usize = 500;
124 const MAX_BLOCKS: usize = 250;
126 pub struct DestinationPropagation;
128 impl<'tcx> MirPass<'tcx> for DestinationPropagation {
129 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
130 // Only run at mir-opt-level=2 or higher for now (we don't fix up debuginfo and remove
131 // storage statements at the moment).
132 if tcx.sess.opts.debugging_opts.mir_opt_level <= 1 {
136 let def_id = body.source.def_id();
138 let candidates = find_candidates(tcx, body);
139 if candidates.is_empty() {
140 debug!("{:?}: no dest prop candidates, done", def_id);
144 // Collect all locals we care about. We only compute conflicts for these to save time.
145 let mut relevant_locals = BitSet::new_empty(body.local_decls.len());
146 for CandidateAssignment { dest, src, loc: _ } in &candidates {
147 relevant_locals.insert(dest.local);
148 relevant_locals.insert(*src);
151 // This pass unfortunately has `O(l² * s)` performance, where `l` is the number of locals
152 // and `s` is the number of statements and terminators in the function.
153 // To prevent blowing up compile times too much, we bail out when there are too many locals.
154 let relevant = relevant_locals.count();
156 "{:?}: {} locals ({} relevant), {} blocks",
158 body.local_decls.len(),
160 body.basic_blocks().len()
162 if relevant > MAX_LOCALS {
164 "too many candidate locals in {:?} ({}, max is {}), not optimizing",
165 def_id, relevant, MAX_LOCALS
169 if body.basic_blocks().len() > MAX_BLOCKS {
171 "too many blocks in {:?} ({}, max is {}), not optimizing",
173 body.basic_blocks().len(),
179 let mut conflicts = Conflicts::build(tcx, body, &relevant_locals);
181 let mut replacements = Replacements::new(body.local_decls.len());
182 for candidate @ CandidateAssignment { dest, src, loc } in candidates {
183 // Merge locals that don't conflict.
184 if !conflicts.can_unify(dest.local, src) {
185 debug!("at assignment {:?}, conflict {:?} vs. {:?}", loc, dest.local, src);
189 if replacements.for_src(candidate.src).is_some() {
190 debug!("src {:?} already has replacement", candidate.src);
194 if !tcx.consider_optimizing(|| {
195 format!("DestinationPropagation {:?} {:?}", def_id, candidate)
200 replacements.push(candidate);
201 conflicts.unify(candidate.src, candidate.dest.local);
204 replacements.flatten(tcx);
206 debug!("replacements {:?}", replacements.map);
208 Replacer { tcx, replacements, place_elem_cache: Vec::new() }.visit_body(body);
210 // FIXME fix debug info
214 #[derive(Debug, Eq, PartialEq, Copy, Clone)]
215 struct UnifyLocal(Local);
217 impl From<Local> for UnifyLocal {
218 fn from(l: Local) -> Self {
223 impl UnifyKey for UnifyLocal {
225 fn index(&self) -> u32 {
228 fn from_index(u: u32) -> Self {
229 Self(Local::from_u32(u))
231 fn tag() -> &'static str {
236 struct Replacements<'tcx> {
237 /// Maps locals to their replacement.
238 map: IndexVec<Local, Option<Place<'tcx>>>,
240 /// Whose locals' live ranges to kill.
244 impl Replacements<'tcx> {
245 fn new(locals: usize) -> Self {
246 Self { map: IndexVec::from_elem_n(None, locals), kill: BitSet::new_empty(locals) }
249 fn push(&mut self, candidate: CandidateAssignment<'tcx>) {
250 trace!("Replacements::push({:?})", candidate);
251 let entry = &mut self.map[candidate.src];
252 assert!(entry.is_none());
254 *entry = Some(candidate.dest);
255 self.kill.insert(candidate.src);
256 self.kill.insert(candidate.dest.local);
259 /// Applies the stored replacements to all replacements, until no replacements would result in
260 /// locals that need further replacements when applied.
261 fn flatten(&mut self, tcx: TyCtxt<'tcx>) {
262 // Note: This assumes that there are no cycles in the replacements, which is enforced via
263 // `self.unified_locals`. Otherwise this can cause an infinite loop.
265 for local in self.map.indices() {
266 if let Some(replacement) = self.map[local] {
267 // Substitute the base local of `replacement` until fixpoint.
268 let mut base = replacement.local;
269 let mut reversed_projection_slices = Vec::with_capacity(1);
270 while let Some(replacement_for_replacement) = self.map[base] {
271 base = replacement_for_replacement.local;
272 reversed_projection_slices.push(replacement_for_replacement.projection);
275 let projection: Vec<_> = reversed_projection_slices
278 .flat_map(|projs| projs.iter())
279 .chain(replacement.projection.iter())
281 let projection = tcx.intern_place_elems(&projection);
283 // Replace with the final `Place`.
284 self.map[local] = Some(Place { local: base, projection });
289 fn for_src(&self, src: Local) -> Option<Place<'tcx>> {
294 struct Replacer<'tcx> {
296 replacements: Replacements<'tcx>,
297 place_elem_cache: Vec<PlaceElem<'tcx>>,
300 impl<'tcx> MutVisitor<'tcx> for Replacer<'tcx> {
301 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
305 fn visit_local(&mut self, local: &mut Local, context: PlaceContext, location: Location) {
306 if context.is_use() && self.replacements.for_src(*local).is_some() {
308 "use of local {:?} should have been replaced by visit_place; context={:?}, loc={:?}",
316 fn process_projection_elem(
318 elem: PlaceElem<'tcx>,
320 ) -> Option<PlaceElem<'tcx>> {
322 PlaceElem::Index(local) => {
323 if let Some(replacement) = self.replacements.for_src(local) {
325 "cannot replace {:?} with {:?} in index projection {:?}",
338 fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
339 if let Some(replacement) = self.replacements.for_src(place.local) {
340 // Rebase `place`s projections onto `replacement`'s.
341 self.place_elem_cache.clear();
342 self.place_elem_cache.extend(replacement.projection.iter().chain(place.projection));
343 let projection = self.tcx.intern_place_elems(&self.place_elem_cache);
344 let new_place = Place { local: replacement.local, projection };
346 debug!("Replacer: {:?} -> {:?}", place, new_place);
350 self.super_place(place, context, location);
353 fn visit_statement(&mut self, statement: &mut Statement<'tcx>, location: Location) {
354 self.super_statement(statement, location);
356 match &statement.kind {
357 // FIXME: Don't delete storage statements, merge the live ranges instead
358 StatementKind::StorageDead(local) | StatementKind::StorageLive(local)
359 if self.replacements.kill.contains(*local) =>
364 StatementKind::Assign(box (dest, rvalue)) => {
366 Rvalue::Use(Operand::Copy(place) | Operand::Move(place)) => {
367 // These might've been turned into self-assignments by the replacement
368 // (this includes the original statement we wanted to eliminate).
370 debug!("{:?} turned into self-assignment, deleting", location);
371 statement.make_nop();
383 struct Conflicts<'a> {
384 relevant_locals: &'a BitSet<Local>,
386 /// The conflict matrix. It is always symmetric and the adjacency matrix of the corresponding
388 matrix: BitMatrix<Local, Local>,
390 /// Preallocated `BitSet` used by `unify`.
391 unify_cache: BitSet<Local>,
393 /// Tracks locals that have been merged together to prevent cycles and propagate conflicts.
394 unified_locals: InPlaceUnificationTable<UnifyLocal>,
400 body: &'_ Body<'tcx>,
401 relevant_locals: &'a BitSet<Local>,
403 // We don't have to look out for locals that have their address taken, since
404 // `find_candidates` already takes care of that.
406 let conflicts = BitMatrix::from_row_n(
407 &BitSet::new_empty(body.local_decls.len()),
408 body.local_decls.len(),
411 let mut init = MaybeInitializedLocals
412 .into_engine(tcx, body)
413 .iterate_to_fixpoint()
414 .into_results_cursor(body);
416 MaybeLiveLocals.into_engine(tcx, body).iterate_to_fixpoint().into_results_cursor(body);
418 let mut reachable = None;
419 dump_mir(tcx, None, "DestinationPropagation-dataflow", &"", body, |pass_where, w| {
420 let reachable = reachable.get_or_insert_with(|| traversal::reachable_as_bitset(body));
423 PassWhere::BeforeLocation(loc) if reachable.contains(loc.block) => {
424 init.seek_before_primary_effect(loc);
425 live.seek_after_primary_effect(loc);
427 writeln!(w, " // init: {:?}", init.get())?;
428 writeln!(w, " // live: {:?}", live.get())?;
430 PassWhere::AfterTerminator(bb) if reachable.contains(bb) => {
431 let loc = body.terminator_loc(bb);
432 init.seek_after_primary_effect(loc);
433 live.seek_before_primary_effect(loc);
435 writeln!(w, " // init: {:?}", init.get())?;
436 writeln!(w, " // live: {:?}", live.get())?;
439 PassWhere::BeforeBlock(bb) if reachable.contains(bb) => {
440 init.seek_to_block_start(bb);
441 live.seek_to_block_start(bb);
443 writeln!(w, " // init: {:?}", init.get())?;
444 writeln!(w, " // live: {:?}", live.get())?;
447 PassWhere::BeforeCFG | PassWhere::AfterCFG | PassWhere::AfterLocation(_) => {}
449 PassWhere::BeforeLocation(_) | PassWhere::AfterTerminator(_) => {
450 writeln!(w, " // init: <unreachable>")?;
451 writeln!(w, " // live: <unreachable>")?;
454 PassWhere::BeforeBlock(_) => {
455 writeln!(w, " // init: <unreachable>")?;
456 writeln!(w, " // live: <unreachable>")?;
463 let mut this = Self {
466 unify_cache: BitSet::new_empty(body.local_decls.len()),
468 let mut table = InPlaceUnificationTable::new();
469 // Pre-fill table with all locals (this creates N nodes / "connected" components,
470 // "graph"-ically speaking).
471 for local in 0..body.local_decls.len() {
472 assert_eq!(table.new_key(()), UnifyLocal(Local::from_usize(local)));
478 let mut live_and_init_locals = Vec::new();
480 // Visit only reachable basic blocks. The exact order is not important.
481 for (block, data) in traversal::preorder(body) {
482 // We need to observe the dataflow state *before* all possible locations (statement or
483 // terminator) in each basic block, and then observe the state *after* the terminator
484 // effect is applied. As long as neither `init` nor `borrowed` has a "before" effect,
485 // we will observe all possible dataflow states.
487 // Since liveness is a backwards analysis, we need to walk the results backwards. To do
488 // that, we first collect in the `MaybeInitializedLocals` results in a forwards
491 live_and_init_locals.resize_with(data.statements.len() + 1, || {
492 BitSet::new_empty(body.local_decls.len())
495 // First, go forwards for `MaybeInitializedLocals` and apply intra-statement/terminator
497 for (i, statement) in data.statements.iter().enumerate() {
498 this.record_statement_conflicts(statement);
500 let loc = Location { block, statement_index: i };
501 init.seek_before_primary_effect(loc);
503 live_and_init_locals[i].clone_from(init.get());
506 this.record_terminator_conflicts(data.terminator());
507 let term_loc = Location { block, statement_index: data.statements.len() };
508 init.seek_before_primary_effect(term_loc);
509 live_and_init_locals[term_loc.statement_index].clone_from(init.get());
511 // Now, go backwards and union with the liveness results.
512 for statement_index in (0..=data.statements.len()).rev() {
513 let loc = Location { block, statement_index };
514 live.seek_after_primary_effect(loc);
516 live_and_init_locals[statement_index].intersect(live.get());
518 trace!("record conflicts at {:?}", loc);
520 this.record_dataflow_conflicts(&mut live_and_init_locals[statement_index]);
523 init.seek_to_block_end(block);
524 live.seek_to_block_end(block);
525 let mut conflicts = init.get().clone();
526 conflicts.intersect(live.get());
527 trace!("record conflicts at end of {:?}", block);
529 this.record_dataflow_conflicts(&mut conflicts);
535 fn record_dataflow_conflicts(&mut self, new_conflicts: &mut BitSet<Local>) {
536 // Remove all locals that are not candidates.
537 new_conflicts.intersect(self.relevant_locals);
539 for local in new_conflicts.iter() {
540 self.matrix.union_row_with(&new_conflicts, local);
544 fn record_local_conflict(&mut self, a: Local, b: Local, why: &str) {
545 trace!("conflict {:?} <-> {:?} due to {}", a, b, why);
546 self.matrix.insert(a, b);
547 self.matrix.insert(b, a);
550 /// Records locals that must not overlap during the evaluation of `stmt`. These locals conflict
551 /// and must not be merged.
552 fn record_statement_conflicts(&mut self, stmt: &Statement<'_>) {
554 // While the left and right sides of an assignment must not overlap, we do not mark
555 // conflicts here as that would make this optimization useless. When we optimize, we
556 // eliminate the resulting self-assignments automatically.
557 StatementKind::Assign(_) => {}
559 StatementKind::LlvmInlineAsm(asm) => {
560 // Inputs and outputs must not overlap.
561 for (_, input) in &*asm.inputs {
562 if let Some(in_place) = input.place() {
563 if !in_place.is_indirect() {
564 for out_place in &*asm.outputs {
565 if !out_place.is_indirect() && !in_place.is_indirect() {
566 self.record_local_conflict(
569 "aliasing llvm_asm! operands",
578 StatementKind::SetDiscriminant { .. }
579 | StatementKind::StorageLive(..)
580 | StatementKind::StorageDead(..)
581 | StatementKind::Retag(..)
582 | StatementKind::FakeRead(..)
583 | StatementKind::AscribeUserType(..)
584 | StatementKind::Coverage(..)
585 | StatementKind::Nop => {}
589 fn record_terminator_conflicts(&mut self, term: &Terminator<'_>) {
591 TerminatorKind::DropAndReplace {
592 place: dropped_place,
597 if let Some(place) = value.place() {
598 if !place.is_indirect() && !dropped_place.is_indirect() {
599 self.record_local_conflict(
602 "DropAndReplace operand overlap",
607 TerminatorKind::Yield { value, resume: _, resume_arg, drop: _ } => {
608 if let Some(place) = value.place() {
609 if !place.is_indirect() && !resume_arg.is_indirect() {
610 self.record_local_conflict(
613 "Yield operand overlap",
618 TerminatorKind::Call {
621 destination: Some((dest_place, _)),
626 // No arguments may overlap with the destination.
627 for arg in args.iter().chain(Some(func)) {
628 if let Some(place) = arg.place() {
629 if !place.is_indirect() && !dest_place.is_indirect() {
630 self.record_local_conflict(
633 "call dest/arg overlap",
639 TerminatorKind::InlineAsm {
646 // The intended semantics here aren't documented, we just assume that nothing that
647 // could be written to by the assembly may overlap with any other operands.
650 InlineAsmOperand::Out { reg: _, late: _, place: Some(dest_place) }
651 | InlineAsmOperand::InOut {
655 out_place: Some(dest_place),
657 // For output place `place`, add all places accessed by the inline asm.
660 InlineAsmOperand::In { reg: _, value } => {
661 if let Some(p) = value.place() {
662 if !p.is_indirect() && !dest_place.is_indirect() {
663 self.record_local_conflict(
666 "asm! operand overlap",
671 InlineAsmOperand::Out {
676 if !place.is_indirect() && !dest_place.is_indirect() {
677 self.record_local_conflict(
680 "asm! operand overlap",
684 InlineAsmOperand::InOut {
690 if let Some(place) = in_value.place() {
691 if !place.is_indirect() && !dest_place.is_indirect() {
692 self.record_local_conflict(
695 "asm! operand overlap",
700 if let Some(place) = out_place {
701 if !place.is_indirect() && !dest_place.is_indirect() {
702 self.record_local_conflict(
705 "asm! operand overlap",
710 InlineAsmOperand::Out { reg: _, late: _, place: None }
711 | InlineAsmOperand::Const { value: _ }
712 | InlineAsmOperand::SymFn { value: _ }
713 | InlineAsmOperand::SymStatic { def_id: _ } => {}
717 InlineAsmOperand::Const { value } => {
718 assert!(value.place().is_none());
720 InlineAsmOperand::InOut {
726 | InlineAsmOperand::In { reg: _, value: _ }
727 | InlineAsmOperand::Out { reg: _, late: _, place: None }
728 | InlineAsmOperand::SymFn { value: _ }
729 | InlineAsmOperand::SymStatic { def_id: _ } => {}
734 TerminatorKind::Goto { .. }
735 | TerminatorKind::Call { destination: None, .. }
736 | TerminatorKind::SwitchInt { .. }
737 | TerminatorKind::Resume
738 | TerminatorKind::Abort
739 | TerminatorKind::Return
740 | TerminatorKind::Unreachable
741 | TerminatorKind::Drop { .. }
742 | TerminatorKind::Assert { .. }
743 | TerminatorKind::GeneratorDrop
744 | TerminatorKind::FalseEdge { .. }
745 | TerminatorKind::FalseUnwind { .. } => {}
749 /// Checks whether `a` and `b` may be merged. Returns `false` if there's a conflict.
750 fn can_unify(&mut self, a: Local, b: Local) -> bool {
751 // After some locals have been unified, their conflicts are only tracked in the root key,
753 let a = self.unified_locals.find(a).0;
754 let b = self.unified_locals.find(b).0;
757 // Already merged (part of the same connected component).
761 if self.matrix.contains(a, b) {
762 // Conflict (derived via dataflow, intra-statement conflicts, or inherited from another
763 // local during unification).
770 /// Merges the conflicts of `a` and `b`, so that each one inherits all conflicts of the other.
772 /// `can_unify` must have returned `true` for the same locals, or this may panic or lead to
775 /// This is called when the pass makes the decision to unify `a` and `b` (or parts of `a` and
776 /// `b`) and is needed to ensure that future unification decisions take potentially newly
777 /// introduced conflicts into account.
779 /// For an example, assume we have locals `_0`, `_1`, `_2`, and `_3`. There are these conflicts:
785 /// We then decide to merge `_2` with `_3` since they don't conflict. Then we decide to merge
786 /// `_2` with `_0`, which also doesn't have a conflict in the above list. However `_2` is now
787 /// `_3`, which does conflict with `_0`.
788 fn unify(&mut self, a: Local, b: Local) {
789 trace!("unify({:?}, {:?})", a, b);
791 // Get the root local of the connected components. The root local stores the conflicts of
792 // all locals in the connected component (and *is stored* as the conflicting local of other
794 let a = self.unified_locals.find(a).0;
795 let b = self.unified_locals.find(b).0;
798 trace!("roots: a={:?}, b={:?}", a, b);
799 trace!("{:?} conflicts: {:?}", a, self.matrix.iter(a).format(", "));
800 trace!("{:?} conflicts: {:?}", b, self.matrix.iter(b).format(", "));
802 self.unified_locals.union(a, b);
804 let root = self.unified_locals.find(a).0;
805 assert!(root == a || root == b);
807 // Make all locals that conflict with `a` also conflict with `b`, and vice versa.
808 self.unify_cache.clear();
809 for conflicts_with_a in self.matrix.iter(a) {
810 self.unify_cache.insert(conflicts_with_a);
812 for conflicts_with_b in self.matrix.iter(b) {
813 self.unify_cache.insert(conflicts_with_b);
815 for conflicts_with_a_or_b in self.unify_cache.iter() {
816 // Set both `a` and `b` for this local's row.
817 self.matrix.insert(conflicts_with_a_or_b, a);
818 self.matrix.insert(conflicts_with_a_or_b, b);
821 // Write the locals `a` conflicts with to `b`'s row.
822 self.matrix.union_rows(a, b);
823 // Write the locals `b` conflicts with to `a`'s row.
824 self.matrix.union_rows(b, a);
828 /// A `dest = {move} src;` statement at `loc`.
830 /// We want to consider merging `dest` and `src` due to this assignment.
831 #[derive(Debug, Copy, Clone)]
832 struct CandidateAssignment<'tcx> {
833 /// Does not contain indirection or indexing (so the only local it contains is the place base).
839 /// Scans the MIR for assignments between locals that we might want to consider merging.
841 /// This will filter out assignments that do not match the right form (as described in the top-level
842 /// comment) and also throw out assignments that involve a local that has its address taken or is
843 /// otherwise ineligible (eg. locals used as array indices are ignored because we cannot propagate
844 /// arbitrary places into array indices).
845 fn find_candidates<'a, 'tcx>(
847 body: &'a Body<'tcx>,
848 ) -> Vec<CandidateAssignment<'tcx>> {
849 let mut visitor = FindAssignments {
852 candidates: Vec::new(),
853 ever_borrowed_locals: ever_borrowed_locals(body),
854 locals_used_as_array_index: locals_used_as_array_index(body),
856 visitor.visit_body(body);
860 struct FindAssignments<'a, 'tcx> {
862 body: &'a Body<'tcx>,
863 candidates: Vec<CandidateAssignment<'tcx>>,
864 ever_borrowed_locals: BitSet<Local>,
865 locals_used_as_array_index: BitSet<Local>,
868 impl<'a, 'tcx> Visitor<'tcx> for FindAssignments<'a, 'tcx> {
869 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
870 if let StatementKind::Assign(box (
872 Rvalue::Use(Operand::Copy(src) | Operand::Move(src)),
875 // `dest` must not have pointer indirection.
876 if dest.is_indirect() {
880 // `src` must be a plain local.
881 if !src.projection.is_empty() {
885 // Since we want to replace `src` with `dest`, `src` must not be required.
886 if is_local_required(src.local, self.body) {
890 // Can't optimize if both locals ever have their address taken (can introduce
892 // FIXME: This can be smarter and take `StorageDead` into account (which
893 // invalidates borrows).
894 if self.ever_borrowed_locals.contains(dest.local)
895 || self.ever_borrowed_locals.contains(src.local)
900 assert_ne!(dest.local, src.local, "self-assignments are UB");
902 // We can't replace locals occurring in `PlaceElem::Index` for now.
903 if self.locals_used_as_array_index.contains(src.local) {
907 // Handle the "subtle case" described above by rejecting any `dest` that is or
908 // projects through a union.
909 let is_union = |ty: Ty<'_>| {
910 if let ty::Adt(def, _) = ty.kind() {
918 let mut place_ty = PlaceTy::from_ty(self.body.local_decls[dest.local].ty);
919 if is_union(place_ty.ty) {
922 for elem in dest.projection {
923 if let PlaceElem::Index(_) = elem {
924 // `dest` contains an indexing projection.
928 place_ty = place_ty.projection_ty(self.tcx, elem);
929 if is_union(place_ty.ty) {
934 self.candidates.push(CandidateAssignment {
943 /// Some locals are part of the function's interface and can not be removed.
945 /// Note that these locals *can* still be merged with non-required locals by removing that other
947 fn is_local_required(local: Local, body: &Body<'_>) -> bool {
948 match body.local_kind(local) {
949 LocalKind::Arg | LocalKind::ReturnPointer => true,
950 LocalKind::Var | LocalKind::Temp => false,
954 /// Walks MIR to find all locals that have their address taken anywhere.
955 fn ever_borrowed_locals(body: &Body<'_>) -> BitSet<Local> {
956 let mut visitor = BorrowCollector { locals: BitSet::new_empty(body.local_decls.len()) };
957 visitor.visit_body(body);
961 struct BorrowCollector {
962 locals: BitSet<Local>,
965 impl<'tcx> Visitor<'tcx> for BorrowCollector {
966 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
967 self.super_rvalue(rvalue, location);
970 Rvalue::AddressOf(_, borrowed_place) | Rvalue::Ref(_, _, borrowed_place) => {
971 if !borrowed_place.is_indirect() {
972 self.locals.insert(borrowed_place.local);
980 | Rvalue::BinaryOp(..)
981 | Rvalue::CheckedBinaryOp(..)
982 | Rvalue::NullaryOp(..)
983 | Rvalue::UnaryOp(..)
984 | Rvalue::Discriminant(..)
985 | Rvalue::Aggregate(..)
986 | Rvalue::ThreadLocalRef(..) => {}
990 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
991 self.super_terminator(terminator, location);
993 match terminator.kind {
994 TerminatorKind::Drop { place: dropped_place, .. }
995 | TerminatorKind::DropAndReplace { place: dropped_place, .. } => {
996 self.locals.insert(dropped_place.local);
999 TerminatorKind::Abort
1000 | TerminatorKind::Assert { .. }
1001 | TerminatorKind::Call { .. }
1002 | TerminatorKind::FalseEdge { .. }
1003 | TerminatorKind::FalseUnwind { .. }
1004 | TerminatorKind::GeneratorDrop
1005 | TerminatorKind::Goto { .. }
1006 | TerminatorKind::Resume
1007 | TerminatorKind::Return
1008 | TerminatorKind::SwitchInt { .. }
1009 | TerminatorKind::Unreachable
1010 | TerminatorKind::Yield { .. }
1011 | TerminatorKind::InlineAsm { .. } => {}
1016 /// `PlaceElem::Index` only stores a `Local`, so we can't replace that with a full `Place`.
1018 /// Collect locals used as indices so we don't generate candidates that are impossible to apply
1020 fn locals_used_as_array_index(body: &Body<'_>) -> BitSet<Local> {
1021 let mut visitor = IndexCollector { locals: BitSet::new_empty(body.local_decls.len()) };
1022 visitor.visit_body(body);
1026 struct IndexCollector {
1027 locals: BitSet<Local>,
1030 impl<'tcx> Visitor<'tcx> for IndexCollector {
1031 fn visit_projection_elem(
1034 proj_base: &[PlaceElem<'tcx>],
1035 elem: PlaceElem<'tcx>,
1036 context: PlaceContext,
1039 if let PlaceElem::Index(i) = elem {
1040 self.locals.insert(i);
1042 self.super_projection_elem(local, proj_base, elem, context, location);