Skip to content

Commit 02333ad

Browse files
committed
Simplify some literal-value negations with u128::wrapping_neg
1 parent 2f1bd3f commit 02333ad

File tree

2 files changed

+7
-5
lines changed

2 files changed

+7
-5
lines changed

compiler/rustc_mir_build/src/builder/expr/as_constant.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,9 @@ fn lit_to_mir_constant<'tcx>(tcx: TyCtxt<'tcx>, lit_input: LitToConstInput<'tcx>
157157
}
158158
(ast::LitKind::Int(n, _), ty::Uint(_)) if !neg => trunc(n.get()),
159159
(ast::LitKind::Int(n, _), ty::Int(_)) => {
160-
trunc(if neg { (n.get() as i128).overflowing_neg().0 as u128 } else { n.get() })
160+
// Unsigned "negation" has the same bitwise effect as signed negation,
161+
// which gets the result we want without additional casts.
162+
trunc(if neg { u128::wrapping_neg(n.get()) } else { n.get() })
161163
}
162164
(ast::LitKind::Float(n, _), ty::Float(fty)) => {
163165
parse_float_into_constval(n, *fty, neg).unwrap()

compiler/rustc_mir_build/src/thir/constant.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -72,10 +72,10 @@ pub(crate) fn lit_to_const<'tcx>(
7272
ty::ValTree::from_scalar_int(tcx, scalar_int)
7373
}
7474
(ast::LitKind::Int(n, _), ty::Int(i)) => {
75-
let scalar_int = trunc(
76-
if neg { (n.get() as i128).overflowing_neg().0 as u128 } else { n.get() },
77-
i.to_unsigned(),
78-
);
75+
// Unsigned "negation" has the same bitwise effect as signed negation,
76+
// which gets the result we want without additional casts.
77+
let scalar_int =
78+
trunc(if neg { u128::wrapping_neg(n.get()) } else { n.get() }, i.to_unsigned());
7979
ty::ValTree::from_scalar_int(tcx, scalar_int)
8080
}
8181
(ast::LitKind::Bool(b), ty::Bool) => ty::ValTree::from_scalar_int(tcx, b.into()),

0 commit comments

Comments
 (0)