Skip to content

Commit

Permalink
Auto merge of #96116 - ouz-a:mir-opt, r=oli-obk
Browse files Browse the repository at this point in the history
Make derefer work everwhere

Follow up work on previous PR's #95649 and #95857.

r? rust-lang/mir-opt

_Co-Authored-By: `@oli-obk_`
  • Loading branch information
bors committed Apr 25, 2022
2 parents 18b53ce + 5364c86 commit 055bf4c
Show file tree
Hide file tree
Showing 12 changed files with 612 additions and 270 deletions.
20 changes: 20 additions & 0 deletions compiler/rustc_middle/src/mir/patch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ impl<'tcx> MirPatch<'tcx> {

let mut delta = 0;
let mut last_bb = START_BLOCK;
let mut stmts_and_targets: Vec<(Statement<'_>, BasicBlock)> = Vec::new();
for (mut loc, stmt) in new_statements {
if loc.block != last_bb {
delta = 0;
Expand All @@ -149,11 +150,30 @@ impl<'tcx> MirPatch<'tcx> {
debug!("MirPatch: adding statement {:?} at loc {:?}+{}", stmt, loc, delta);
loc.statement_index += delta;
let source_info = Self::source_info_for_index(&body[loc.block], loc);

// For mir-opt `Derefer` to work in all cases we need to
// get terminator's targets and apply the statement to all of them.
if loc.statement_index > body[loc.block].statements.len() {
let term = body[loc.block].terminator();
let successors = term.successors().clone();

for i in successors {
stmts_and_targets
.push((Statement { source_info, kind: stmt.clone() }, i.clone()));
}
delta += 1;
continue;
}

body[loc.block]
.statements
.insert(loc.statement_index, Statement { source_info, kind: stmt });
delta += 1;
}

for (stmt, target) in stmts_and_targets.into_iter().rev() {
body[target].statements.insert(0, stmt);
}
}

pub fn source_info_for_index(data: &BasicBlockData<'_>, loc: Location) -> SourceInfo {
Expand Down
131 changes: 76 additions & 55 deletions compiler/rustc_mir_transform/src/deref_separator.rs
Original file line number Diff line number Diff line change
@@ -1,68 +1,89 @@
use crate::MirPass;
use rustc_index::vec::IndexVec;
use rustc_middle::mir::patch::MirPatch;
use rustc_middle::mir::visit::{MutVisitor, PlaceContext};
use rustc_middle::mir::*;
use rustc_middle::ty::TyCtxt;
pub struct Derefer;

pub fn deref_finder<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
let mut patch = MirPatch::new(body);
let (basic_blocks, local_decl) = body.basic_blocks_and_local_decls_mut();
for (block, data) in basic_blocks.iter_enumerated_mut() {
for (i, stmt) in data.statements.iter_mut().enumerate() {
match stmt.kind {
StatementKind::Assign(box (og_place, Rvalue::Ref(region, borrow_knd, place))) => {
let mut place_local = place.local;
let mut last_len = 0;
for (idx, (p_ref, p_elem)) in place.iter_projections().enumerate() {
if p_elem == ProjectionElem::Deref && !p_ref.projection.is_empty() {
// The type that we are derefing.
let ty = p_ref.ty(local_decl, tcx).ty;
let temp = patch.new_temp(ty, stmt.source_info.span);

// Because we are assigning this right before original statement
// we are using index i of statement.
let loc = Location { block: block, statement_index: i };
patch.add_statement(loc, StatementKind::StorageLive(temp));

// We are adding current p_ref's projections to our
// temp value, excluding projections we already covered.
let deref_place = Place::from(place_local)
.project_deeper(&p_ref.projection[last_len..], tcx);
patch.add_assign(
loc,
Place::from(temp),
Rvalue::Use(Operand::Move(deref_place)),
);

place_local = temp;
last_len = p_ref.projection.len();

// We are creating a place by using our temp value's location
// and copying derefed values which we need to create new statement.
let temp_place =
Place::from(temp).project_deeper(&place.projection[idx..], tcx);
let new_stmt = Statement {
source_info: stmt.source_info,
kind: StatementKind::Assign(Box::new((
og_place,
Rvalue::Ref(region, borrow_knd, temp_place),
))),
};

// Replace current statement with newly created one.
*stmt = new_stmt;

// Since our job with the temp is done it should be gone
let loc = Location { block: block, statement_index: i + 1 };
patch.add_statement(loc, StatementKind::StorageDead(temp));
}
}
pub struct DerefChecker<'tcx> {
tcx: TyCtxt<'tcx>,
patcher: MirPatch<'tcx>,
local_decls: IndexVec<Local, LocalDecl<'tcx>>,
}

impl<'tcx> MutVisitor<'tcx> for DerefChecker<'tcx> {
fn tcx(&self) -> TyCtxt<'tcx> {
self.tcx
}

fn visit_place(&mut self, place: &mut Place<'tcx>, _: PlaceContext, loc: Location) {
let mut place_local = place.local;
let mut last_len = 0;
let mut last_deref_idx = 0;

let mut prev_temp: Option<Local> = None;

for (idx, (p_ref, p_elem)) in place.iter_projections().enumerate() {
if p_elem == ProjectionElem::Deref && !p_ref.projection.is_empty() {
last_deref_idx = idx;
}
}

for (idx, (p_ref, p_elem)) in place.iter_projections().enumerate() {
if p_elem == ProjectionElem::Deref && !p_ref.projection.is_empty() {
let ty = p_ref.ty(&self.local_decls, self.tcx).ty;
let temp =
self.patcher.new_temp(ty, self.local_decls[p_ref.local].source_info.span);

self.patcher.add_statement(loc, StatementKind::StorageLive(temp));

// We are adding current p_ref's projections to our
// temp value, excluding projections we already covered.
let deref_place = Place::from(place_local)
.project_deeper(&p_ref.projection[last_len..], self.tcx);
self.patcher.add_assign(
loc,
Place::from(temp),
Rvalue::Use(Operand::Move(deref_place)),
);

place_local = temp;
last_len = p_ref.projection.len();

// Change `Place` only if we are actually at the Place's last deref
if idx == last_deref_idx {
let temp_place =
Place::from(temp).project_deeper(&place.projection[idx..], self.tcx);
*place = temp_place;
}

// We are destroying last temp since it's no longer used.
if let Some(prev_temp) = prev_temp {
self.patcher.add_statement(loc, StatementKind::StorageDead(prev_temp));
}
_ => (),

prev_temp = Some(temp);
}
}

// Since we won't be able to reach final temp, we destroy it outside the loop.
if let Some(prev_temp) = prev_temp {
let last_loc = Location { block: loc.block, statement_index: loc.statement_index + 1 };
self.patcher.add_statement(last_loc, StatementKind::StorageDead(prev_temp));
}
}
patch.apply(body);
}

pub fn deref_finder<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
let patch = MirPatch::new(body);
let mut checker = DerefChecker { tcx, patcher: patch, local_decls: body.local_decls.clone() };

for (bb, data) in body.basic_blocks_mut().iter_enumerated_mut() {
checker.visit_basic_block_data(bb, data);
}

checker.patcher.apply(body);
}

impl<'tcx> MirPass<'tcx> for Derefer {
Expand Down
111 changes: 111 additions & 0 deletions src/test/mir-opt/derefer_complex_case.main.Derefer.diff
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
- // MIR for `main` before Derefer
+ // MIR for `main` after Derefer

fn main() -> () {
let mut _0: (); // return place in scope 0 at $DIR/derefer_complex_case.rs:3:11: 3:11
let mut _1: std::slice::Iter<i32>; // in scope 0 at $DIR/derefer_complex_case.rs:4:17: 4:26
let mut _2: &[i32; 2]; // in scope 0 at $DIR/derefer_complex_case.rs:4:17: 4:26
let _3: [i32; 2]; // in scope 0 at $DIR/derefer_complex_case.rs:4:18: 4:26
let mut _4: std::slice::Iter<i32>; // in scope 0 at $DIR/derefer_complex_case.rs:4:17: 4:26
let mut _5: (); // in scope 0 at $DIR/derefer_complex_case.rs:3:1: 5:2
let _6: (); // in scope 0 at $DIR/derefer_complex_case.rs:4:17: 4:26
let mut _7: std::option::Option<&i32>; // in scope 0 at $DIR/derefer_complex_case.rs:4:17: 4:26
let mut _8: &mut std::slice::Iter<i32>; // in scope 0 at $DIR/derefer_complex_case.rs:4:17: 4:26
let mut _9: &mut std::slice::Iter<i32>; // in scope 0 at $DIR/derefer_complex_case.rs:4:17: 4:26
let mut _10: isize; // in scope 0 at $DIR/derefer_complex_case.rs:4:5: 4:40
let mut _11: !; // in scope 0 at $DIR/derefer_complex_case.rs:4:5: 4:40
let mut _13: i32; // in scope 0 at $DIR/derefer_complex_case.rs:4:34: 4:37
let mut _14: &[i32; 2]; // in scope 0 at $DIR/derefer_complex_case.rs:4:17: 4:26
+ let mut _15: &i32; // in scope 0 at $DIR/derefer_complex_case.rs:4:17: 4:26
scope 1 {
debug iter => _4; // in scope 1 at $DIR/derefer_complex_case.rs:4:17: 4:26
let _12: i32; // in scope 1 at $DIR/derefer_complex_case.rs:4:10: 4:13
scope 2 {
debug foo => _12; // in scope 2 at $DIR/derefer_complex_case.rs:4:10: 4:13
}
}

bb0: {
StorageLive(_1); // scope 0 at $DIR/derefer_complex_case.rs:4:17: 4:26
StorageLive(_2); // scope 0 at $DIR/derefer_complex_case.rs:4:17: 4:26
_14 = const main::promoted[0]; // scope 0 at $DIR/derefer_complex_case.rs:4:17: 4:26
// mir::Constant
// + span: $DIR/derefer_complex_case.rs:4:17: 4:26
// + literal: Const { ty: &[i32; 2], val: Unevaluated(main, [], Some(promoted[0])) }
_2 = &(*_14); // scope 0 at $DIR/derefer_complex_case.rs:4:17: 4:26
_1 = <&[i32; 2] as IntoIterator>::into_iter(move _2) -> bb1; // scope 0 at $DIR/derefer_complex_case.rs:4:17: 4:26
// mir::Constant
// + span: $DIR/derefer_complex_case.rs:4:17: 4:26
// + literal: Const { ty: fn(&[i32; 2]) -> <&[i32; 2] as IntoIterator>::IntoIter {<&[i32; 2] as IntoIterator>::into_iter}, val: Value(Scalar(<ZST>)) }
}

bb1: {
StorageDead(_2); // scope 0 at $DIR/derefer_complex_case.rs:4:25: 4:26
StorageLive(_4); // scope 0 at $DIR/derefer_complex_case.rs:4:17: 4:26
_4 = move _1; // scope 0 at $DIR/derefer_complex_case.rs:4:17: 4:26
goto -> bb2; // scope 1 at $DIR/derefer_complex_case.rs:4:5: 4:40
}

bb2: {
StorageLive(_6); // scope 1 at $DIR/derefer_complex_case.rs:4:17: 4:26
StorageLive(_7); // scope 1 at $DIR/derefer_complex_case.rs:4:17: 4:26
StorageLive(_8); // scope 1 at $DIR/derefer_complex_case.rs:4:17: 4:26
StorageLive(_9); // scope 1 at $DIR/derefer_complex_case.rs:4:17: 4:26
_9 = &mut _4; // scope 1 at $DIR/derefer_complex_case.rs:4:17: 4:26
_8 = &mut (*_9); // scope 1 at $DIR/derefer_complex_case.rs:4:17: 4:26
_7 = <std::slice::Iter<i32> as Iterator>::next(move _8) -> bb3; // scope 1 at $DIR/derefer_complex_case.rs:4:17: 4:26
// mir::Constant
// + span: $DIR/derefer_complex_case.rs:4:17: 4:26
// + literal: Const { ty: for<'r> fn(&'r mut std::slice::Iter<i32>) -> Option<<std::slice::Iter<i32> as Iterator>::Item> {<std::slice::Iter<i32> as Iterator>::next}, val: Value(Scalar(<ZST>)) }
}

bb3: {
StorageDead(_8); // scope 1 at $DIR/derefer_complex_case.rs:4:25: 4:26
_10 = discriminant(_7); // scope 1 at $DIR/derefer_complex_case.rs:4:17: 4:26
switchInt(move _10) -> [0_isize: bb6, 1_isize: bb4, otherwise: bb5]; // scope 1 at $DIR/derefer_complex_case.rs:4:17: 4:26
}

bb4: {
StorageLive(_12); // scope 1 at $DIR/derefer_complex_case.rs:4:10: 4:13
- _12 = (*((_7 as Some).0: &i32)); // scope 1 at $DIR/derefer_complex_case.rs:4:10: 4:13
+ StorageLive(_15); // scope 1 at $DIR/derefer_complex_case.rs:4:10: 4:13
+ _15 = move ((_7 as Some).0: &i32); // scope 1 at $DIR/derefer_complex_case.rs:4:10: 4:13
+ _12 = (*_15); // scope 1 at $DIR/derefer_complex_case.rs:4:10: 4:13
+ StorageDead(_15); // scope 2 at $DIR/derefer_complex_case.rs:4:34: 4:37
StorageLive(_13); // scope 2 at $DIR/derefer_complex_case.rs:4:34: 4:37
_13 = _12; // scope 2 at $DIR/derefer_complex_case.rs:4:34: 4:37
_6 = std::mem::drop::<i32>(move _13) -> bb7; // scope 2 at $DIR/derefer_complex_case.rs:4:29: 4:38
// mir::Constant
// + span: $DIR/derefer_complex_case.rs:4:29: 4:33
// + literal: Const { ty: fn(i32) {std::mem::drop::<i32>}, val: Value(Scalar(<ZST>)) }
}

bb5: {
unreachable; // scope 1 at $DIR/derefer_complex_case.rs:4:17: 4:26
}

bb6: {
_0 = const (); // scope 1 at $DIR/derefer_complex_case.rs:4:5: 4:40
StorageDead(_9); // scope 1 at $DIR/derefer_complex_case.rs:4:39: 4:40
StorageDead(_7); // scope 1 at $DIR/derefer_complex_case.rs:4:39: 4:40
StorageDead(_6); // scope 1 at $DIR/derefer_complex_case.rs:4:39: 4:40
StorageDead(_4); // scope 0 at $DIR/derefer_complex_case.rs:4:39: 4:40
StorageDead(_1); // scope 0 at $DIR/derefer_complex_case.rs:4:39: 4:40
return; // scope 0 at $DIR/derefer_complex_case.rs:5:2: 5:2
}

bb7: {
StorageDead(_13); // scope 2 at $DIR/derefer_complex_case.rs:4:37: 4:38
StorageDead(_12); // scope 1 at $DIR/derefer_complex_case.rs:4:39: 4:40
StorageDead(_9); // scope 1 at $DIR/derefer_complex_case.rs:4:39: 4:40
StorageDead(_7); // scope 1 at $DIR/derefer_complex_case.rs:4:39: 4:40
StorageDead(_6); // scope 1 at $DIR/derefer_complex_case.rs:4:39: 4:40
_5 = const (); // scope 1 at $DIR/derefer_complex_case.rs:4:5: 4:40
goto -> bb2; // scope 1 at $DIR/derefer_complex_case.rs:4:5: 4:40
+ }
+
+ bb8 (cleanup): {
+ resume; // scope 0 at $DIR/derefer_complex_case.rs:3:1: 5:2
}
}

5 changes: 5 additions & 0 deletions src/test/mir-opt/derefer_complex_case.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// EMIT_MIR derefer_complex_case.main.Derefer.diff

fn main() {
for &foo in &[42, 43] { drop(foo) }
}
Loading

0 comments on commit 055bf4c

Please sign in to comment.