diff --git a/compiler/rustc_mir_build/src/builder/expr/as_constant.rs b/compiler/rustc_mir_build/src/builder/expr/as_constant.rs index 1772d66f5285a..8a242445f1756 100644 --- a/compiler/rustc_mir_build/src/builder/expr/as_constant.rs +++ b/compiler/rustc_mir_build/src/builder/expr/as_constant.rs @@ -157,7 +157,9 @@ fn lit_to_mir_constant<'tcx>(tcx: TyCtxt<'tcx>, lit_input: LitToConstInput<'tcx> } (ast::LitKind::Int(n, _), ty::Uint(_)) if !neg => trunc(n.get()), (ast::LitKind::Int(n, _), ty::Int(_)) => { - trunc(if neg { (n.get() as i128).overflowing_neg().0 as u128 } else { n.get() }) + // Unsigned "negation" has the same bitwise effect as signed negation, + // which gets the result we want without additional casts. + trunc(if neg { u128::wrapping_neg(n.get()) } else { n.get() }) } (ast::LitKind::Float(n, _), ty::Float(fty)) => { parse_float_into_constval(n, *fty, neg).unwrap() diff --git a/compiler/rustc_mir_build/src/thir/constant.rs b/compiler/rustc_mir_build/src/thir/constant.rs index 7964a58a7ab01..96248499044aa 100644 --- a/compiler/rustc_mir_build/src/thir/constant.rs +++ b/compiler/rustc_mir_build/src/thir/constant.rs @@ -72,10 +72,10 @@ pub(crate) fn lit_to_const<'tcx>( ty::ValTree::from_scalar_int(tcx, scalar_int) } (ast::LitKind::Int(n, _), ty::Int(i)) => { - let scalar_int = trunc( - if neg { (n.get() as i128).overflowing_neg().0 as u128 } else { n.get() }, - i.to_unsigned(), - ); + // Unsigned "negation" has the same bitwise effect as signed negation, + // which gets the result we want without additional casts. + let scalar_int = + trunc(if neg { u128::wrapping_neg(n.get()) } else { n.get() }, i.to_unsigned()); ty::ValTree::from_scalar_int(tcx, scalar_int) } (ast::LitKind::Bool(b), ty::Bool) => ty::ValTree::from_scalar_int(tcx, b.into()),