Skip to content

Commit 10df001

Browse files
authored
Merge pull request #1569 from N1ark/consts-rework-4
Fixes for const pointers
2 parents 0e07227 + 4e72667 commit 10df001

9 files changed

Lines changed: 181 additions & 84 deletions

‎charon/rustc_const_uneval/src/pointer.rs‎

Lines changed: 64 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,10 @@ use rustc_const_eval::interpret::{InterpResult, MPlaceTy, OpTy, Projectable, int
77
impl<'tcx> ConstReader<'tcx> {
88
/// Whether this allocation target should be read through a pointer -- it is otherwise
99
/// read directly, breaking sharing.
10-
fn should_use_pointer(&self, tgt: AllocTarget, in_bounds: bool) -> bool {
10+
fn should_use_pointer(&self, tgt: AllocTarget) -> bool {
1111
match tgt {
1212
AllocTarget::Global(GlobalRef::Static(_)) => true,
13-
AllocTarget::Global(_) => self.config.anon_allocs_as_globals || !in_bounds,
13+
AllocTarget::Global(_) => self.config.anon_allocs_as_globals,
1414
AllocTarget::Fn(_) | AllocTarget::VTable(..) | AllocTarget::TypeId(..) => true,
1515
}
1616
}
@@ -81,35 +81,39 @@ impl<'tcx> ConstReader<'tcx> {
8181
let alloc_target = self.alloc_target(alloc_id);
8282
// A pointer outside of its allocation (one-past-the-end is fine) needs a wrapping offset.
8383
let in_bounds = offset <= ecx.get_alloc_info(alloc_id).size;
84-
let kind = if let Some(view_ty) = view_ty
85-
&& self.should_use_pointer(alloc_target, in_bounds)
86-
{
84+
let kind = if !in_bounds || self.should_use_pointer(alloc_target) {
8785
let (decl_ty, projections, end_ty) =
8886
self.place_in_global(ecx, &place, alloc_target, offset, in_bounds, view_ty)?;
8987
let target = PtrTarget::Global {
9088
target: alloc_target,
9189
ty: decl_ty,
9290
projections,
9391
};
94-
if end_ty == tcx.erase_and_anonymize_regions(view_ty) {
92+
let (ty::Ref(.., mutability) | ty::RawPtr(_, mutability)) = *op.layout.ty.kind() else {
93+
unreachable!()
94+
};
95+
// We can't take a `*mut` to an immutable global, so we take a `*const` and cast it.
96+
let borrow_mutability = match alloc_target {
97+
AllocTarget::Global(global) => global.mutability(tcx).min(mutability),
98+
_ => mutability,
99+
};
100+
if Some(end_ty) == tcx.erase_and_anonymize_regions(view_ty)
101+
&& borrow_mutability == mutability
102+
{
95103
ConstKind::Ptr { target, unsize }
96104
} else {
97105
// Point to the place we reached, then cast the pointer to the right type.
98106
let ptr = |ty, kind| Box::new(Const { ty, kind });
99107
let inner = ptr(
100-
Ty::new_ptr(tcx, end_ty, mutability),
108+
Ty::new_ptr(tcx, end_ty, borrow_mutability),
101109
ConstKind::Ptr {
102110
target,
103111
unsize: None,
104112
},
105113
);
106-
match unsize {
107-
None => ConstKind::PtrCast {
108-
ptr: inner,
109-
unsize: None,
110-
},
114+
match (unsize, view_ty) {
111115
// Cast to the sized type first, then unsize.
112-
Some(unsize) => ConstKind::PtrCast {
116+
(Some(unsize), Some(view_ty)) => ConstKind::PtrCast {
113117
ptr: ptr(
114118
Ty::new_ptr(tcx, view_ty, mutability),
115119
ConstKind::PtrCast {
@@ -119,10 +123,9 @@ impl<'tcx> ConstReader<'tcx> {
119123
),
120124
unsize: Some(unsize),
121125
},
126+
(_, _) => ConstKind::PtrCast { ptr: inner, unsize },
122127
}
123128
}
124-
} else if !in_bounds {
125-
ConstKind::Unsupported("pointer outside of its allocation")
126129
} else {
127130
// HACK: fallback to reading the value of the pointee, at type `view_ty`.
128131
let place = match view_ty {
@@ -147,22 +150,25 @@ impl<'tcx> ConstReader<'tcx> {
147150
}
148151
}
149152

150-
/// Express the place of type `ty` located `offset` bytes into `global` (whose allocation
151-
/// `place` points into) as projections from the global. `in_bounds` tells whether that place
152-
/// is inside the global (incl. one past its end). Returns the type of the global, the
153-
/// projections and the type of the place they reach.
153+
/// Express `place`, located `offset` bytes into `global`, as projections from the global, aiming
154+
/// for a place of the sized type `ty` if any. `in_bounds` tells whether that place is inside
155+
/// the global (incl. one past its end). Returns the type of the global, the projections and the
156+
/// type of the place they reach.
154157
fn place_in_global(
155158
&self,
156159
ecx: &CompileTimeInterpCx<'tcx>,
157160
place: &MPlaceTy<'tcx>,
158161
global: AllocTarget<'tcx>,
159162
offset: Size,
160163
in_bounds: bool,
161-
ty: Ty<'tcx>,
164+
ty: Option<Ty<'tcx>>,
162165
) -> InterpResult<'tcx, (Ty<'tcx>, ProjectionPath<'tcx>, Ty<'tcx>)> {
163166
let tcx = self.tcx;
164167
let ty = tcx.erase_and_anonymize_regions(ty);
165-
let size = ecx.layout_of(ty)?.size;
168+
let size = match ecx.size_and_align_of_val(place)? {
169+
Some((size, _)) => size,
170+
None => Size::ZERO, // extern type
171+
};
166172
let decl_ty = match global {
167173
AllocTarget::Global(global) => tcx.erase_and_anonymize_regions(self.global_ty(global)),
168174
// Other allocations have no contents.
@@ -182,81 +188,87 @@ impl<'tcx> ConstReader<'tcx> {
182188
.data_layout
183189
.pointer_size()
184190
.sign_extend(offset.bytes().into());
185-
let proj = offset_projection(offset as i64, ty, size, in_bounds);
186-
// An offset reaches a place of the type we want.
187-
let end_ty = if proj.is_some() { ty } else { decl_ty };
188-
(proj.map(|proj| (proj, ty)).into_iter().collect(), end_ty)
191+
let proj = offset_projection(tcx, offset as i64, ty, size, in_bounds);
192+
let end_ty = match proj {
193+
Some((_, ty)) => ty,
194+
None => decl_ty,
195+
};
196+
(proj.into_iter().collect(), end_ty)
189197
};
190198
interp_ok((decl_ty, path, end_ty))
191199
}
192200
}
193201

194202
/// The projection to the place located `offset` bytes after the current place, for a pointee of
195-
/// type `ty` and size `size`, if `offset` isn't zero.
203+
/// size `size`, if `offset` isn't zero.
196204
fn offset_projection<'tcx>(
205+
tcx: TyCtxt<'tcx>,
197206
offset: i64,
198-
ty: Ty<'tcx>,
207+
ty: Option<Ty<'tcx>>,
199208
size: Size,
200209
in_bounds: bool,
201-
) -> Option<Projection<'tcx>> {
210+
) -> Option<(Projection<'tcx>, Ty<'tcx>)> {
202211
if offset == 0 {
203212
return None;
204213
}
205214
let size = size.bytes() as i64;
206-
let (count, ty) = if size != 0 && offset % size == 0 {
215+
let (count, elem_ty) = if let Some(ty) = ty
216+
&& size != 0
217+
&& offset % size == 0
218+
{
207219
(offset / size, Some(ty))
208220
} else {
209221
(offset, None)
210222
};
211-
Some(Projection::Offset {
223+
let proj = Projection::Offset {
212224
count,
213-
ty,
225+
ty: elem_ty,
214226
in_bounds,
215-
})
227+
};
228+
Some((proj, ty.unwrap_or(tcx.types.u8)))
216229
}
217230

218-
/// Find projections from `place` to the place of type `to_ty` and size `size` located `offset`
219-
/// bytes after it. There may be many ways of reaching the same destination. Returns the
220-
/// projections to use, and the type of the final place, which may not match `to_ty`, in which
221-
/// case a cast is needed.
231+
/// Find projections from `place` to the place of size `size` located `offset` bytes after it,
232+
/// aiming for a place of type `to_ty` if any. There may be many ways of reaching the same
233+
/// destination. Returns the projections to use, and the type of the final place, which may not
234+
/// match `to_ty`, in which case a cast is needed.
222235
fn structural_path<'tcx>(
223236
ecx: &CompileTimeInterpCx<'tcx>,
224237
mut place: MPlaceTy<'tcx>,
225238
mut offset: Size,
226-
to_ty: Ty<'tcx>,
239+
to_ty: Option<Ty<'tcx>>,
227240
size: Size,
228241
) -> (ProjectionPath<'tcx>, Ty<'tcx>) {
229242
let mut path = vec![];
230-
while !(place.layout.ty == to_ty && offset == Size::ZERO) {
243+
while !(Some(place.layout.ty) == to_ty && offset == Size::ZERO) {
231244
let Some((proj, sub, sub_offset)) = find_subplace(ecx, &place, offset, to_ty, size)
232245
.discard_err()
233246
.flatten()
234247
else {
235248
// Give up: we couldn't find a typed path, so we offset from the place we reached.
236-
let proj = offset_projection(offset.bytes() as i64, to_ty, size, true);
237-
let end_ty = if proj.is_some() {
238-
to_ty
239-
} else {
240-
place.layout.ty
249+
let proj = offset_projection(*ecx.tcx, offset.bytes() as i64, to_ty, size, true);
250+
let end_ty = match proj {
251+
Some((_, ty)) => ty,
252+
None => place.layout.ty,
241253
};
242-
path.extend(proj.map(|proj| (proj, to_ty)));
254+
path.extend(proj);
243255
return (path, end_ty);
244256
};
245257
path.push((proj, sub.layout.ty));
246258
place = sub;
247259
offset = sub_offset;
248260
}
249-
(path, to_ty)
261+
(path, place.layout.ty)
250262
}
251263

252-
/// Find the subplace of `place` that contains the place of type `to_ty` and size `size` located
253-
/// `offset` bytes after `place`. Returns the projection to that subplace, the subplace, and the
254-
/// offset of the target within it.
264+
/// Find the subplace of `place` that contains the place of size `size` (and type `to_ty`, if
265+
/// known) located `offset` bytes after `place`. Returns the projection to that subplace, the
266+
/// subplace, and the offset of the target within it.
255267
fn find_subplace<'tcx>(
256268
ecx: &CompileTimeInterpCx<'tcx>,
257269
place: &MPlaceTy<'tcx>,
258270
offset: Size,
259-
to_ty: Ty<'tcx>,
271+
to_ty: Option<Ty<'tcx>>,
260272
size: Size,
261273
) -> InterpResult<'tcx, Option<(Projection<'tcx>, MPlaceTy<'tcx>, Size)>> {
262274
match place.layout.ty.kind() {
@@ -267,7 +279,8 @@ fn find_subplace<'tcx>(
267279
return interp_ok(None);
268280
};
269281
// The target may be a subarray.
270-
if let ty::Array(target_elem, _) = to_ty.kind()
282+
if let Some(to_ty) = to_ty
283+
&& let ty::Array(target_elem, _) = to_ty.kind()
271284
&& target_elem == elem
272285
&& offset.bytes().is_multiple_of(stride)
273286
&& i + size.bytes() / stride <= len
@@ -292,7 +305,7 @@ fn find_subplace<'tcx>(
292305
ty::Adt(adt_def, _) if adt_def.is_union() => {
293306
if offset == Size::ZERO
294307
&& let Some(i) = (0..place.layout.fields.count())
295-
.find(|&i| place.layout.field(ecx, i).ty == to_ty)
308+
.find(|&i| Some(place.layout.field(ecx, i).ty) == to_ty)
296309
{
297310
let field = FieldIdx::from_usize(i);
298311
let sub = ecx.project_field(place, field)?;

‎charon/tests/ui/consts/extern-type-pointers.values.out‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ extern opaque type Opaque
4242
static X: u8 = 0u8
4343

4444
// Full name: test_crate::EXTERN
45-
static EXTERN: test_crate::Sync<*const Opaque>[{built_in impl Sized for *const Opaque}] = test_crate::Sync { _0: &raw const Opaque(Unhandled constant type) }
45+
static EXTERN: test_crate::Sync<*const Opaque>[{built_in impl Sized for *const Opaque}] = test_crate::Sync { _0: cast<*const Opaque>(&raw const X) }
4646

4747
// Full name: test_crate::EXTERN_NO_PROVENANCE
4848
static EXTERN_NO_PROVENANCE: test_crate::Sync<*const Opaque>[{built_in impl Sized for *const Opaque}] = test_crate::Sync { _0: no-provenance 8 }

‎charon/tests/ui/consts/str-pointers.unsized_strings.out‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -31,17 +31,18 @@ struct str {
3131
_0: [u8],
3232
}
3333

34-
// Full name: test_crate::{promoted_const}
35-
static {promoted_const}: MaybeUninit<[u8; 5usize]>[{built_in impl Sized for [u8; 5usize]}] = RawMemory(0x68, 0x65, 0x6c, 0x6c, 0x6f)
34+
static test_crate::{promoted_const}: MaybeUninit<[u8; 5usize]>[{built_in impl Sized for [u8; 5usize]}] = RawMemory(0x68, 0x65, 0x6c, 0x6c, 0x6f)
35+
36+
static test_crate::{promoted_const#1}: MaybeUninit<[u8; 3usize]>[{built_in impl Sized for [u8; 3usize]}] = RawMemory(0x68, 0x69, 0x00)
3637

3738
// Full name: test_crate::STR
38-
pub static STR: &'static str = unsize_cast<&'_ str, 5usize>(cast<*const [u8; 5usize]>(&raw const {promoted_const}))
39+
pub static STR: &'static str = unsize_cast<&'_ str, 5usize>(cast<*const [u8; 5usize]>(&raw const test_crate::{promoted_const}))
3940

4041
// Full name: test_crate::STR_SUFFIX
41-
pub static STR_SUFFIX: &'static str = &{promoted_const}.offset!(1isize) with_metadata(4usize)
42+
pub static STR_SUFFIX: &'static str = &test_crate::{promoted_const}.offset!(1isize) with_metadata(4usize)
4243

4344
// Full name: test_crate::CSTR
44-
pub static CSTR: &'static CStr = &CStr { 0: [104i8, 105i8, 0i8] } with_metadata(3usize)
45+
pub static CSTR: &'static CStr = unsize_cast<&'_ CStr, 3usize>(&raw const test_crate::{promoted_const#1})
4546

4647
// Full name: test_crate::W
4748
pub struct W<T>
@@ -56,7 +57,7 @@ where
5657
pub static WS: W<[u8; 2usize]>[{built_in impl MetaSized for [u8; 2usize]}] = W { _0: 0u8, _1: [1u8, 2u8] }
5758

5859
// Full name: test_crate::W_SLICE
59-
pub static W_SLICE: &'static W<[u8]>[{built_in impl MetaSized for [u8]}] = &W { _0: 0u8, _1: [1u8, 2u8] } with_metadata(2usize)
60+
pub static W_SLICE: &'static W<[u8]>[{built_in impl MetaSized for [u8]}] = unsize_cast<&'_ W<[u8]>[{built_in impl MetaSized for [u8]}], 2usize>(&raw const WS)
6061

6162

6263

‎charon/tests/ui/consts/str-pointers.values.out‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,20 +19,30 @@ pub trait Sized<Self>
1919
non-dyn-compatible
2020
}
2121

22+
// Full name: core::mem::maybe_uninit::MaybeUninit
23+
#[lang_item(MaybeUninit)]
24+
pub opaque type MaybeUninit<T>
25+
where
26+
TraitClause0: (T: Sized),
27+
2228
struct () {}
2329

2430
struct str {
2531
_0: [u8],
2632
}
2733

34+
static test_crate::{promoted_const}: MaybeUninit<[u8; 5usize]>[{built_in impl Sized for [u8; 5usize]}] = RawMemory(0x68, 0x65, 0x6c, 0x6c, 0x6f)
35+
36+
static test_crate::{promoted_const#1}: MaybeUninit<[u8; 3usize]>[{built_in impl Sized for [u8; 3usize]}] = RawMemory(0x68, 0x69, 0x00)
37+
2838
// Full name: test_crate::STR
29-
pub static STR: &'static str = "hello"
39+
pub static STR: &'static str = unsize_cast<&'_ str, 5usize>(&raw const test_crate::{promoted_const})
3040

3141
// Full name: test_crate::STR_SUFFIX
32-
pub static STR_SUFFIX: &'static str = "ello"
42+
pub static STR_SUFFIX: &'static str = unsize_cast<&'_ str, 4usize>(&raw const test_crate::{promoted_const}.offset!(1isize))
3343

3444
// Full name: test_crate::CSTR
35-
pub static CSTR: &'static CStr = &CStr { 0: [104i8, 105i8, 0i8] } with_metadata(3usize)
45+
pub static CSTR: &'static CStr = unsize_cast<&'_ CStr, 3usize>(&raw const test_crate::{promoted_const#1})
3646

3747
// Full name: test_crate::W
3848
pub struct W<T>
@@ -47,7 +57,7 @@ where
4757
pub static WS: W<[u8; 2usize]>[{built_in impl MetaSized for [u8; 2usize]}] = W { _0: 0u8, _1: [1u8, 2u8] }
4858

4959
// Full name: test_crate::W_SLICE
50-
pub static W_SLICE: &'static W<[u8]>[{built_in impl MetaSized for [u8]}] = &W { _0: 0u8, _1: [1u8, 2u8] } with_metadata(2usize)
60+
pub static W_SLICE: &'static W<[u8]>[{built_in impl MetaSized for [u8]}] = unsize_cast<&'_ W<[u8]>[{built_in impl MetaSized for [u8]}], 2usize>(&raw const WS)
5161

5262

5363

‎charon/tests/ui/consts/unsized-globals.initializers.out‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,48 @@ pub fn INTERIOR() -> &'static Wrap<[u16]>[{built_in impl MetaSized for [u16]}]
242242
// Full name: test_crate::INTERIOR
243243
pub static INTERIOR: &'static Wrap<[u16]>[{built_in impl MetaSized for [u16]}] = INTERIOR()
244244

245+
// Full name: test_crate::SIZED
246+
pub fn SIZED() -> Outer<[u16; 2usize]>[{built_in impl MetaSized for [u16; 2usize]}]
247+
{
248+
let _0: Outer<[u16; 2usize]>[{built_in impl MetaSized for [u16; 2usize]}]; // return
249+
let _1: Wrap<[u16; 2usize]>[{built_in impl MetaSized for [u16; 2usize]}]; // anonymous local
250+
let _2: [u16; 2usize]; // anonymous local
251+
252+
storage_live(_0)
253+
storage_live(_1)
254+
storage_live(_2)
255+
_2 = [const 3u16, const 4u16]
256+
_1 = Wrap { a: const 2u8, b: move _2 }
257+
storage_dead(_2)
258+
_0 = Outer { x: const 1u32, w: move _1 }
259+
storage_dead(_1)
260+
return
261+
}
262+
263+
// Full name: test_crate::SIZED
264+
pub static SIZED: Outer<[u16; 2usize]>[{built_in impl MetaSized for [u16; 2usize]}] = SIZED()
265+
266+
// Full name: test_crate::SIZED_INTERIOR
267+
pub fn SIZED_INTERIOR() -> &'static Wrap<[u16]>[{built_in impl MetaSized for [u16]}]
268+
{
269+
let _0: &'1 Wrap<[u16]>[{built_in impl MetaSized for [u16]}]; // return
270+
let _1: &'3 Wrap<[u16; 2usize]>[{built_in impl MetaSized for [u16; 2usize]}]; // anonymous local
271+
let _2: &'4 Wrap<[u16; 2usize]>[{built_in impl MetaSized for [u16; 2usize]}]; // anonymous local
272+
273+
storage_live(_0)
274+
storage_live(_1)
275+
storage_live(_2)
276+
_2 = &SIZED.w
277+
_1 = &(*_2)
278+
_0 = unsize_cast<&'8 Wrap<[u16]>[{built_in impl MetaSized for [u16]}], 2usize>(move _1)
279+
storage_dead(_2)
280+
storage_dead(_1)
281+
return
282+
}
283+
284+
// Full name: test_crate::SIZED_INTERIOR
285+
pub static SIZED_INTERIOR: &'static Wrap<[u16]>[{built_in impl MetaSized for [u16]}] = SIZED_INTERIOR()
286+
245287
struct test_crate::Trait::{vtable} {
246288
size: usize,
247289
align: usize,

‎charon/tests/ui/consts/unsized-globals.rs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,11 @@ pub const NESTED: (u8, &Outer<[u16]>) = (7, OUTER);
2525

2626
pub static STATIC: &Outer<[u16]> = OUTER;
2727
pub static INTERIOR: &Wrap<[u16]> = &STATIC.w;
28+
pub static SIZED: Outer<[u16; 2]> = Outer {
29+
x: 1,
30+
w: Wrap { a: 2, b: [3, 4] },
31+
};
32+
pub static SIZED_INTERIOR: &Wrap<[u16]> = &SIZED.w;
2833

2934
pub trait Trait: Sync {}
3035
impl Trait for u8 {}

0 commit comments

Comments
 (0)