Skip to content

Commit 3e31775

Browse files
committed
Auto merge of #135634 - joboet:trivial-clone, r=<try>
stop specializing on `Copy` fixes #132442 `std` specializes on `Copy` to optimize certain library functions such as `clone_from_slice`. This is unsound, however, as the `Copy` implementation may not be always applicable because of lifetime bounds, which specialization does not take into account; the result being that values are copied even though they are not `Copy`. For instance, this code: ```rust struct SometimesCopy<'a>(&'a Cell<bool>); impl<'a> Clone for SometimesCopy<'a> { fn clone(&self) -> Self { self.0.set(true); Self(self.0) } } impl Copy for SometimesCopy<'static> {} let clone_called = Cell::new(false); // As SometimesCopy<'clone_called> is not 'static, this must run `clone`, // setting the value to `true`. let _ = [SometimesCopy(&clone_called)].clone(); assert!(clone_called.get()); ``` should not panic, but does ([playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=6be7a48cad849d8bd064491616fdb43c)). To solve this, this PR introduces a new `unsafe` trait: `TrivialClone`. This trait may be implemented whenever the `Clone` implementation is equivalent to copying the value (so e.g. `fn clone(&self) -> Self { *self }`). Because of lifetime erasure, there is no way for the `Clone` implementation to observe lifetime bounds, meaning that even if the `TrivialClone` has stricter bounds than the `Clone` implementation, its invariant still holds. Therefore, it is sound to specialize on `TrivialClone`. I've changed all `Copy` specializations in the standard library to specialize on `TrivialClone` instead. Unfortunately, the unsound `#[rustc_unsafe_specialization_marker]` attribute on `Copy` cannot be removed in this PR as `hashbrown` still depends on it. I'll make a PR updating `hashbrown` once this lands. With `Copy` no longer being considered for specialization, this change alone would result in the standard library optimizations not being applied for user types unaware of `TrivialClone`. To avoid this and restore the optimizations in most cases, I have changed the expansion of `#[derive(Clone)]`: Currently, whenever both `Clone` and `Copy` are derived, the `clone` method performs a copy of the value. With this PR, the derive macro also adds a `TrivialClone` implementation to make this case observable using specialization. I anticipate that most users will use `#[derive(Clone, Copy)]` whenever both are applicable, so most users will still profit from the library optimizations. Unfortunately, Hyrum's law applies to this PR: there are some popular crates which rely on the precise specialization behaviour of `core` to implement "specialization at home", e.g. [`libAFL`](https://github.com/AFLplusplus/LibAFL/blob/89cff637025c1652c24e8d97a30a2e3d01f187a4/libafl_bolts/src/tuples.rs#L27-L49). I have no remorse for breaking such horrible code, but perhaps we should open other, better ways to satisfy their needs – for example by dropping the `'static` bound on `TypeId::of`...
2 parents 021fb9c + d31fbe3 commit 3e31775

File tree

28 files changed

+223
-81
lines changed

28 files changed

+223
-81
lines changed

compiler/rustc_builtin_macros/src/deriving/bounds.rs

+5-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use rustc_ast::MetaItem;
1+
use rustc_ast::{MetaItem, Safety};
22
use rustc_expand::base::{Annotatable, ExtCtxt};
33
use rustc_span::Span;
44

@@ -23,6 +23,7 @@ pub(crate) fn expand_deriving_copy(
2323
methods: Vec::new(),
2424
associated_types: Vec::new(),
2525
is_const,
26+
safety: Safety::Default,
2627
};
2728

2829
trait_def.expand(cx, mitem, item, push);
@@ -46,6 +47,7 @@ pub(crate) fn expand_deriving_const_param_ty(
4647
methods: Vec::new(),
4748
associated_types: Vec::new(),
4849
is_const,
50+
safety: Safety::Default,
4951
};
5052

5153
trait_def.expand(cx, mitem, item, push);
@@ -60,6 +62,7 @@ pub(crate) fn expand_deriving_const_param_ty(
6062
methods: Vec::new(),
6163
associated_types: Vec::new(),
6264
is_const,
65+
safety: Safety::Default,
6366
};
6467

6568
trait_def.expand(cx, mitem, item, push);
@@ -83,6 +86,7 @@ pub(crate) fn expand_deriving_unsized_const_param_ty(
8386
methods: Vec::new(),
8487
associated_types: Vec::new(),
8588
is_const,
89+
safety: Safety::Default,
8690
};
8791

8892
trait_def.expand(cx, mitem, item, push);

compiler/rustc_builtin_macros/src/deriving/clone.rs

+22-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
use rustc_ast::{self as ast, Generics, ItemKind, MetaItem, VariantData};
1+
use rustc_ast::{self as ast, Generics, ItemKind, MetaItem, Safety, VariantData};
22
use rustc_data_structures::fx::FxHashSet;
33
use rustc_expand::base::{Annotatable, ExtCtxt};
4-
use rustc_span::{Ident, Span, kw, sym};
4+
use rustc_span::{DUMMY_SP, Ident, Span, kw, sym};
55
use thin_vec::{ThinVec, thin_vec};
66

77
use crate::deriving::generic::ty::*;
@@ -68,6 +68,25 @@ pub(crate) fn expand_deriving_clone(
6868
_ => cx.dcx().span_bug(span, "`#[derive(Clone)]` on trait item or impl item"),
6969
}
7070

71+
// If the clone method is just copying the value, also mark the type as
72+
// `TrivialClone` to allow some library optimizations.
73+
if is_simple {
74+
let trivial_def = TraitDef {
75+
span,
76+
path: path_std!(clone::TrivialClone),
77+
skip_path_as_bound: false,
78+
needs_copy_as_bound_if_packed: true,
79+
additional_bounds: bounds.clone(),
80+
supports_unions: true,
81+
methods: Vec::new(),
82+
associated_types: Vec::new(),
83+
is_const,
84+
safety: Safety::Unsafe(DUMMY_SP),
85+
};
86+
87+
trivial_def.expand_ext(cx, mitem, item, push, true);
88+
}
89+
7190
let trait_def = TraitDef {
7291
span,
7392
path: path_std!(clone::Clone),
@@ -87,6 +106,7 @@ pub(crate) fn expand_deriving_clone(
87106
}],
88107
associated_types: Vec::new(),
89108
is_const,
109+
safety: Safety::Default,
90110
};
91111

92112
trait_def.expand_ext(cx, mitem, item, push, is_simple)

compiler/rustc_builtin_macros/src/deriving/cmp/eq.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use rustc_ast::{self as ast, MetaItem};
1+
use rustc_ast::{self as ast, MetaItem, Safety};
22
use rustc_data_structures::fx::FxHashSet;
33
use rustc_expand::base::{Annotatable, ExtCtxt};
44
use rustc_span::{Span, sym};
@@ -43,6 +43,7 @@ pub(crate) fn expand_deriving_eq(
4343
}],
4444
associated_types: Vec::new(),
4545
is_const,
46+
safety: Safety::Default,
4647
};
4748
trait_def.expand_ext(cx, mitem, item, push, true)
4849
}

compiler/rustc_builtin_macros/src/deriving/cmp/ord.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use rustc_ast::MetaItem;
1+
use rustc_ast::{MetaItem, Safety};
22
use rustc_expand::base::{Annotatable, ExtCtxt};
33
use rustc_span::{Ident, Span, sym};
44
use thin_vec::thin_vec;
@@ -34,6 +34,7 @@ pub(crate) fn expand_deriving_ord(
3434
}],
3535
associated_types: Vec::new(),
3636
is_const,
37+
safety: Safety::Default,
3738
};
3839

3940
trait_def.expand(cx, mitem, item, push)

compiler/rustc_builtin_macros/src/deriving/cmp/partial_eq.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use rustc_ast::ptr::P;
2-
use rustc_ast::{BinOpKind, BorrowKind, Expr, ExprKind, MetaItem, Mutability};
2+
use rustc_ast::{BinOpKind, BorrowKind, Expr, ExprKind, MetaItem, Mutability, Safety};
33
use rustc_expand::base::{Annotatable, ExtCtxt};
44
use rustc_span::{Span, sym};
55
use thin_vec::thin_vec;
@@ -84,6 +84,7 @@ pub(crate) fn expand_deriving_partial_eq(
8484
methods: Vec::new(),
8585
associated_types: Vec::new(),
8686
is_const: false,
87+
safety: Safety::Default,
8788
};
8889
structural_trait_def.expand(cx, mitem, item, push);
8990

@@ -110,6 +111,7 @@ pub(crate) fn expand_deriving_partial_eq(
110111
methods,
111112
associated_types: Vec::new(),
112113
is_const,
114+
safety: Safety::Default,
113115
};
114116
trait_def.expand(cx, mitem, item, push)
115117
}

compiler/rustc_builtin_macros/src/deriving/cmp/partial_ord.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use rustc_ast::{ExprKind, ItemKind, MetaItem, PatKind};
1+
use rustc_ast::{ExprKind, ItemKind, MetaItem, PatKind, Safety};
22
use rustc_expand::base::{Annotatable, ExtCtxt};
33
use rustc_span::{Ident, Span, sym};
44
use thin_vec::thin_vec;
@@ -64,6 +64,7 @@ pub(crate) fn expand_deriving_partial_ord(
6464
methods: vec![partial_cmp_def],
6565
associated_types: Vec::new(),
6666
is_const,
67+
safety: Safety::Default,
6768
};
6869
trait_def.expand(cx, mitem, item, push)
6970
}

compiler/rustc_builtin_macros/src/deriving/debug.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use rustc_ast::{self as ast, EnumDef, MetaItem};
1+
use rustc_ast::{self as ast, EnumDef, MetaItem, Safety};
22
use rustc_expand::base::{Annotatable, ExtCtxt};
33
use rustc_session::config::FmtDebug;
44
use rustc_span::{Ident, Span, Symbol, sym};
@@ -41,6 +41,7 @@ pub(crate) fn expand_deriving_debug(
4141
}],
4242
associated_types: Vec::new(),
4343
is_const,
44+
safety: Safety::Default,
4445
};
4546
trait_def.expand(cx, mitem, item, push)
4647
}

compiler/rustc_builtin_macros/src/deriving/default.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
use core::ops::ControlFlow;
22

3-
use rustc_ast as ast;
43
use rustc_ast::visit::visit_opt;
5-
use rustc_ast::{EnumDef, VariantData, attr};
4+
use rustc_ast::{self as ast, EnumDef, Safety, VariantData, attr};
65
use rustc_expand::base::{Annotatable, DummyResult, ExtCtxt};
76
use rustc_span::{ErrorGuaranteed, Ident, Span, kw, sym};
87
use smallvec::SmallVec;
@@ -51,6 +50,7 @@ pub(crate) fn expand_deriving_default(
5150
}],
5251
associated_types: Vec::new(),
5352
is_const,
53+
safety: Safety::Default,
5454
};
5555
trait_def.expand(cx, mitem, item, push)
5656
}

compiler/rustc_builtin_macros/src/deriving/generic/mod.rs

+5-2
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,7 @@ pub(crate) use SubstructureFields::*;
183183
use rustc_ast::ptr::P;
184184
use rustc_ast::{
185185
self as ast, AnonConst, BindingMode, ByRef, EnumDef, Expr, GenericArg, GenericParamKind,
186-
Generics, Mutability, PatKind, VariantData,
186+
Generics, Mutability, PatKind, Safety, VariantData,
187187
};
188188
use rustc_attr_parsing as attr;
189189
use rustc_expand::base::{Annotatable, ExtCtxt};
@@ -220,6 +220,9 @@ pub(crate) struct TraitDef<'a> {
220220
pub associated_types: Vec<(Ident, Ty)>,
221221

222222
pub is_const: bool,
223+
224+
/// The safety of the `impl`.
225+
pub safety: Safety,
223226
}
224227

225228
pub(crate) struct MethodDef<'a> {
@@ -788,7 +791,7 @@ impl<'a> TraitDef<'a> {
788791
Ident::empty(),
789792
attrs,
790793
ast::ItemKind::Impl(Box::new(ast::Impl {
791-
safety: ast::Safety::Default,
794+
safety: self.safety,
792795
polarity: ast::ImplPolarity::Positive,
793796
defaultness: ast::Defaultness::Final,
794797
constness: if self.is_const { ast::Const::Yes(DUMMY_SP) } else { ast::Const::No },

compiler/rustc_builtin_macros/src/deriving/hash.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use rustc_ast::{MetaItem, Mutability};
1+
use rustc_ast::{MetaItem, Mutability, Safety};
22
use rustc_expand::base::{Annotatable, ExtCtxt};
33
use rustc_span::{Span, sym};
44
use thin_vec::thin_vec;
@@ -41,6 +41,7 @@ pub(crate) fn expand_deriving_hash(
4141
}],
4242
associated_types: Vec::new(),
4343
is_const,
44+
safety: Safety::Default,
4445
};
4546

4647
hash_trait_def.expand(cx, mitem, item, push);

compiler/rustc_span/src/symbol.rs

+1
Original file line numberDiff line numberDiff line change
@@ -346,6 +346,7 @@ symbols! {
346346
ToString,
347347
TokenStream,
348348
Trait,
349+
TrivialClone,
349350
Try,
350351
TryCaptureGeneric,
351352
TryCapturePrintable,

library/alloc/src/boxed/convert.rs

+5-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
use core::any::Any;
2+
#[cfg(not(no_global_oom_handling))]
3+
use core::clone::TrivialClone;
24
use core::error::Error;
35
use core::mem;
46
use core::pin::Pin;
@@ -75,11 +77,13 @@ impl<T: Clone> BoxFromSlice<T> for Box<[T]> {
7577
}
7678

7779
#[cfg(not(no_global_oom_handling))]
78-
impl<T: Copy> BoxFromSlice<T> for Box<[T]> {
80+
impl<T: TrivialClone> BoxFromSlice<T> for Box<[T]> {
7981
#[inline]
8082
fn from_slice(slice: &[T]) -> Self {
8183
let len = slice.len();
8284
let buf = RawVec::with_capacity(len);
85+
// SAFETY: since `T` implements `TrivialClone`, this is sound and
86+
// equivalent to the above.
8387
unsafe {
8488
ptr::copy_nonoverlapping(slice.as_ptr(), buf.ptr(), len);
8589
buf.into_box(slice.len()).assume_init()

library/alloc/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,7 @@
147147
#![feature(std_internals)]
148148
#![feature(str_internals)]
149149
#![feature(temporary_niche_types)]
150+
#![feature(trivial_clone)]
150151
#![feature(trusted_fused)]
151152
#![feature(trusted_len)]
152153
#![feature(trusted_random_access)]

library/alloc/src/rc.rs

+6-3
Original file line numberDiff line numberDiff line change
@@ -244,7 +244,7 @@
244244
use core::any::Any;
245245
use core::cell::Cell;
246246
#[cfg(not(no_global_oom_handling))]
247-
use core::clone::CloneToUninit;
247+
use core::clone::{CloneToUninit, TrivialClone};
248248
use core::cmp::Ordering;
249249
use core::hash::{Hash, Hasher};
250250
use core::intrinsics::abort;
@@ -2143,7 +2143,8 @@ impl<T> Rc<[T]> {
21432143

21442144
/// Copy elements from slice into newly allocated `Rc<[T]>`
21452145
///
2146-
/// Unsafe because the caller must either take ownership or bind `T: Copy`
2146+
/// Unsafe because the caller must either take ownership, bind `T: Copy` or
2147+
/// bind `T: TrivialClone`.
21472148
#[cfg(not(no_global_oom_handling))]
21482149
unsafe fn copy_from_slice(v: &[T]) -> Rc<[T]> {
21492150
unsafe {
@@ -2233,9 +2234,11 @@ impl<T: Clone> RcFromSlice<T> for Rc<[T]> {
22332234
}
22342235

22352236
#[cfg(not(no_global_oom_handling))]
2236-
impl<T: Copy> RcFromSlice<T> for Rc<[T]> {
2237+
impl<T: TrivialClone> RcFromSlice<T> for Rc<[T]> {
22372238
#[inline]
22382239
fn from_slice(v: &[T]) -> Self {
2240+
// SAFETY: `T` implements `TrivialClone`, so this is sound and equivalent
2241+
// to the above.
22392242
unsafe { Rc::copy_from_slice(v) }
22402243
}
22412244
}

library/alloc/src/slice.rs

+6-2
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414

1515
use core::borrow::{Borrow, BorrowMut};
1616
#[cfg(not(no_global_oom_handling))]
17+
use core::clone::TrivialClone;
18+
#[cfg(not(no_global_oom_handling))]
1719
use core::cmp::Ordering::{self, Less};
1820
#[cfg(not(no_global_oom_handling))]
1921
use core::mem::{self, MaybeUninit};
@@ -88,6 +90,8 @@ use crate::vec::Vec;
8890
#[allow(unreachable_pub)] // cfg(test) pub above
8991
pub(crate) mod hack {
9092
use core::alloc::Allocator;
93+
#[cfg(not(no_global_oom_handling))]
94+
use core::clone::TrivialClone;
9195

9296
use crate::boxed::Box;
9397
use crate::vec::Vec;
@@ -156,7 +160,7 @@ pub(crate) mod hack {
156160
}
157161

158162
#[cfg(not(no_global_oom_handling))]
159-
impl<T: Copy> ConvertVec for T {
163+
impl<T: TrivialClone> ConvertVec for T {
160164
#[inline]
161165
fn to_vec<A: Allocator>(s: &[Self], alloc: A) -> Vec<Self, A> {
162166
let mut v = Vec::with_capacity_in(s.len(), alloc);
@@ -872,7 +876,7 @@ impl<T: Clone, A: Allocator> SpecCloneIntoVec<T, A> for [T] {
872876
}
873877

874878
#[cfg(not(no_global_oom_handling))]
875-
impl<T: Copy, A: Allocator> SpecCloneIntoVec<T, A> for [T] {
879+
impl<T: TrivialClone, A: Allocator> SpecCloneIntoVec<T, A> for [T] {
876880
fn clone_into(&self, target: &mut Vec<T, A>) {
877881
target.clear();
878882
target.extend_from_slice(self);

library/alloc/src/sync.rs

+7-2
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111
use core::any::Any;
1212
#[cfg(not(no_global_oom_handling))]
1313
use core::clone::CloneToUninit;
14+
#[cfg(not(no_global_oom_handling))]
15+
use core::clone::TrivialClone;
1416
use core::cmp::Ordering;
1517
use core::hash::{Hash, Hasher};
1618
use core::intrinsics::abort;
@@ -2044,7 +2046,8 @@ impl<T> Arc<[T]> {
20442046

20452047
/// Copy elements from slice into newly allocated `Arc<[T]>`
20462048
///
2047-
/// Unsafe because the caller must either take ownership or bind `T: Copy`.
2049+
/// Unsafe because the caller must either take ownership, bind `T: Copy` or
2050+
/// bind `T: TrivialClone`.
20482051
#[cfg(not(no_global_oom_handling))]
20492052
unsafe fn copy_from_slice(v: &[T]) -> Arc<[T]> {
20502053
unsafe {
@@ -2136,9 +2139,11 @@ impl<T: Clone> ArcFromSlice<T> for Arc<[T]> {
21362139
}
21372140

21382141
#[cfg(not(no_global_oom_handling))]
2139-
impl<T: Copy> ArcFromSlice<T> for Arc<[T]> {
2142+
impl<T: TrivialClone> ArcFromSlice<T> for Arc<[T]> {
21402143
#[inline]
21412144
fn from_slice(v: &[T]) -> Self {
2145+
// SAFETY: `T` implements `TrivialClone`, so this is sound and equivalent
2146+
// to the above.
21422147
unsafe { Arc::copy_from_slice(v) }
21432148
}
21442149
}

library/alloc/src/vec/mod.rs

+5-3
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,8 @@
5353
5454
#![stable(feature = "rust1", since = "1.0.0")]
5555

56+
#[cfg(not(no_global_oom_handling))]
57+
use core::clone::TrivialClone;
5658
#[cfg(not(no_global_oom_handling))]
5759
use core::cmp;
5860
use core::cmp::Ordering;
@@ -3225,7 +3227,7 @@ impl<T: Clone, A: Allocator> ExtendFromWithinSpec for Vec<T, A> {
32253227
}
32263228

32273229
#[cfg(not(no_global_oom_handling))]
3228-
impl<T: Copy, A: Allocator> ExtendFromWithinSpec for Vec<T, A> {
3230+
impl<T: TrivialClone, A: Allocator> ExtendFromWithinSpec for Vec<T, A> {
32293231
unsafe fn spec_extend_from_within(&mut self, src: Range<usize>) {
32303232
let count = src.len();
32313233
{
@@ -3238,8 +3240,8 @@ impl<T: Copy, A: Allocator> ExtendFromWithinSpec for Vec<T, A> {
32383240
// SAFETY:
32393241
// - Both pointers are created from unique slice references (`&mut [_]`)
32403242
// so they are valid and do not overlap.
3241-
// - Elements are :Copy so it's OK to copy them, without doing
3242-
// anything with the original values
3243+
// - Elements implement `TrivialClone` so this is equivalent to calling
3244+
// `clone` on every one of them.
32433245
// - `count` is equal to the len of `source`, so source is valid for
32443246
// `count` reads
32453247
// - `.reserve(count)` guarantees that `spare.len() >= count` so spare

0 commit comments

Comments
 (0)