Skip to content

Commit 93b8ebd

Browse files
committed
Auto merge of #50612 - Zoxc:thin-slice, r=<try>
Make &Slice a thin pointer Split out from #50395 r? @michaelwoerister
2 parents 38fd7ea + 60ca7ef commit 93b8ebd

File tree

5 files changed

+139
-45
lines changed

5 files changed

+139
-45
lines changed

src/libarena/lib.rs

+34-25
Original file line numberDiff line numberDiff line change
@@ -314,17 +314,15 @@ impl DroplessArena {
314314
false
315315
}
316316

317-
fn align_for<T>(&self) {
318-
let align = mem::align_of::<T>();
317+
fn align(&self, align: usize) {
319318
let final_address = ((self.ptr.get() as usize) + align - 1) & !(align - 1);
320319
self.ptr.set(final_address as *mut u8);
321320
assert!(self.ptr <= self.end);
322321
}
323322

324323
#[inline(never)]
325324
#[cold]
326-
fn grow<T>(&self, n: usize) {
327-
let needed_bytes = n * mem::size_of::<T>();
325+
fn grow(&self, needed_bytes: usize) {
328326
unsafe {
329327
let mut chunks = self.chunks.borrow_mut();
330328
let (chunk, mut new_capacity);
@@ -356,25 +354,38 @@ impl DroplessArena {
356354
}
357355

358356
#[inline]
359-
pub fn alloc<T>(&self, object: T) -> &mut T {
357+
pub fn alloc_raw(&self, bytes: usize, align: usize) -> &mut [u8] {
360358
unsafe {
361-
assert!(!mem::needs_drop::<T>());
362-
assert!(mem::size_of::<T>() != 0);
359+
assert!(bytes != 0);
360+
361+
self.align(align);
363362

364-
self.align_for::<T>();
365-
let future_end = intrinsics::arith_offset(self.ptr.get(), mem::size_of::<T>() as isize);
363+
let future_end = intrinsics::arith_offset(self.ptr.get(), bytes as isize);
366364
if (future_end as *mut u8) >= self.end.get() {
367-
self.grow::<T>(1)
365+
self.grow(bytes);
368366
}
369367

370368
let ptr = self.ptr.get();
371369
// Set the pointer past ourselves
372370
self.ptr.set(
373-
intrinsics::arith_offset(self.ptr.get(), mem::size_of::<T>() as isize) as *mut u8,
371+
intrinsics::arith_offset(self.ptr.get(), bytes as isize) as *mut u8,
374372
);
373+
slice::from_raw_parts_mut(ptr, bytes)
374+
}
375+
}
376+
377+
#[inline]
378+
pub fn alloc<T>(&self, object: T) -> &mut T {
379+
assert!(!mem::needs_drop::<T>());
380+
381+
let mem = self.alloc_raw(
382+
mem::size_of::<T>(),
383+
mem::align_of::<T>()) as *mut _ as *mut T;
384+
385+
unsafe {
375386
// Write into uninitialized memory.
376-
ptr::write(ptr as *mut T, object);
377-
&mut *(ptr as *mut T)
387+
ptr::write(mem, object);
388+
&mut *mem
378389
}
379390
}
380391

@@ -393,21 +404,13 @@ impl DroplessArena {
393404
assert!(!mem::needs_drop::<T>());
394405
assert!(mem::size_of::<T>() != 0);
395406
assert!(slice.len() != 0);
396-
self.align_for::<T>();
397407

398-
let future_end = unsafe {
399-
intrinsics::arith_offset(self.ptr.get(), (slice.len() * mem::size_of::<T>()) as isize)
400-
};
401-
if (future_end as *mut u8) >= self.end.get() {
402-
self.grow::<T>(slice.len());
403-
}
408+
let mem = self.alloc_raw(
409+
slice.len() * mem::size_of::<T>(),
410+
mem::align_of::<T>()) as *mut _ as *mut T;
404411

405412
unsafe {
406-
let arena_slice = slice::from_raw_parts_mut(self.ptr.get() as *mut T, slice.len());
407-
self.ptr.set(intrinsics::arith_offset(
408-
self.ptr.get(),
409-
(slice.len() * mem::size_of::<T>()) as isize,
410-
) as *mut u8);
413+
let arena_slice = slice::from_raw_parts_mut(mem, slice.len());
411414
arena_slice.copy_from_slice(slice);
412415
arena_slice
413416
}
@@ -464,6 +467,12 @@ impl SyncDroplessArena {
464467
self.lock.lock().in_arena(ptr)
465468
}
466469

470+
#[inline(always)]
471+
pub fn alloc_raw(&self, bytes: usize, align: usize) -> &mut [u8] {
472+
// Extend the lifetime of the result since it's limited to the lock guard
473+
unsafe { &mut *(self.lock.lock().alloc_raw(bytes, align) as *mut [u8]) }
474+
}
475+
467476
#[inline(always)]
468477
pub fn alloc<T>(&self, object: T) -> &mut T {
469478
// Extend the lifetime of the result since it's limited to the lock guard

src/librustc/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@
5454
#![feature(macro_vis_matcher)]
5555
#![feature(never_type)]
5656
#![feature(exhaustive_patterns)]
57+
#![feature(extern_types)]
5758
#![feature(non_exhaustive)]
5859
#![feature(proc_macro_internals)]
5960
#![feature(quote)]

src/librustc/ty/context.rs

+21-12
Original file line numberDiff line numberDiff line change
@@ -794,6 +794,12 @@ impl<'a, 'gcx> HashStable<StableHashingContext<'a>> for TypeckTables<'gcx> {
794794

795795
impl<'tcx> CommonTypes<'tcx> {
796796
fn new(interners: &CtxtInterners<'tcx>) -> CommonTypes<'tcx> {
797+
// Ensure our type representation does not grow
798+
#[cfg(target_pointer_width = "64")]
799+
assert!(mem::size_of::<ty::TypeVariants>() <= 24);
800+
#[cfg(target_pointer_width = "64")]
801+
assert!(mem::size_of::<ty::TyS>() <= 32);
802+
797803
let mk = |sty| CtxtInterners::intern_ty(interners, interners, sty);
798804
let mk_region = |r| {
799805
if let Some(r) = interners.region.borrow().get(&r) {
@@ -2124,9 +2130,8 @@ for Interned<'tcx, Slice<Goal<'tcx>>> {
21242130

21252131
macro_rules! intern_method {
21262132
($lt_tcx:tt, $name:ident: $method:ident($alloc:ty,
2127-
$alloc_method:ident,
2133+
$alloc_method:expr,
21282134
$alloc_to_key:expr,
2129-
$alloc_to_ret:expr,
21302135
$keep_in_local_tcx:expr) -> $ty:ty) => {
21312136
impl<'a, 'gcx, $lt_tcx> TyCtxt<'a, 'gcx, $lt_tcx> {
21322137
pub fn $method(self, v: $alloc) -> &$lt_tcx $ty {
@@ -2149,7 +2154,7 @@ macro_rules! intern_method {
21492154
v);
21502155
}
21512156

2152-
let i = ($alloc_to_ret)(self.interners.arena.$alloc_method(v));
2157+
let i = $alloc_method(&self.interners.arena, v);
21532158
interner.insert(Interned(i));
21542159
i
21552160
} else {
@@ -2162,7 +2167,9 @@ macro_rules! intern_method {
21622167
let v = unsafe {
21632168
mem::transmute(v)
21642169
};
2165-
let i = ($alloc_to_ret)(self.global_interners.arena.$alloc_method(v));
2170+
let i: &$lt_tcx $ty = $alloc_method(&self.global_interners.arena, v);
2171+
// Cast to 'gcx
2172+
let i = unsafe { mem::transmute(i) };
21662173
interner.insert(Interned(i));
21672174
i
21682175
}
@@ -2189,8 +2196,10 @@ macro_rules! direct_interners {
21892196

21902197
intern_method!(
21912198
$lt_tcx,
2192-
$name: $method($ty, alloc, |x| x, |x| x, $keep_in_local_tcx) -> $ty
2193-
);)+
2199+
$name: $method($ty,
2200+
|a: &$lt_tcx SyncDroplessArena, v| -> &$lt_tcx $ty { a.alloc(v) },
2201+
|x| x,
2202+
$keep_in_local_tcx) -> $ty);)+
21942203
}
21952204
}
21962205

@@ -2205,10 +2214,11 @@ direct_interners!('tcx,
22052214

22062215
macro_rules! slice_interners {
22072216
($($field:ident: $method:ident($ty:ident)),+) => (
2208-
$(intern_method!('tcx, $field: $method(&[$ty<'tcx>], alloc_slice, Deref::deref,
2209-
|xs: &[$ty]| -> &Slice<$ty> {
2210-
unsafe { mem::transmute(xs) }
2211-
}, |xs: &[$ty]| xs.iter().any(keep_local)) -> Slice<$ty<'tcx>>);)+
2217+
$(intern_method!( 'tcx, $field: $method(
2218+
&[$ty<'tcx>],
2219+
|a, v| Slice::from_arena(a, v),
2220+
Deref::deref,
2221+
|xs: &[$ty]| xs.iter().any(keep_local)) -> Slice<$ty<'tcx>>);)+
22122222
)
22132223
}
22142224

@@ -2230,9 +2240,8 @@ intern_method! {
22302240
'tcx,
22312241
canonical_var_infos: _intern_canonical_var_infos(
22322242
&[CanonicalVarInfo],
2233-
alloc_slice,
2243+
|a, v| Slice::from_arena(a, v),
22342244
Deref::deref,
2235-
|xs: &[CanonicalVarInfo]| -> &Slice<CanonicalVarInfo> { unsafe { mem::transmute(xs) } },
22362245
|_xs: &[CanonicalVarInfo]| -> bool { false }
22372246
) -> Slice<CanonicalVarInfo>
22382247
}

src/librustc/ty/mod.rs

+82-7
Original file line numberDiff line numberDiff line change
@@ -36,12 +36,14 @@ use ty::util::{IntTypeExt, Discr};
3636
use ty::walk::TypeWalker;
3737
use util::captures::Captures;
3838
use util::nodemap::{NodeSet, DefIdMap, FxHashMap};
39+
use arena::SyncDroplessArena;
3940

4041
use serialize::{self, Encodable, Encoder};
4142
use std::cell::RefCell;
4243
use std::cmp;
4344
use std::fmt;
4445
use std::hash::{Hash, Hasher};
46+
use std::marker::PhantomData;
4547
use std::ops::Deref;
4648
use rustc_data_structures::sync::Lrc;
4749
use std::slice;
@@ -570,38 +572,106 @@ impl <'gcx: 'tcx, 'tcx> Canonicalize<'gcx, 'tcx> for Ty<'tcx> {
570572
}
571573
}
572574

575+
extern {
576+
/// A dummy type used to force Slice to by unsized without requiring fat pointers
577+
type OpaqueSliceContents;
578+
}
579+
573580
/// A wrapper for slices with the additional invariant
574581
/// that the slice is interned and no other slice with
575582
/// the same contents can exist in the same context.
576583
/// This means we can use pointer + length for both
577584
/// equality comparisons and hashing.
578-
#[derive(Debug, RustcEncodable)]
579-
pub struct Slice<T>([T]);
585+
pub struct Slice<T>(PhantomData<T>, OpaqueSliceContents);
580586

581-
impl<T> PartialEq for Slice<T> {
587+
impl<T> Slice<T> {
588+
/// Returns the offset of the array
589+
#[inline(always)]
590+
fn offset() -> usize {
591+
// Align up the size of the len (usize) field
592+
let align = mem::align_of::<T>();
593+
let align_mask = align - 1;
594+
let offset = mem::size_of::<usize>();
595+
(offset + align_mask) & !align_mask
596+
}
597+
}
598+
599+
impl<T: Copy> Slice<T> {
600+
#[inline]
601+
fn from_arena<'tcx>(arena: &'tcx SyncDroplessArena, slice: &[T]) -> &'tcx Slice<T> {
602+
assert!(!mem::needs_drop::<T>());
603+
assert!(mem::size_of::<T>() != 0);
604+
assert!(slice.len() != 0);
605+
606+
let offset = Slice::<T>::offset();
607+
let size = offset + slice.len() * mem::size_of::<T>();
608+
609+
let mem: *mut u8 = arena.alloc_raw(
610+
size,
611+
cmp::max(mem::align_of::<T>(), mem::align_of::<usize>())).as_mut_ptr();
612+
613+
unsafe {
614+
// Write the length
615+
*(mem as *mut usize) = slice.len();
616+
617+
// Write the elements
618+
let arena_slice = slice::from_raw_parts_mut(
619+
mem.offset(offset as isize) as *mut T,
620+
slice.len());
621+
arena_slice.copy_from_slice(slice);
622+
623+
&*(mem as *const Slice<T>)
624+
}
625+
}
626+
}
627+
628+
impl<T: fmt::Debug> fmt::Debug for Slice<T> {
629+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
630+
(**self).fmt(f)
631+
}
632+
}
633+
634+
impl<T: Encodable> Encodable for Slice<T> {
635+
#[inline]
636+
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
637+
(**self).encode(s)
638+
}
639+
}
640+
641+
impl<T: PartialEq> PartialEq for Slice<T> {
582642
#[inline]
583643
fn eq(&self, other: &Slice<T>) -> bool {
584-
(&self.0 as *const [T]) == (&other.0 as *const [T])
644+
let r = (self as *const _) == (other as *const _);
645+
assert_eq!(r, **self == **other);
646+
r
585647
}
586648
}
587-
impl<T> Eq for Slice<T> {}
649+
impl<T: Eq> Eq for Slice<T> {}
588650

589651
impl<T> Hash for Slice<T> {
652+
#[inline]
590653
fn hash<H: Hasher>(&self, s: &mut H) {
591654
(self.as_ptr(), self.len()).hash(s)
592655
}
593656
}
594657

595658
impl<T> Deref for Slice<T> {
596659
type Target = [T];
660+
#[inline(always)]
597661
fn deref(&self) -> &[T] {
598-
&self.0
662+
unsafe {
663+
let raw = self as *const _ as *const u8;
664+
let len = *(raw as *const usize);
665+
let slice = raw.offset(Slice::<T>::offset() as isize);
666+
slice::from_raw_parts(slice as *const T, len)
667+
}
599668
}
600669
}
601670

602671
impl<'a, T> IntoIterator for &'a Slice<T> {
603672
type Item = &'a T;
604673
type IntoIter = <&'a [T] as IntoIterator>::IntoIter;
674+
#[inline(always)]
605675
fn into_iter(self) -> Self::IntoIter {
606676
self[..].iter()
607677
}
@@ -610,9 +680,14 @@ impl<'a, T> IntoIterator for &'a Slice<T> {
610680
impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Slice<Ty<'tcx>> {}
611681

612682
impl<T> Slice<T> {
683+
#[inline(always)]
613684
pub fn empty<'a>() -> &'a Slice<T> {
685+
#[repr(align(64), C)]
686+
struct EmptySlice([usize; 64]);
687+
static EMPTY_SLICE: EmptySlice = EmptySlice([0; 64]);
688+
assert!(mem::align_of::<T>() <= 64);
614689
unsafe {
615-
mem::transmute(slice::from_raw_parts(0x1 as *const T, 0))
690+
&*(&EMPTY_SLICE as *const _ as *const Slice<T>)
616691
}
617692
}
618693
}

src/test/mir-opt/basic_assignment.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ fn main() {
4848
// _2 = move _3;
4949
// StorageDead(_3);
5050
// StorageLive(_4);
51-
// UserAssertTy(Canonical { variables: Slice([]), value: std::option::Option<std::boxed::Box<u32>> }, _4);
51+
// UserAssertTy(Canonical { variables: [], value: std::option::Option<std::boxed::Box<u32>> }, _4);
5252
// _4 = std::option::Option<std::boxed::Box<u32>>::None;
5353
// StorageLive(_5);
5454
// StorageLive(_6);

0 commit comments

Comments
 (0)