Skip to content

Commit 4d71c16

Browse files
committed
Auto merge of #69550 - RalfJung:scalar, r=oli-obk
interpret engine: Scalar cleanup * Remove `to_ptr` * Make `to_bits` private r? @oli-obk
2 parents 592e9c3 + 0e15738 commit 4d71c16

File tree

7 files changed

+69
-87
lines changed

7 files changed

+69
-87
lines changed

src/librustc/mir/interpret/value.rs

+14-28
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,10 @@ impl<Tag> From<Double> for Scalar<Tag> {
170170
}
171171

172172
impl Scalar<()> {
173+
/// Make sure the `data` fits in `size`.
174+
/// This is guaranteed by all constructors here, but since the enum variants are public,
175+
/// it could still be violated (even though no code outside this file should
176+
/// construct `Scalar`s).
173177
#[inline(always)]
174178
fn check_data(data: u128, size: u8) {
175179
debug_assert_eq!(
@@ -364,10 +368,10 @@ impl<'tcx, Tag> Scalar<Tag> {
364368
target_size: Size,
365369
cx: &impl HasDataLayout,
366370
) -> Result<u128, Pointer<Tag>> {
371+
assert_ne!(target_size.bytes(), 0, "you should never look at the bits of a ZST");
367372
match self {
368373
Scalar::Raw { data, size } => {
369374
assert_eq!(target_size.bytes(), size as u64);
370-
assert_ne!(size, 0, "you should never look at the bits of a ZST");
371375
Scalar::check_data(data, size);
372376
Ok(data)
373377
}
@@ -378,19 +382,15 @@ impl<'tcx, Tag> Scalar<Tag> {
378382
}
379383
}
380384

381-
#[inline(always)]
382-
pub fn check_raw(data: u128, size: u8, target_size: Size) {
383-
assert_eq!(target_size.bytes(), size as u64);
384-
assert_ne!(size, 0, "you should never look at the bits of a ZST");
385-
Scalar::check_data(data, size);
386-
}
387-
388-
/// Do not call this method! Use either `assert_bits` or `force_bits`.
385+
/// This method is intentionally private!
386+
/// It is just a helper for other methods in this file.
389387
#[inline]
390-
pub fn to_bits(self, target_size: Size) -> InterpResult<'tcx, u128> {
388+
fn to_bits(self, target_size: Size) -> InterpResult<'tcx, u128> {
389+
assert_ne!(target_size.bytes(), 0, "you should never look at the bits of a ZST");
391390
match self {
392391
Scalar::Raw { data, size } => {
393-
Self::check_raw(data, size, target_size);
392+
assert_eq!(target_size.bytes(), size as u64);
393+
Scalar::check_data(data, size);
394394
Ok(data)
395395
}
396396
Scalar::Ptr(_) => throw_unsup!(ReadPointerAsBytes),
@@ -402,22 +402,14 @@ impl<'tcx, Tag> Scalar<Tag> {
402402
self.to_bits(target_size).expect("expected Raw bits but got a Pointer")
403403
}
404404

405-
/// Do not call this method! Use either `assert_ptr` or `force_ptr`.
406-
/// This method is intentionally private, do not make it public.
407405
#[inline]
408-
fn to_ptr(self) -> InterpResult<'tcx, Pointer<Tag>> {
406+
pub fn assert_ptr(self) -> Pointer<Tag> {
409407
match self {
410-
Scalar::Raw { data: 0, .. } => throw_unsup!(InvalidNullPointerUsage),
411-
Scalar::Raw { .. } => throw_unsup!(ReadBytesAsPointer),
412-
Scalar::Ptr(p) => Ok(p),
408+
Scalar::Ptr(p) => p,
409+
Scalar::Raw { .. } => bug!("expected a Pointer but got Raw bits"),
413410
}
414411
}
415412

416-
#[inline(always)]
417-
pub fn assert_ptr(self) -> Pointer<Tag> {
418-
self.to_ptr().expect("expected a Pointer but got Raw bits")
419-
}
420-
421413
/// Do not call this method! Dispatch based on the type instead.
422414
#[inline]
423415
pub fn is_bits(self) -> bool {
@@ -595,12 +587,6 @@ impl<'tcx, Tag> ScalarMaybeUndef<Tag> {
595587
}
596588
}
597589

598-
/// Do not call this method! Use either `assert_bits` or `force_bits`.
599-
#[inline(always)]
600-
pub fn to_bits(self, target_size: Size) -> InterpResult<'tcx, u128> {
601-
self.not_undef()?.to_bits(target_size)
602-
}
603-
604590
#[inline(always)]
605591
pub fn to_bool(self) -> InterpResult<'tcx, bool> {
606592
self.not_undef()?.to_bool()

src/librustc/ty/sty.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -2571,7 +2571,7 @@ impl<'tcx> ConstKind<'tcx> {
25712571

25722572
#[inline]
25732573
pub fn try_to_bits(&self, size: ty::layout::Size) -> Option<u128> {
2574-
self.try_to_scalar()?.to_bits(size).ok()
2574+
if let ConstKind::Value(val) = self { val.try_to_bits(size) } else { None }
25752575
}
25762576
}
25772577

src/librustc_mir/interpret/intrinsics.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -384,7 +384,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
384384
// `x % y != 0` or `y == 0` or `x == T::min_value() && y == -1`.
385385
// First, check x % y != 0 (or if that computation overflows).
386386
let (res, overflow, _ty) = self.overflowing_binary_op(BinOp::Rem, a, b)?;
387-
if overflow || res.to_bits(a.layout.size)? != 0 {
387+
if overflow || res.assert_bits(a.layout.size) != 0 {
388388
// Then, check if `b` is -1, which is the "min_value / -1" case.
389389
let minus1 = Scalar::from_int(-1, dest.layout.size);
390390
let b_scalar = b.to_scalar().unwrap();

src/librustc_mir/interpret/operand.rs

+29-34
Original file line numberDiff line numberDiff line change
@@ -96,40 +96,40 @@ pub struct ImmTy<'tcx, Tag = ()> {
9696
impl<Tag: Copy> std::fmt::Display for ImmTy<'tcx, Tag> {
9797
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
9898
match &self.imm {
99-
Immediate::Scalar(ScalarMaybeUndef::Scalar(s)) => match s.to_bits(self.layout.size) {
100-
Ok(s) => {
101-
match self.layout.ty.kind {
102-
ty::Int(_) => {
103-
return write!(
104-
fmt,
105-
"{}",
106-
super::sign_extend(s, self.layout.size) as i128,
107-
);
108-
}
109-
ty::Uint(_) => return write!(fmt, "{}", s),
110-
ty::Bool if s == 0 => return fmt.write_str("false"),
111-
ty::Bool if s == 1 => return fmt.write_str("true"),
112-
ty::Char => {
113-
if let Some(c) = u32::try_from(s).ok().and_then(std::char::from_u32) {
114-
return write!(fmt, "{}", c);
115-
}
99+
// We cannot use `to_bits_or_ptr` as we do not have a `tcx`.
100+
// So we use `is_bits` and circumvent a bunch of sanity checking -- but
101+
// this is anyway only for printing.
102+
Immediate::Scalar(ScalarMaybeUndef::Scalar(s)) if s.is_ptr() => {
103+
fmt.write_str("{pointer}")
104+
}
105+
Immediate::Scalar(ScalarMaybeUndef::Scalar(s)) => {
106+
let s = s.assert_bits(self.layout.size);
107+
match self.layout.ty.kind {
108+
ty::Int(_) => {
109+
return write!(fmt, "{}", super::sign_extend(s, self.layout.size) as i128,);
110+
}
111+
ty::Uint(_) => return write!(fmt, "{}", s),
112+
ty::Bool if s == 0 => return fmt.write_str("false"),
113+
ty::Bool if s == 1 => return fmt.write_str("true"),
114+
ty::Char => {
115+
if let Some(c) = u32::try_from(s).ok().and_then(std::char::from_u32) {
116+
return write!(fmt, "{}", c);
116117
}
117-
ty::Float(ast::FloatTy::F32) => {
118-
if let Ok(u) = u32::try_from(s) {
119-
return write!(fmt, "{}", f32::from_bits(u));
120-
}
118+
}
119+
ty::Float(ast::FloatTy::F32) => {
120+
if let Ok(u) = u32::try_from(s) {
121+
return write!(fmt, "{}", f32::from_bits(u));
121122
}
122-
ty::Float(ast::FloatTy::F64) => {
123-
if let Ok(u) = u64::try_from(s) {
124-
return write!(fmt, "{}", f64::from_bits(u));
125-
}
123+
}
124+
ty::Float(ast::FloatTy::F64) => {
125+
if let Ok(u) = u64::try_from(s) {
126+
return write!(fmt, "{}", f64::from_bits(u));
126127
}
127-
_ => {}
128128
}
129-
write!(fmt, "{:x}", s)
129+
_ => {}
130130
}
131-
Err(_) => fmt.write_str("{pointer}"),
132-
},
131+
write!(fmt, "{:x}", s)
132+
}
133133
Immediate::Scalar(ScalarMaybeUndef::Undef) => fmt.write_str("{undef}"),
134134
Immediate::ScalarPair(..) => fmt.write_str("{wide pointer or tuple}"),
135135
}
@@ -205,11 +205,6 @@ impl<'tcx, Tag: Copy> ImmTy<'tcx, Tag> {
205205
pub fn from_int(i: impl Into<i128>, layout: TyLayout<'tcx>) -> Self {
206206
Self::from_scalar(Scalar::from_int(i, layout.size), layout)
207207
}
208-
209-
#[inline]
210-
pub fn to_bits(self) -> InterpResult<'tcx, u128> {
211-
self.to_scalar()?.to_bits(self.layout.size)
212-
}
213208
}
214209

215210
// Use the existing layout if given (but sanity check in debug mode),

src/librustc_mir/interpret/validity.rs

+8-7
Original file line numberDiff line numberDiff line change
@@ -322,16 +322,17 @@ impl<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, 'tcx, M
322322
ty::Float(_) | ty::Int(_) | ty::Uint(_) => {
323323
// NOTE: Keep this in sync with the array optimization for int/float
324324
// types below!
325-
let size = value.layout.size;
326325
let value = value.to_scalar_or_undef();
327326
if self.ref_tracking_for_consts.is_some() {
328327
// Integers/floats in CTFE: Must be scalar bits, pointers are dangerous
329-
try_validation!(
330-
value.to_bits(size),
331-
value,
332-
self.path,
333-
"initialized plain (non-pointer) bytes"
334-
);
328+
let is_bits = value.not_undef().map_or(false, |v| v.is_bits());
329+
if !is_bits {
330+
throw_validation_failure!(
331+
value,
332+
self.path,
333+
"initialized plain (non-pointer) bytes"
334+
)
335+
}
335336
} else {
336337
// At run-time, for now, we accept *anything* for these types, including
337338
// undef. We should fix that, but let's start low.

src/librustc_mir/transform/const_prop.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -545,7 +545,9 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
545545
let left_ty = left.ty(&self.local_decls, self.tcx);
546546
let left_size_bits = self.ecx.layout_of(left_ty).ok()?.size.bits();
547547
let right_size = r.layout.size;
548-
let r_bits = r.to_scalar().and_then(|r| r.to_bits(right_size));
548+
let r_bits = r.to_scalar().ok();
549+
// This is basically `force_bits`.
550+
let r_bits = r_bits.and_then(|r| r.to_bits_or_ptr(right_size, &self.tcx).ok());
549551
if r_bits.map_or(false, |b| b >= left_size_bits as u128) {
550552
self.report_assert_as_lint(
551553
lint::builtin::ARITHMETIC_OVERFLOW,

src/librustc_mir_build/hair/pattern/_match.rs

+13-15
Original file line numberDiff line numberDiff line change
@@ -1396,21 +1396,19 @@ impl<'tcx> IntRange<'tcx> {
13961396
) -> Option<IntRange<'tcx>> {
13971397
if let Some((target_size, bias)) = Self::integral_size_and_signed_bias(tcx, value.ty) {
13981398
let ty = value.ty;
1399-
let val = if let ty::ConstKind::Value(ConstValue::Scalar(Scalar::Raw { data, size })) =
1400-
value.val
1401-
{
1402-
// For this specific pattern we can skip a lot of effort and go
1403-
// straight to the result, after doing a bit of checking. (We
1404-
// could remove this branch and just use the next branch, which
1405-
// is more general but much slower.)
1406-
Scalar::<()>::check_raw(data, size, target_size);
1407-
data
1408-
} else if let Some(val) = value.try_eval_bits(tcx, param_env, ty) {
1409-
// This is a more general form of the previous branch.
1410-
val
1411-
} else {
1412-
return None;
1413-
};
1399+
let val = (|| {
1400+
if let ty::ConstKind::Value(ConstValue::Scalar(scalar)) = value.val {
1401+
// For this specific pattern we can skip a lot of effort and go
1402+
// straight to the result, after doing a bit of checking. (We
1403+
// could remove this branch and just fall through, which
1404+
// is more general but much slower.)
1405+
if let Ok(bits) = scalar.to_bits_or_ptr(target_size, &tcx) {
1406+
return Some(bits);
1407+
}
1408+
}
1409+
// This is a more general form of the previous case.
1410+
value.try_eval_bits(tcx, param_env, ty)
1411+
})()?;
14141412
let val = val ^ bias;
14151413
Some(IntRange { range: val..=val, ty, span })
14161414
} else {

0 commit comments

Comments
 (0)