Skip to content

Commit 7c7b90d

Browse files
committed
interning cleanup: we no longer need to distinguish Const and ConstInner; we no longer need the ignore_interior_mut_in_const hack
1 parent 341170d commit 7c7b90d

File tree

7 files changed

+33
-81
lines changed

7 files changed

+33
-81
lines changed

compiler/rustc_middle/src/mir/mod.rs

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -210,16 +210,6 @@ pub struct Body<'tcx> {
210210
/// We hold in this field all the constants we are not able to evaluate yet.
211211
pub required_consts: Vec<Constant<'tcx>>,
212212

213-
/// The user may be writing e.g. `&[(SOME_CELL, 42)][i].1` and this would get promoted, because
214-
/// we'd statically know that no thing with interior mutability will ever be available to the
215-
/// user without some serious unsafe code. Now this means that our promoted is actually
216-
/// `&[(SOME_CELL, 42)]` and the MIR using it will do the `&promoted[i].1` projection because
217-
/// the index may be a runtime value. Such a promoted value is illegal because it has reachable
218-
/// interior mutability. This flag just makes this situation very obvious where the previous
219-
/// implementation without the flag hid this situation silently.
220-
/// FIXME(oli-obk): rewrite the promoted during promotion to eliminate the cell components.
221-
pub ignore_interior_mut_in_const_validation: bool,
222-
223213
/// Does this body use generic parameters. This is used for the `ConstEvaluatable` check.
224214
///
225215
/// Note that this does not actually mean that this body is not computable right now.
@@ -276,7 +266,6 @@ impl<'tcx> Body<'tcx> {
276266
var_debug_info,
277267
span,
278268
required_consts: Vec::new(),
279-
ignore_interior_mut_in_const_validation: false,
280269
is_polymorphic: false,
281270
predecessor_cache: PredecessorCache::new(),
282271
};
@@ -306,7 +295,6 @@ impl<'tcx> Body<'tcx> {
306295
required_consts: Vec::new(),
307296
generator_kind: None,
308297
var_debug_info: Vec::new(),
309-
ignore_interior_mut_in_const_validation: false,
310298
is_polymorphic: false,
311299
predecessor_cache: PredecessorCache::new(),
312300
};

compiler/rustc_mir/src/const_eval/eval_queries.rs

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -67,12 +67,7 @@ fn eval_body_using_ecx<'mir, 'tcx>(
6767
None => InternKind::Constant,
6868
}
6969
};
70-
intern_const_alloc_recursive(
71-
ecx,
72-
intern_kind,
73-
ret,
74-
body.ignore_interior_mut_in_const_validation,
75-
);
70+
intern_const_alloc_recursive(ecx, intern_kind, ret);
7671

7772
debug!("eval_body_using_ecx done: {:?}", *ret);
7873
Ok(ret)
@@ -373,7 +368,13 @@ pub fn eval_to_allocation_raw_provider<'tcx>(
373368
// Since evaluation had no errors, valiate the resulting constant:
374369
let validation = try {
375370
// FIXME do not validate promoteds until a decision on
376-
// https://github.com/rust-lang/rust/issues/67465 is made
371+
// https://github.com/rust-lang/rust/issues/67465 and
372+
// https://github.com/rust-lang/rust/issues/67534 is made.
373+
// Promoteds can contain unexpected `UnsafeCell` and reference `static`s, but their
374+
// otherwise restricted form ensures that this is still sound. We just lose the
375+
// extra safety net of some of the dynamic checks. They can also contain invalid
376+
// values, but since we do not usually check intermediate results of a computation
377+
// for validity, it might be surprising to do that here.
377378
if cid.promoted.is_none() {
378379
let mut ref_tracking = RefTracking::new(mplace);
379380
let mut inner = false;

compiler/rustc_mir/src/const_eval/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ pub(crate) fn const_caller_location(
2929
let mut ecx = mk_eval_cx(tcx, DUMMY_SP, ty::ParamEnv::reveal_all(), false);
3030

3131
let loc_place = ecx.alloc_caller_location(file, line, col);
32-
intern_const_alloc_recursive(&mut ecx, InternKind::Constant, loc_place, false);
32+
intern_const_alloc_recursive(&mut ecx, InternKind::Constant, loc_place);
3333
ConstValue::Scalar(loc_place.ptr)
3434
}
3535

compiler/rustc_mir/src/interpret/intern.rs

Lines changed: 16 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use super::validity::RefTracking;
77
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
88
use rustc_hir as hir;
99
use rustc_middle::mir::interpret::InterpResult;
10-
use rustc_middle::ty::{self, layout::TyAndLayout, query::TyCtxtAt, Ty};
10+
use rustc_middle::ty::{self, layout::TyAndLayout, Ty};
1111
use rustc_target::abi::Size;
1212

1313
use rustc_ast::Mutability;
@@ -40,11 +40,6 @@ struct InternVisitor<'rt, 'mir, 'tcx, M: CompileTimeMachine<'mir, 'tcx>> {
4040
/// This field stores whether we are *currently* inside an `UnsafeCell`. This can affect
4141
/// the intern mode of references we encounter.
4242
inside_unsafe_cell: bool,
43-
44-
/// This flag is to avoid triggering UnsafeCells are not allowed behind references in constants
45-
/// for promoteds.
46-
/// It's a copy of `mir::Body`'s ignore_interior_mut_in_const_validation field
47-
ignore_interior_mut_in_const: bool,
4843
}
4944

5045
#[derive(Copy, Clone, Debug, PartialEq, Hash, Eq)]
@@ -53,22 +48,14 @@ enum InternMode {
5348
/// this is *immutable*, and below mutable references inside an `UnsafeCell`, this
5449
/// is *mutable*.
5550
Static(hir::Mutability),
56-
/// The "base value" of a const, which can have `UnsafeCell` (as in `const FOO: Cell<i32>`),
57-
/// but that interior mutability is simply ignored.
58-
ConstBase,
59-
/// The "inner values" of a const with references, where `UnsafeCell` is an error.
60-
ConstInner,
51+
/// A `const`.
52+
Const,
6153
}
6254

6355
/// Signalling data structure to ensure we don't recurse
6456
/// into the memory of other constants or statics
6557
struct IsStaticOrFn;
6658

67-
fn mutable_memory_in_const(tcx: TyCtxtAt<'_>, kind: &str) {
68-
// FIXME: show this in validation instead so we can point at where in the value the error is?
69-
tcx.sess.span_err(tcx.span, &format!("mutable memory ({}) is not allowed in constant", kind));
70-
}
71-
7259
/// Intern an allocation without looking at its children.
7360
/// `mode` is the mode of the environment where we found this pointer.
7461
/// `mutablity` is the mutability of the place to be interned; even if that says
@@ -165,17 +152,13 @@ impl<'rt, 'mir, 'tcx: 'mir, M: CompileTimeMachine<'mir, 'tcx>> ValueVisitor<'mir
165152
mplace: MPlaceTy<'tcx>,
166153
fields: impl Iterator<Item = InterpResult<'tcx, Self::V>>,
167154
) -> InterpResult<'tcx> {
155+
// ZSTs cannot contain pointers, so we can skip them.
156+
if mplace.layout.is_zst() {
157+
return Ok(());
158+
}
159+
168160
if let Some(def) = mplace.layout.ty.ty_adt_def() {
169161
if Some(def.did) == self.ecx.tcx.lang_items().unsafe_cell_type() {
170-
if self.mode == InternMode::ConstInner && !self.ignore_interior_mut_in_const {
171-
// We do not actually make this memory mutable. But in case the user
172-
// *expected* it to be mutable, make sure we error. This is just a
173-
// sanity check to prevent users from accidentally exploiting the UB
174-
// they caused. It also helps us to find cases where const-checking
175-
// failed to prevent an `UnsafeCell` (but as `ignore_interior_mut_in_const`
176-
// shows that part is not airtight).
177-
//mutable_memory_in_const(self.ecx.tcx, "`UnsafeCell`");
178-
}
179162
// We are crossing over an `UnsafeCell`, we can mutate again. This means that
180163
// References we encounter inside here are interned as pointing to mutable
181164
// allocations.
@@ -187,11 +170,6 @@ impl<'rt, 'mir, 'tcx: 'mir, M: CompileTimeMachine<'mir, 'tcx>> ValueVisitor<'mir
187170
}
188171
}
189172

190-
// ZSTs cannot contain pointers, so we can skip them.
191-
if mplace.layout.is_zst() {
192-
return Ok(());
193-
}
194-
195173
self.walk_aggregate(mplace, fields)
196174
}
197175

@@ -211,7 +189,7 @@ impl<'rt, 'mir, 'tcx: 'mir, M: CompileTimeMachine<'mir, 'tcx>> ValueVisitor<'mir
211189
if let Scalar::Ptr(vtable) = mplace.meta.unwrap_meta() {
212190
// Explicitly choose const mode here, since vtables are immutable, even
213191
// if the reference of the fat pointer is mutable.
214-
self.intern_shallow(vtable.alloc_id, InternMode::ConstInner, None);
192+
self.intern_shallow(vtable.alloc_id, InternMode::Const, None);
215193
} else {
216194
// Validation will error (with a better message) on an invalid vtable pointer.
217195
// Let validation show the error message, but make sure it *does* error.
@@ -223,7 +201,7 @@ impl<'rt, 'mir, 'tcx: 'mir, M: CompileTimeMachine<'mir, 'tcx>> ValueVisitor<'mir
223201
// Only recurse for allocation-backed pointers.
224202
if let Scalar::Ptr(ptr) = mplace.ptr {
225203
// Compute the mode with which we intern this. Our goal here is to make as many
226-
// statics as we can immutable so they can be placed in const memory by LLVM.
204+
// statics as we can immutable so they can be placed in read-only memory by LLVM.
227205
let ref_mode = match self.mode {
228206
InternMode::Static(mutbl) => {
229207
// In statics, merge outer mutability with reference mutability and
@@ -257,27 +235,11 @@ impl<'rt, 'mir, 'tcx: 'mir, M: CompileTimeMachine<'mir, 'tcx>> ValueVisitor<'mir
257235
}
258236
}
259237
}
260-
InternMode::ConstBase | InternMode::ConstInner => {
261-
// Ignore `UnsafeCell`, everything is immutable. Do some sanity checking
262-
// for mutable references that we encounter -- they must all be ZST.
263-
// This helps to prevent users from accidentally exploiting UB that they
264-
// caused (by somehow getting a mutable reference in a `const`).
265-
if ref_mutability == Mutability::Mut {
266-
/*match referenced_ty.kind() {
267-
ty::Array(_, n) if n.eval_usize(*tcx, self.ecx.param_env) == 0 => {}
268-
ty::Slice(_)
269-
if mplace.meta.unwrap_meta().to_machine_usize(self.ecx)?
270-
== 0 => {}
271-
_ => mutable_memory_in_const(tcx, "`&mut`"),
272-
}*/
273-
} else {
274-
// A shared reference. We cannot check `freeze` here due to references
275-
// like `&dyn Trait` that are actually immutable. We do check for
276-
// concrete `UnsafeCell` when traversing the pointee though (if it is
277-
// a new allocation, not yet interned).
278-
}
279-
// Go on with the "inner" rules.
280-
InternMode::ConstInner
238+
InternMode::Const => {
239+
// Ignore `UnsafeCell`, everything is immutable. Validity does some sanity
240+
// checking for mutable references that we encounter -- they must all be
241+
// ZST.
242+
InternMode::Const
281243
}
282244
};
283245
match self.intern_shallow(ptr.alloc_id, ref_mode, Some(referenced_ty)) {
@@ -316,7 +278,6 @@ pub fn intern_const_alloc_recursive<M: CompileTimeMachine<'mir, 'tcx>>(
316278
ecx: &mut InterpCx<'mir, 'tcx, M>,
317279
intern_kind: InternKind,
318280
ret: MPlaceTy<'tcx>,
319-
ignore_interior_mut_in_const: bool,
320281
) where
321282
'tcx: 'mir,
322283
{
@@ -325,7 +286,7 @@ pub fn intern_const_alloc_recursive<M: CompileTimeMachine<'mir, 'tcx>>(
325286
InternKind::Static(mutbl) => InternMode::Static(mutbl),
326287
// `Constant` includes array lengths.
327288
// `Promoted` includes non-`Copy` array initializers and `rustc_args_required_const` arguments.
328-
InternKind::Constant | InternKind::Promoted => InternMode::ConstBase,
289+
InternKind::Constant | InternKind::Promoted => InternMode::Const,
329290
};
330291

331292
// Type based interning.
@@ -355,7 +316,6 @@ pub fn intern_const_alloc_recursive<M: CompileTimeMachine<'mir, 'tcx>>(
355316
ecx,
356317
mode,
357318
leftover_allocations,
358-
ignore_interior_mut_in_const,
359319
inside_unsafe_cell: false,
360320
}
361321
.visit_value(mplace);

compiler/rustc_mir/src/interpret/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ pub use self::machine::{compile_time_machine, AllocMap, Machine, MayLeak, StackP
2424
pub use self::memory::{AllocCheck, FnVal, Memory, MemoryKind};
2525
pub use self::operand::{ImmTy, Immediate, OpTy, Operand};
2626
pub use self::place::{MPlaceTy, MemPlace, MemPlaceMeta, Place, PlaceTy};
27-
pub use self::validity::{RefTracking, CtfeValidationMode};
27+
pub use self::validity::{CtfeValidationMode, RefTracking};
2828
pub use self::visitor::{MutValueVisitor, ValueVisitor};
2929

3030
crate use self::intrinsics::eval_nullary_intrinsic;

compiler/rustc_mir/src/interpret/validity.rs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,8 @@ pub enum CtfeValidationMode {
119119
Regular,
120120
/// Validation of a `const`. `inner` says if this is an inner, indirect allocation (as opposed
121121
/// to the top-level const allocation).
122+
/// Being an inner allocation makes a difference because the top-level allocation of a `const`
123+
/// is copied for each use, but the inner allocations are implicitly shared.
122124
Const { inner: bool },
123125
}
124126

@@ -541,8 +543,10 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, '
541543
Ok(true)
542544
}
543545
ty::Ref(_, ty, mutbl) => {
544-
if matches!(self.ctfe_mode, Some(CtfeValidationMode::Const { .. })) && *mutbl == hir::Mutability::Mut {
545-
// A mutable reference inside a const? That does not seem right (except of it is
546+
if matches!(self.ctfe_mode, Some(CtfeValidationMode::Const { .. }))
547+
&& *mutbl == hir::Mutability::Mut
548+
{
549+
// A mutable reference inside a const? That does not seem right (except if it is
546550
// a ZST).
547551
let layout = self.ecx.layout_of(ty)?;
548552
if !layout.is_zst() {

compiler/rustc_mir/src/transform/promote_consts.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1176,7 +1176,7 @@ pub fn promote_candidates<'tcx>(
11761176
let mut scope = body.source_scopes[candidate.source_info(body).scope].clone();
11771177
scope.parent_scope = None;
11781178

1179-
let mut promoted = Body::new(
1179+
let promoted = Body::new(
11801180
body.source, // `promoted` gets filled in below
11811181
IndexVec::new(),
11821182
IndexVec::from_elem_n(scope, 1),
@@ -1187,7 +1187,6 @@ pub fn promote_candidates<'tcx>(
11871187
body.span,
11881188
body.generator_kind,
11891189
);
1190-
promoted.ignore_interior_mut_in_const_validation = true;
11911190

11921191
let promoter = Promoter {
11931192
promoted,

0 commit comments

Comments
 (0)