Skip to content

Commit faa5493

Browse files
committed
Simplify match based on the cast result of IntToInt.
1 parent 47766a2 commit faa5493

4 files changed

+146
-83
lines changed

compiler/rustc_mir_transform/src/match_branches.rs

+66-60
Original file line numberDiff line numberDiff line change
@@ -263,33 +263,49 @@ impl<'tcx> SimplifyMatch<'tcx> for SimplifyToIf {
263263
}
264264
}
265265

266+
/// Check if the cast constant using `IntToInt` is equal to the target constant.
267+
fn can_cast(
268+
from_val: impl Into<u128>,
269+
from_size: Size,
270+
target_scalar: ScalarInt,
271+
target_is_signed: bool,
272+
) -> bool {
273+
let from_scalar = ScalarInt::try_from_uint(from_val.into(), from_size).unwrap();
274+
let to_size = target_scalar.size();
275+
let cast_scalar = if target_is_signed {
276+
ScalarInt::try_from_int(from_scalar.to_int(from_size), to_size).unwrap()
277+
} else {
278+
ScalarInt::try_from_uint(from_scalar.to_uint(from_size), to_size).unwrap()
279+
};
280+
cast_scalar == target_scalar
281+
}
282+
266283
#[derive(Default)]
267284
struct SimplifyToExp {
268-
transfrom_types: Vec<TransfromType>,
285+
transfrom_kinds: Vec<TransfromKind>,
269286
}
270287

271288
#[derive(Clone, Copy)]
272-
enum CompareType<'tcx, 'a> {
289+
enum ExpectedTransformKind<'tcx, 'a> {
273290
/// Identical statements.
274291
Same(&'a StatementKind<'tcx>),
275292
/// Assignment statements have the same value.
276-
Eq(&'a Place<'tcx>, Ty<'tcx>, ScalarInt),
293+
SameByEq { place: &'a Place<'tcx>, ty: Ty<'tcx>, scalar: ScalarInt },
277294
/// Enum variant comparison type.
278-
Discr { place: &'a Place<'tcx>, ty: Ty<'tcx>, is_signed: bool },
295+
Cast { place: &'a Place<'tcx>, ty: Ty<'tcx> },
279296
}
280297

281-
enum TransfromType {
298+
enum TransfromKind {
282299
Same,
283-
Eq,
284-
Discr,
300+
Cast,
285301
}
286302

287-
impl From<CompareType<'_, '_>> for TransfromType {
288-
fn from(compare_type: CompareType<'_, '_>) -> Self {
303+
impl From<ExpectedTransformKind<'_, '_>> for TransfromKind {
304+
fn from(compare_type: ExpectedTransformKind<'_, '_>) -> Self {
289305
match compare_type {
290-
CompareType::Same(_) => TransfromType::Same,
291-
CompareType::Eq(_, _, _) => TransfromType::Eq,
292-
CompareType::Discr { .. } => TransfromType::Discr,
306+
ExpectedTransformKind::Same(_) => TransfromKind::Same,
307+
ExpectedTransformKind::SameByEq { .. } => TransfromKind::Same,
308+
ExpectedTransformKind::Cast { .. } => TransfromKind::Cast,
293309
}
294310
}
295311
}
@@ -353,7 +369,7 @@ impl<'tcx> SimplifyMatch<'tcx> for SimplifyToExp {
353369
return None;
354370
}
355371
let mut target_iter = targets.iter();
356-
let (first_val, first_target) = target_iter.next().unwrap();
372+
let (first_case_val, first_target) = target_iter.next().unwrap();
357373
let first_terminator_kind = &bbs[first_target].terminator().kind;
358374
// Check that destinations are identical, and if not, then don't optimize this block
359375
if !targets
@@ -365,22 +381,18 @@ impl<'tcx> SimplifyMatch<'tcx> for SimplifyToExp {
365381

366382
let discr_size = tcx.layout_of(param_env.and(discr_ty)).unwrap().size;
367383
let first_stmts = &bbs[first_target].statements;
368-
let (second_val, second_target) = target_iter.next().unwrap();
384+
let (second_case_val, second_target) = target_iter.next().unwrap();
369385
let second_stmts = &bbs[second_target].statements;
370386
if first_stmts.len() != second_stmts.len() {
371387
return None;
372388
}
373389

374-
fn int_equal(l: ScalarInt, r: impl Into<u128>, size: Size) -> bool {
375-
l.to_bits_unchecked() == ScalarInt::try_from_uint(r, size).unwrap().to_bits_unchecked()
376-
}
377-
378390
// We first compare the two branches, and then the other branches need to fulfill the same conditions.
379-
let mut compare_types = Vec::new();
391+
let mut expected_transform_kinds = Vec::new();
380392
for (f, s) in iter::zip(first_stmts, second_stmts) {
381393
let compare_type = match (&f.kind, &s.kind) {
382394
// If two statements are exactly the same, we can optimize.
383-
(f_s, s_s) if f_s == s_s => CompareType::Same(f_s),
395+
(f_s, s_s) if f_s == s_s => ExpectedTransformKind::Same(f_s),
384396

385397
// If two statements are assignments with the match values to the same place, we can optimize.
386398
(
@@ -394,22 +406,27 @@ impl<'tcx> SimplifyMatch<'tcx> for SimplifyToExp {
394406
f_c.const_.try_eval_scalar_int(tcx, param_env),
395407
s_c.const_.try_eval_scalar_int(tcx, param_env),
396408
) {
397-
(Some(f), Some(s)) if f == s => CompareType::Eq(lhs_f, f_c.const_.ty(), f),
398-
// Enum variants can also be simplified to an assignment statement if their values are equal.
399-
// We need to consider both unsigned and signed scenarios here.
409+
(Some(f), Some(s)) if f == s => ExpectedTransformKind::SameByEq {
410+
place: lhs_f,
411+
ty: f_c.const_.ty(),
412+
scalar: f,
413+
},
414+
// Enum variants can also be simplified to an assignment statement,
415+
// if we can use `IntToInt` cast to get an equal value.
400416
(Some(f), Some(s))
401-
if ((f_c.const_.ty().is_signed() || discr_ty.is_signed())
402-
&& int_equal(f, first_val, discr_size)
403-
&& int_equal(s, second_val, discr_size))
404-
|| (Some(f) == ScalarInt::try_from_uint(first_val, f.size())
405-
&& Some(s)
406-
== ScalarInt::try_from_uint(second_val, s.size())) =>
417+
if (can_cast(
418+
first_case_val,
419+
discr_size,
420+
f,
421+
f_c.const_.ty().is_signed(),
422+
) && can_cast(
423+
second_case_val,
424+
discr_size,
425+
s,
426+
s_c.const_.ty().is_signed(),
427+
)) =>
407428
{
408-
CompareType::Discr {
409-
place: lhs_f,
410-
ty: f_c.const_.ty(),
411-
is_signed: f_c.const_.ty().is_signed() || discr_ty.is_signed(),
412-
}
429+
ExpectedTransformKind::Cast { place: lhs_f, ty: f_c.const_.ty() }
413430
}
414431
_ => {
415432
return None;
@@ -420,47 +437,36 @@ impl<'tcx> SimplifyMatch<'tcx> for SimplifyToExp {
420437
// Otherwise we cannot optimize. Try another block.
421438
_ => return None,
422439
};
423-
compare_types.push(compare_type);
440+
expected_transform_kinds.push(compare_type);
424441
}
425442

426443
// All remaining BBs need to fulfill the same pattern as the two BBs from the previous step.
427444
for (other_val, other_target) in target_iter {
428445
let other_stmts = &bbs[other_target].statements;
429-
if compare_types.len() != other_stmts.len() {
446+
if expected_transform_kinds.len() != other_stmts.len() {
430447
return None;
431448
}
432-
for (f, s) in iter::zip(&compare_types, other_stmts) {
449+
for (f, s) in iter::zip(&expected_transform_kinds, other_stmts) {
433450
match (*f, &s.kind) {
434-
(CompareType::Same(f_s), s_s) if f_s == s_s => {}
451+
(ExpectedTransformKind::Same(f_s), s_s) if f_s == s_s => {}
435452
(
436-
CompareType::Eq(lhs_f, f_ty, val),
453+
ExpectedTransformKind::SameByEq { place: lhs_f, ty: f_ty, scalar },
437454
StatementKind::Assign(box (lhs_s, Rvalue::Use(Operand::Constant(s_c)))),
438455
) if lhs_f == lhs_s
439456
&& s_c.const_.ty() == f_ty
440-
&& s_c.const_.try_eval_scalar_int(tcx, param_env) == Some(val) => {}
457+
&& s_c.const_.try_eval_scalar_int(tcx, param_env) == Some(scalar) => {}
441458
(
442-
CompareType::Discr { place: lhs_f, ty: f_ty, is_signed },
459+
ExpectedTransformKind::Cast { place: lhs_f, ty: f_ty },
443460
StatementKind::Assign(box (lhs_s, Rvalue::Use(Operand::Constant(s_c)))),
444-
) if lhs_f == lhs_s && s_c.const_.ty() == f_ty => {
445-
let Some(f) = s_c.const_.try_eval_scalar_int(tcx, param_env) else {
446-
return None;
447-
};
448-
if is_signed
449-
&& s_c.const_.ty().is_signed()
450-
&& int_equal(f, other_val, discr_size)
451-
{
452-
continue;
453-
}
454-
if Some(f) == ScalarInt::try_from_uint(other_val, f.size()) {
455-
continue;
456-
}
457-
return None;
458-
}
461+
) if let Some(f) = s_c.const_.try_eval_scalar_int(tcx, param_env)
462+
&& lhs_f == lhs_s
463+
&& s_c.const_.ty() == f_ty
464+
&& can_cast(other_val, discr_size, f, f_ty.is_signed()) => {}
459465
_ => return None,
460466
}
461467
}
462468
}
463-
self.transfrom_types = compare_types.into_iter().map(|c| c.into()).collect();
469+
self.transfrom_kinds = expected_transform_kinds.into_iter().map(|c| c.into()).collect();
464470
Some(())
465471
}
466472

@@ -478,13 +484,13 @@ impl<'tcx> SimplifyMatch<'tcx> for SimplifyToExp {
478484
let (_, first) = targets.iter().next().unwrap();
479485
let first = &bbs[first];
480486

481-
for (t, s) in iter::zip(&self.transfrom_types, &first.statements) {
487+
for (t, s) in iter::zip(&self.transfrom_kinds, &first.statements) {
482488
match (t, &s.kind) {
483-
(TransfromType::Same, _) | (TransfromType::Eq, _) => {
489+
(TransfromKind::Same, _) => {
484490
patch.add_statement(parent_end, s.kind.clone());
485491
}
486492
(
487-
TransfromType::Discr,
493+
TransfromKind::Cast,
488494
StatementKind::Assign(box (lhs, Rvalue::Use(Operand::Constant(f_c)))),
489495
) => {
490496
let operand = Operand::Copy(Place::from(discr_local));

tests/mir-opt/matches_reduce_branches.match_i8_i16.MatchBranchSimplification.diff

+28-23
Original file line numberDiff line numberDiff line change
@@ -5,32 +5,37 @@
55
debug i => _1;
66
let mut _0: i16;
77
let mut _2: i8;
8+
+ let mut _3: i8;
89

910
bb0: {
1011
_2 = discriminant(_1);
11-
switchInt(move _2) -> [255: bb3, 2: bb4, 253: bb2, otherwise: bb1];
12-
}
13-
14-
bb1: {
15-
unreachable;
16-
}
17-
18-
bb2: {
19-
_0 = const -3_i16;
20-
goto -> bb5;
21-
}
22-
23-
bb3: {
24-
_0 = const -1_i16;
25-
goto -> bb5;
26-
}
27-
28-
bb4: {
29-
_0 = const 2_i16;
30-
goto -> bb5;
31-
}
32-
33-
bb5: {
12+
- switchInt(move _2) -> [255: bb3, 2: bb4, 253: bb2, otherwise: bb1];
13+
- }
14+
-
15+
- bb1: {
16+
- unreachable;
17+
- }
18+
-
19+
- bb2: {
20+
- _0 = const -3_i16;
21+
- goto -> bb5;
22+
- }
23+
-
24+
- bb3: {
25+
- _0 = const -1_i16;
26+
- goto -> bb5;
27+
- }
28+
-
29+
- bb4: {
30+
- _0 = const 2_i16;
31+
- goto -> bb5;
32+
- }
33+
-
34+
- bb5: {
35+
+ StorageLive(_3);
36+
+ _3 = move _2;
37+
+ _0 = _3 as i16 (IntToInt);
38+
+ StorageDead(_3);
3439
return;
3540
}
3641
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
- // MIR for `match_i8_i16_failed_2` before MatchBranchSimplification
2+
+ // MIR for `match_i8_i16_failed_2` after MatchBranchSimplification
3+
4+
fn match_i8_i16_failed_2(_1: EnumAi8) -> i16 {
5+
debug i => _1;
6+
let mut _0: i16;
7+
let mut _2: i8;
8+
9+
bb0: {
10+
_2 = discriminant(_1);
11+
switchInt(move _2) -> [255: bb3, 2: bb4, 253: bb2, otherwise: bb1];
12+
}
13+
14+
bb1: {
15+
unreachable;
16+
}
17+
18+
bb2: {
19+
_0 = const -3_i16;
20+
goto -> bb5;
21+
}
22+
23+
bb3: {
24+
_0 = const 255_i16;
25+
goto -> bb5;
26+
}
27+
28+
bb4: {
29+
_0 = const 2_i16;
30+
goto -> bb5;
31+
}
32+
33+
bb5: {
34+
return;
35+
}
36+
}
37+

tests/mir-opt/matches_reduce_branches.rs

+15
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,20 @@ enum EnumAi16 {
233233
C = -3,
234234
}
235235

236+
// We cannot transform it, even though `-1i8` and `255i16` are the same in terms of bits,
237+
// what we actually require is that they are considered equal in a signed comparison,
238+
// after sign-extending to the larger type.
239+
// EMIT_MIR matches_reduce_branches.match_i8_i16_failed_2.MatchBranchSimplification.diff
240+
fn match_i8_i16_failed_2(i: EnumAi8) -> i16 {
241+
// CHECK-LABEL: fn match_i8_i16_failed_2(
242+
// CHECK: switchInt
243+
match i {
244+
EnumAi8::A => 255,
245+
EnumAi8::B => 2,
246+
EnumAi8::C => -3,
247+
}
248+
}
249+
236250
// EMIT_MIR matches_reduce_branches.match_i16_i8.MatchBranchSimplification.diff
237251
fn match_i16_i8(i: EnumAi16) -> i8 {
238252
// CHECK-LABEL: fn match_i16_i8(
@@ -281,6 +295,7 @@ fn main() {
281295
let _ = match_u8_u16_2(EnumBu8::A);
282296
let _ = match_i8_i16(EnumAi8::A);
283297
let _ = match_i8_i16_failed(EnumAi8::A);
298+
let _ = match_i8_i16_failed_2(EnumAi8::A);
284299
let _ = match_i8_i16(EnumAi8::A);
285300
let _ = match_i16_i8(EnumAi16::A);
286301
let _ = match_i128_u128(EnumAi128::A);

0 commit comments

Comments
 (0)