Skip to content

Commit 5b984a0

Browse files
committed
Merge these copy statements that simplified the canonical enum clone method by GVN
1 parent 71bba28 commit 5b984a0

25 files changed

+451
-294
lines changed

compiler/rustc_mir_transform/src/lib.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -588,15 +588,14 @@ fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
588588
// Now, we need to shrink the generated MIR.
589589
&ref_prop::ReferencePropagation,
590590
&sroa::ScalarReplacementOfAggregates,
591-
&match_branches::MatchBranchSimplification,
592-
// inst combine is after MatchBranchSimplification to clean up Ne(_1, false)
593591
&multiple_return_terminators::MultipleReturnTerminators,
594592
// After simplifycfg, it allows us to discover new opportunities for peephole optimizations.
595593
&instsimplify::InstSimplify::AfterSimplifyCfg,
596594
&simplify::SimplifyLocals::BeforeConstProp,
597595
&dead_store_elimination::DeadStoreElimination::Initial,
598596
&gvn::GVN,
599597
&simplify::SimplifyLocals::AfterGVN,
598+
&match_branches::MatchBranchSimplification,
600599
&dataflow_const_prop::DataflowConstProp,
601600
&single_use_consts::SingleUseConsts,
602601
&o1(simplify_branches::SimplifyConstCondition::AfterConstProp),

compiler/rustc_mir_transform/src/match_branches.rs

+210-1
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,16 @@
1-
use std::iter;
1+
use std::{iter, usize};
22

3+
use rustc_const_eval::const_eval::mk_eval_cx_for_const_val;
4+
use rustc_index::bit_set::BitSet;
35
use rustc_index::IndexSlice;
46
use rustc_middle::mir::patch::MirPatch;
57
use rustc_middle::mir::*;
8+
use rustc_middle::ty;
69
use rustc_middle::ty::layout::{IntegerExt, TyAndLayout};
10+
use rustc_middle::ty::util::Discr;
711
use rustc_middle::ty::{ParamEnv, ScalarInt, Ty, TyCtxt};
12+
use rustc_mir_dataflow::impls::{borrowed_locals, MaybeTransitiveLiveLocals};
13+
use rustc_mir_dataflow::Analysis;
814
use rustc_target::abi::Integer;
915
use rustc_type_ir::TyKind::*;
1016

@@ -48,6 +54,10 @@ impl<'tcx> MirPass<'tcx> for MatchBranchSimplification {
4854
should_cleanup = true;
4955
continue;
5056
}
57+
if simplify_to_copy(tcx, body, bb_idx, param_env).is_some() {
58+
should_cleanup = true;
59+
continue;
60+
}
5161
}
5262

5363
if should_cleanup {
@@ -515,3 +525,202 @@ impl<'tcx> SimplifyMatch<'tcx> for SimplifyToExp {
515525
}
516526
}
517527
}
528+
529+
/// This is primarily used to merge these copy statements that simplified the canonical enum clone method by GVN.
530+
/// The GVN simplified
531+
/// ```ignore (syntax-highlighting-only)
532+
/// match a {
533+
/// Foo::A(x) => Foo::A(*x),
534+
/// Foo::B => Foo::B
535+
/// }
536+
/// ```
537+
/// to
538+
/// ```ignore (syntax-highlighting-only)
539+
/// match a {
540+
/// Foo::A(_x) => a, // copy a
541+
/// Foo::B => Foo::B
542+
/// }
543+
/// ```
544+
/// This function will simplify into a copy statement.
545+
fn simplify_to_copy<'tcx>(
546+
tcx: TyCtxt<'tcx>,
547+
body: &mut Body<'tcx>,
548+
switch_bb_idx: BasicBlock,
549+
param_env: ParamEnv<'tcx>,
550+
) -> Option<()> {
551+
let bbs = &body.basic_blocks;
552+
// Check if the copy source matches the following pattern.
553+
// _2 = discriminant(*_1); // "*_1" is the expected the copy source.
554+
// switchInt(move _2) -> [0: bb3, 1: bb2, otherwise: bb1];
555+
let &Statement {
556+
kind: StatementKind::Assign(box (discr_place, Rvalue::Discriminant(expected_src_place))),
557+
..
558+
} = bbs[switch_bb_idx].statements.last()?
559+
else {
560+
return None;
561+
};
562+
let expected_src_ty = expected_src_place.ty(body.local_decls(), tcx);
563+
if !expected_src_ty.ty.is_enum() || expected_src_ty.variant_index.is_some() {
564+
return None;
565+
}
566+
let targets = match bbs[switch_bb_idx].terminator().kind {
567+
TerminatorKind::SwitchInt { ref discr, ref targets, .. }
568+
if discr.place() == Some(discr_place) =>
569+
{
570+
targets
571+
}
572+
_ => return None,
573+
};
574+
// We require that the possible target blocks all be distinct.
575+
if !targets.is_distinct() {
576+
return None;
577+
}
578+
if !bbs[targets.otherwise()].is_empty_unreachable() {
579+
return None;
580+
}
581+
// Check that destinations are identical, and if not, then don't optimize this block.
582+
let mut target_iter = targets.iter();
583+
let first_terminator_kind = &bbs[target_iter.next().unwrap().1].terminator().kind;
584+
if !target_iter
585+
.all(|(_, other_target)| first_terminator_kind == &bbs[other_target].terminator().kind)
586+
{
587+
return None;
588+
}
589+
590+
let borrowed_locals = borrowed_locals(body);
591+
let mut live = None;
592+
let mut expected_dest_place = None;
593+
for (index, target_bb) in targets.iter() {
594+
let stmts = &bbs[target_bb].statements;
595+
if stmts.is_empty() {
596+
return None;
597+
}
598+
if let [Statement { kind: StatementKind::Assign(box (place, rvalue)), .. }] =
599+
bbs[target_bb].statements.as_slice()
600+
{
601+
let dest_ty = place.ty(body.local_decls(), tcx);
602+
if dest_ty.ty != expected_src_ty.ty || dest_ty.variant_index.is_some() {
603+
return None;
604+
}
605+
let ty::Adt(def, _) = dest_ty.ty.kind() else {
606+
return None;
607+
};
608+
if *expected_dest_place.get_or_insert(*place) != *place {
609+
return None;
610+
}
611+
match rvalue {
612+
// Check if `_3 = const Foo::B` can be transformed to `_3 = copy *_1`.
613+
Rvalue::Use(Operand::Constant(box constant))
614+
if let Const::Val(const_, ty) = constant.const_ =>
615+
{
616+
let (ecx, op) =
617+
mk_eval_cx_for_const_val(tcx.at(constant.span), param_env, const_, ty)?;
618+
let variant = ecx.read_discriminant(&op).ok()?;
619+
if !def.variants()[variant].fields.is_empty() {
620+
return None;
621+
}
622+
let Discr { val, .. } = ty.discriminant_for_variant(tcx, variant)?;
623+
if val != index {
624+
return None;
625+
}
626+
}
627+
Rvalue::Use(Operand::Copy(src_place)) if *src_place == expected_src_place => {}
628+
// Check if `_3 = Foo::B` can be transformed to `_3 = copy *_1`.
629+
Rvalue::Aggregate(box AggregateKind::Adt(_, variant_index, _, _, None), fields)
630+
if fields.is_empty()
631+
&& let Some(Discr { val, .. }) =
632+
expected_src_ty.ty.discriminant_for_variant(tcx, *variant_index)
633+
&& val == index => {}
634+
_ => return None,
635+
}
636+
} else {
637+
// If the BB contains more than one statement, we have to check if these statements can be ignored.
638+
let mut lived_stmts: BitSet<usize> =
639+
BitSet::new_filled(bbs[target_bb].statements.len());
640+
let mut dest_place = None;
641+
for (statement_index, statement) in bbs[target_bb].statements.iter().enumerate().rev() {
642+
let loc = Location { block: target_bb, statement_index };
643+
if let StatementKind::Assign(assign) = &statement.kind {
644+
if !assign.1.is_safe_to_remove() {
645+
return None;
646+
}
647+
}
648+
match &statement.kind {
649+
StatementKind::Assign(box (place, _))
650+
| StatementKind::SetDiscriminant { place: box place, .. }
651+
| StatementKind::Deinit(box place) => {
652+
if place.is_indirect() || borrowed_locals.contains(place.local) {
653+
return None;
654+
}
655+
let live = live.get_or_insert_with(|| {
656+
MaybeTransitiveLiveLocals::new(&borrowed_locals)
657+
.into_engine(tcx, body)
658+
.iterate_to_fixpoint()
659+
.into_results_cursor(body)
660+
});
661+
live.seek_before_primary_effect(loc);
662+
if !live.get().contains(place.local) {
663+
lived_stmts.remove(statement_index);
664+
} else if matches!(
665+
&statement.kind,
666+
StatementKind::Assign(box (_, Rvalue::Use(Operand::Copy(_))))
667+
) && dest_place.is_none()
668+
{
669+
// There is only one statement that cannot be ignored that can be used as an expected copy statement.
670+
dest_place = Some(*place);
671+
} else {
672+
return None;
673+
}
674+
}
675+
StatementKind::StorageLive(_)
676+
| StatementKind::StorageDead(_)
677+
| StatementKind::Nop => (),
678+
679+
StatementKind::Retag(_, _)
680+
| StatementKind::Coverage(_)
681+
| StatementKind::Intrinsic(_)
682+
| StatementKind::ConstEvalCounter
683+
| StatementKind::PlaceMention(_)
684+
| StatementKind::FakeRead(_)
685+
| StatementKind::AscribeUserType(_, _) => {
686+
return None;
687+
}
688+
}
689+
}
690+
let dest_place = dest_place?;
691+
if *expected_dest_place.get_or_insert(dest_place) != dest_place {
692+
return None;
693+
}
694+
// We can ignore the paired StorageLive and StorageDead.
695+
let mut storage_live_locals: BitSet<Local> = BitSet::new_empty(body.local_decls.len());
696+
for stmt_index in lived_stmts.iter() {
697+
let statement = &bbs[target_bb].statements[stmt_index];
698+
match &statement.kind {
699+
StatementKind::Assign(box (place, Rvalue::Use(Operand::Copy(src_place))))
700+
if *place == dest_place && *src_place == expected_src_place => {}
701+
StatementKind::StorageLive(local)
702+
if *local != dest_place.local && storage_live_locals.insert(*local) => {}
703+
StatementKind::StorageDead(local)
704+
if *local != dest_place.local && storage_live_locals.remove(*local) => {}
705+
StatementKind::Nop => {}
706+
_ => return None,
707+
}
708+
}
709+
if !storage_live_locals.is_empty() {
710+
return None;
711+
}
712+
}
713+
}
714+
let expected_dest_place = expected_dest_place?;
715+
let statement_index = bbs[switch_bb_idx].statements.len();
716+
let parent_end = Location { block: switch_bb_idx, statement_index };
717+
let mut patch = MirPatch::new(body);
718+
patch.add_assign(
719+
parent_end,
720+
expected_dest_place,
721+
Rvalue::Use(Operand::Copy(expected_src_place)),
722+
);
723+
patch.patch_terminator(switch_bb_idx, first_terminator_kind.clone());
724+
patch.apply(body);
725+
Some(())
726+
}

tests/codegen/match-optimizes-away.rs

+8-6
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
//
2-
//@ compile-flags: -O
1+
//@ compile-flags: -O -Cno-prepopulate-passes
2+
33
#![crate_type = "lib"]
44

55
pub enum Three {
@@ -19,8 +19,9 @@ pub enum Four {
1919
#[no_mangle]
2020
pub fn three_valued(x: Three) -> Three {
2121
// CHECK-LABEL: @three_valued
22-
// CHECK-NEXT: {{^.*:$}}
23-
// CHECK-NEXT: ret i8 %0
22+
// CHECK-SAME: (i8{{.*}}) [[X:%x]])
23+
// CHECK-NEXT: start:
24+
// CHECK-NEXT: ret i8 [[X]]
2425
match x {
2526
Three::A => Three::A,
2627
Three::B => Three::B,
@@ -31,8 +32,9 @@ pub fn three_valued(x: Three) -> Three {
3132
#[no_mangle]
3233
pub fn four_valued(x: Four) -> Four {
3334
// CHECK-LABEL: @four_valued
34-
// CHECK-NEXT: {{^.*:$}}
35-
// CHECK-NEXT: ret i16 %0
35+
// CHECK-SAME: (i16{{.*}} [[X:%x]])
36+
// CHECK-NEXT: start:
37+
// CHECK-NEXT: ret i16 [[X]]
3638
match x {
3739
Four::A => Four::A,
3840
Four::B => Four::B,

tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.DataflowConstProp.32bit.panic-abort.diff

+15-15
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,11 @@
1919
let _6: *mut [bool; 0];
2020
scope 6 {
2121
scope 10 (inlined NonNull::<[bool; 0]>::new_unchecked) {
22-
let mut _8: bool;
23-
let _9: ();
24-
let mut _10: *mut ();
25-
let mut _11: *const [bool; 0];
22+
let _8: ();
23+
let mut _9: *mut ();
24+
let mut _10: *const [bool; 0];
2625
scope 11 (inlined core::ub_checks::check_language_ub) {
26+
let mut _11: bool;
2727
scope 12 (inlined core::ub_checks::check_language_ub::runtime) {
2828
}
2929
}
@@ -44,18 +44,18 @@
4444
StorageLive(_1);
4545
StorageLive(_2);
4646
StorageLive(_3);
47-
StorageLive(_9);
47+
StorageLive(_8);
4848
StorageLive(_4);
4949
StorageLive(_5);
5050
StorageLive(_6);
5151
StorageLive(_7);
5252
_7 = const 1_usize;
5353
_6 = const {0x1 as *mut [bool; 0]};
5454
StorageDead(_7);
55+
StorageLive(_10);
5556
StorageLive(_11);
56-
StorageLive(_8);
57-
_8 = UbChecks();
58-
switchInt(move _8) -> [0: bb4, otherwise: bb2];
57+
_11 = UbChecks();
58+
switchInt(copy _11) -> [0: bb4, otherwise: bb2];
5959
}
6060

6161
bb1: {
@@ -64,28 +64,28 @@
6464
}
6565

6666
bb2: {
67-
StorageLive(_10);
68-
_10 = const {0x1 as *mut ()};
69-
_9 = NonNull::<T>::new_unchecked::precondition_check(const {0x1 as *mut ()}) -> [return: bb3, unwind unreachable];
67+
StorageLive(_9);
68+
_9 = const {0x1 as *mut ()};
69+
_8 = NonNull::<T>::new_unchecked::precondition_check(const {0x1 as *mut ()}) -> [return: bb3, unwind unreachable];
7070
}
7171

7272
bb3: {
73-
StorageDead(_10);
73+
StorageDead(_9);
7474
goto -> bb4;
7575
}
7676

7777
bb4: {
78-
StorageDead(_8);
79-
_11 = const {0x1 as *const [bool; 0]};
78+
_10 = const {0x1 as *const [bool; 0]};
8079
_5 = const NonNull::<[bool; 0]> {{ pointer: {0x1 as *const [bool; 0]} }};
8180
StorageDead(_11);
81+
StorageDead(_10);
8282
StorageDead(_6);
8383
_4 = const Unique::<[bool; 0]> {{ pointer: NonNull::<[bool; 0]> {{ pointer: {0x1 as *const [bool; 0]} }}, _marker: PhantomData::<[bool; 0]> }};
8484
StorageDead(_5);
8585
_3 = const Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC0, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }};
8686
StorageDead(_4);
8787
_2 = const Box::<[bool]>(Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC1, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global);
88-
StorageDead(_9);
88+
StorageDead(_8);
8989
StorageDead(_3);
9090
_1 = const A {{ foo: Box::<[bool]>(Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC2, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global) }};
9191
StorageDead(_2);

0 commit comments

Comments
 (0)