Skip to content

Commit 391e7e2

Browse files
authored
Rollup merge of rust-lang#69181 - skinny121:const-eval-return, r=oli-obk
Change const eval to just return the value As discussed in rust-lang#68505 (comment), the type of consts shouldn't be returned from const eval queries. r? @eddyb cc @nikomatsakis
2 parents 6317721 + 8904bdd commit 391e7e2

File tree

25 files changed

+179
-115
lines changed

25 files changed

+179
-115
lines changed

src/librustc/mir/interpret/error.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use super::{CheckInAllocMsg, Pointer, RawConst, ScalarMaybeUndef};
22

33
use crate::hir::map::definitions::DefPathData;
44
use crate::mir;
5+
use crate::mir::interpret::ConstValue;
56
use crate::ty::layout::{Align, LayoutError, Size};
67
use crate::ty::query::TyCtxtAt;
78
use crate::ty::{self, layout, Ty};
@@ -40,7 +41,7 @@ CloneTypeFoldableImpls! {
4041
}
4142

4243
pub type ConstEvalRawResult<'tcx> = Result<RawConst<'tcx>, ErrorHandled>;
43-
pub type ConstEvalResult<'tcx> = Result<&'tcx ty::Const<'tcx>, ErrorHandled>;
44+
pub type ConstEvalResult<'tcx> = Result<ConstValue<'tcx>, ErrorHandled>;
4445

4546
#[derive(Debug)]
4647
pub struct ConstEvalErr<'tcx> {

src/librustc/mir/interpret/value.rs

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use std::fmt;
77

88
use crate::ty::{
99
layout::{HasDataLayout, Size},
10-
Ty,
10+
ParamEnv, Ty, TyCtxt,
1111
};
1212

1313
use super::{sign_extend, truncate, AllocId, Allocation, InterpResult, Pointer, PointerArithmetic};
@@ -66,6 +66,32 @@ impl<'tcx> ConstValue<'tcx> {
6666
ConstValue::Scalar(val) => Some(val),
6767
}
6868
}
69+
70+
pub fn try_to_bits(&self, size: Size) -> Option<u128> {
71+
self.try_to_scalar()?.to_bits(size).ok()
72+
}
73+
74+
pub fn try_to_bits_for_ty(
75+
&self,
76+
tcx: TyCtxt<'tcx>,
77+
param_env: ParamEnv<'tcx>,
78+
ty: Ty<'tcx>,
79+
) -> Option<u128> {
80+
let size = tcx.layout_of(param_env.with_reveal_all().and(ty)).ok()?.size;
81+
self.try_to_bits(size)
82+
}
83+
84+
pub fn from_bool(b: bool) -> Self {
85+
ConstValue::Scalar(Scalar::from_bool(b))
86+
}
87+
88+
pub fn from_u64(i: u64) -> Self {
89+
ConstValue::Scalar(Scalar::from_u64(i))
90+
}
91+
92+
pub fn from_machine_usize(i: u64, cx: &impl HasDataLayout) -> Self {
93+
ConstValue::Scalar(Scalar::from_machine_usize(i, cx))
94+
}
6995
}
7096

7197
/// A `Scalar` represents an immediate, primitive value existing outside of a
@@ -287,6 +313,11 @@ impl<'tcx, Tag> Scalar<Tag> {
287313
Scalar::Raw { data: i as u128, size: 8 }
288314
}
289315

316+
#[inline]
317+
pub fn from_machine_usize(i: u64, cx: &impl HasDataLayout) -> Self {
318+
Self::from_uint(i, cx.data_layout().pointer_size)
319+
}
320+
290321
#[inline]
291322
pub fn try_from_int(i: impl Into<i128>, size: Size) -> Option<Self> {
292323
let i = i.into();
@@ -306,6 +337,11 @@ impl<'tcx, Tag> Scalar<Tag> {
306337
.unwrap_or_else(|| bug!("Signed value {:#x} does not fit in {} bits", i, size.bits()))
307338
}
308339

340+
#[inline]
341+
pub fn from_machine_isize(i: i64, cx: &impl HasDataLayout) -> Self {
342+
Self::from_int(i, cx.data_layout().pointer_size)
343+
}
344+
309345
#[inline]
310346
pub fn from_f32(f: Single) -> Self {
311347
// We trust apfloat to give us properly truncated data.

src/librustc/query/mod.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -519,7 +519,7 @@ rustc_queries! {
519519
/// Extracts a field of a (variant of a) const.
520520
query const_field(
521521
key: ty::ParamEnvAnd<'tcx, (&'tcx ty::Const<'tcx>, mir::Field)>
522-
) -> &'tcx ty::Const<'tcx> {
522+
) -> ConstValue<'tcx> {
523523
no_force
524524
desc { "extract field of const" }
525525
}
@@ -533,7 +533,7 @@ rustc_queries! {
533533
desc { "destructure constant" }
534534
}
535535

536-
query const_caller_location(key: (rustc_span::Symbol, u32, u32)) -> &'tcx ty::Const<'tcx> {
536+
query const_caller_location(key: (rustc_span::Symbol, u32, u32)) -> ConstValue<'tcx> {
537537
no_force
538538
desc { "get a &core::panic::Location referring to a span" }
539539
}

src/librustc/ty/mod.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2388,10 +2388,10 @@ impl<'tcx> AdtDef {
23882388
let repr_type = self.repr.discr_type();
23892389
match tcx.const_eval_poly(expr_did) {
23902390
Ok(val) => {
2391-
// FIXME: Find the right type and use it instead of `val.ty` here
2392-
if let Some(b) = val.try_eval_bits(tcx, param_env, val.ty) {
2391+
let ty = repr_type.to_ty(tcx);
2392+
if let Some(b) = val.try_to_bits_for_ty(tcx, param_env, ty) {
23932393
trace!("discriminants: {} ({:?})", b, repr_type);
2394-
Some(Discr { val: b, ty: val.ty })
2394+
Some(Discr { val: b, ty })
23952395
} else {
23962396
info!("invalid enum discriminant: {:#?}", val);
23972397
crate::mir::interpret::struct_error(

src/librustc/ty/query/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use crate::middle::resolve_lifetime::{ObjectLifetimeDefault, Region, ResolveLife
1414
use crate::middle::stability::{self, DeprecationEntry};
1515
use crate::mir;
1616
use crate::mir::interpret::GlobalId;
17-
use crate::mir::interpret::{ConstEvalRawResult, ConstEvalResult};
17+
use crate::mir::interpret::{ConstEvalRawResult, ConstEvalResult, ConstValue};
1818
use crate::mir::interpret::{LitToConstError, LitToConstInput};
1919
use crate::mir::mono::CodegenUnit;
2020
use crate::session::config::{EntryFnType, OptLevel, OutputFilenames, SymbolManglingVersion};

src/librustc/ty/sty.rs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2417,9 +2417,14 @@ pub struct Const<'tcx> {
24172417
static_assert_size!(Const<'_>, 48);
24182418

24192419
impl<'tcx> Const<'tcx> {
2420+
#[inline]
2421+
pub fn from_value(tcx: TyCtxt<'tcx>, val: ConstValue<'tcx>, ty: Ty<'tcx>) -> &'tcx Self {
2422+
tcx.mk_const(Self { val: ConstKind::Value(val), ty })
2423+
}
2424+
24202425
#[inline]
24212426
pub fn from_scalar(tcx: TyCtxt<'tcx>, val: Scalar, ty: Ty<'tcx>) -> &'tcx Self {
2422-
tcx.mk_const(Self { val: ConstKind::Value(ConstValue::Scalar(val)), ty })
2427+
Self::from_value(tcx, ConstValue::Scalar(val), ty)
24232428
}
24242429

24252430
#[inline]
@@ -2473,7 +2478,9 @@ impl<'tcx> Const<'tcx> {
24732478

24742479
// try to resolve e.g. associated constants to their definition on an impl, and then
24752480
// evaluate the const.
2476-
tcx.const_eval_resolve(param_env, did, substs, promoted, None).ok()
2481+
tcx.const_eval_resolve(param_env, did, substs, promoted, None)
2482+
.ok()
2483+
.map(|val| Const::from_value(tcx, val, self.ty))
24772484
};
24782485

24792486
match self.val {

src/librustc_codegen_llvm/consts.rs

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -78,11 +78,9 @@ pub fn codegen_static_initializer(
7878
cx: &CodegenCx<'ll, 'tcx>,
7979
def_id: DefId,
8080
) -> Result<(&'ll Value, &'tcx Allocation), ErrorHandled> {
81-
let static_ = cx.tcx.const_eval_poly(def_id)?;
82-
83-
let alloc = match static_.val {
84-
ty::ConstKind::Value(ConstValue::ByRef { alloc, offset }) if offset.bytes() == 0 => alloc,
85-
_ => bug!("static const eval returned {:#?}", static_),
81+
let alloc = match cx.tcx.const_eval_poly(def_id)? {
82+
ConstValue::ByRef { alloc, offset } if offset.bytes() == 0 => alloc,
83+
val => bug!("static const eval returned {:#?}", val),
8684
};
8785
Ok((const_alloc_to_llvm(cx, alloc), alloc))
8886
}

src/librustc_codegen_llvm/intrinsic.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,7 @@ impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
193193
.tcx
194194
.const_eval_instance(ty::ParamEnv::reveal_all(), instance, None)
195195
.unwrap();
196-
OperandRef::from_const(self, ty_name).immediate_or_packed_pair(self)
196+
OperandRef::from_const(self, ty_name, ret_ty).immediate_or_packed_pair(self)
197197
}
198198
"init" => {
199199
let ty = substs.type_at(0);

src/librustc_codegen_ssa/mir/block.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -991,7 +991,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
991991
caller.line as u32,
992992
caller.col_display as u32 + 1,
993993
));
994-
OperandRef::from_const(bx, const_loc)
994+
OperandRef::from_const(bx, const_loc, bx.tcx().caller_location_ty())
995995
})
996996
}
997997

src/librustc_codegen_ssa/mir/constant.rs

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use crate::mir::operand::OperandRef;
22
use crate::traits::*;
33
use rustc::mir;
4-
use rustc::mir::interpret::ErrorHandled;
4+
use rustc::mir::interpret::{ConstValue, ErrorHandled};
55
use rustc::ty::layout::{self, HasTyCtxt};
66
use rustc::ty::{self, Ty};
77
use rustc_index::vec::Idx;
@@ -30,15 +30,16 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
3030
}
3131
_ => {
3232
let val = self.eval_mir_constant(constant)?;
33-
Ok(OperandRef::from_const(bx, val))
33+
let ty = self.monomorphize(&constant.literal.ty);
34+
Ok(OperandRef::from_const(bx, val.clone(), ty))
3435
}
3536
}
3637
}
3738

3839
pub fn eval_mir_constant(
3940
&mut self,
4041
constant: &mir::Constant<'tcx>,
41-
) -> Result<&'tcx ty::Const<'tcx>, ErrorHandled> {
42+
) -> Result<ConstValue<'tcx>, ErrorHandled> {
4243
match constant.literal.val {
4344
ty::ConstKind::Unevaluated(def_id, substs, promoted) => {
4445
let substs = self.monomorphize(&substs);
@@ -55,7 +56,15 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
5556
err
5657
})
5758
}
58-
_ => Ok(self.monomorphize(&constant.literal)),
59+
ty::ConstKind::Value(value) => Ok(value),
60+
_ => {
61+
let const_ = self.monomorphize(&constant.literal);
62+
if let ty::ConstKind::Value(value) = const_.val {
63+
Ok(value)
64+
} else {
65+
span_bug!(constant.span, "encountered bad ConstKind in codegen: {:?}", const_);
66+
}
67+
}
5968
}
6069
}
6170

@@ -65,21 +74,22 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
6574
bx: &Bx,
6675
span: Span,
6776
ty: Ty<'tcx>,
68-
constant: Result<&'tcx ty::Const<'tcx>, ErrorHandled>,
77+
constant: Result<ConstValue<'tcx>, ErrorHandled>,
6978
) -> (Bx::Value, Ty<'tcx>) {
7079
constant
71-
.map(|c| {
72-
let field_ty = c.ty.builtin_index().unwrap();
73-
let fields = match c.ty.kind {
80+
.map(|val| {
81+
let field_ty = ty.builtin_index().unwrap();
82+
let fields = match ty.kind {
7483
ty::Array(_, n) => n.eval_usize(bx.tcx(), ty::ParamEnv::reveal_all()),
75-
_ => bug!("invalid simd shuffle type: {}", c.ty),
84+
_ => bug!("invalid simd shuffle type: {}", ty),
7685
};
86+
let c = ty::Const::from_value(bx.tcx(), val, ty);
7787
let values: Vec<_> = (0..fields)
7888
.map(|field| {
7989
let field = bx.tcx().const_field(
8090
ty::ParamEnv::reveal_all().and((&c, mir::Field::new(field as usize))),
8191
);
82-
if let Some(prim) = field.val.try_to_scalar() {
92+
if let Some(prim) = field.try_to_scalar() {
8393
let layout = bx.layout_of(field_ty);
8494
let scalar = match layout.abi {
8595
layout::Abi::Scalar(ref x) => x,

0 commit comments

Comments
 (0)