Skip to content

Commit 14f2f41

Browse files
committed
Auto merge of rust-lang#129900 - matthiaskrgr:rollup-pj890v5, r=matthiaskrgr
Rollup of 8 pull requests Successful merges: - rust-lang#101339 (enable -Zrandomize-layout in debug CI builds ) - rust-lang#127021 (Add target support for RTEMS Arm) - rust-lang#127692 (Suggest `impl Trait` for References to Bare Trait in Function Header) - rust-lang#128701 (Don't Suggest Labeling `const` and `unsafe` Blocks ) - rust-lang#128871 (bypass linker configuration and cross target check for specific commands) - rust-lang#129624 (Adjust `memchr` pinning and run `cargo update`) - rust-lang#129706 (Rename dump of coroutine by-move-body to be more consistent, fix ICE in dump_mir) - rust-lang#129789 (rustdoc: use strategic boxing to shrink `clean::Item`) r? `@ghost` `@rustbot` modify labels: rollup
2 parents 6199b69 + 9b2775a commit 14f2f41

File tree

110 files changed

+2433
-689
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

110 files changed

+2433
-689
lines changed

Diff for: Cargo.lock

+166-152
Large diffs are not rendered by default.

Diff for: compiler/rustc/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -30,5 +30,6 @@ features = ['unprefixed_malloc_on_supported_platforms']
3030
jemalloc = ['dep:jemalloc-sys']
3131
llvm = ['rustc_driver_impl/llvm']
3232
max_level_info = ['rustc_driver_impl/max_level_info']
33+
rustc_randomized_layouts = ['rustc_driver_impl/rustc_randomized_layouts']
3334
rustc_use_parallel_compiler = ['rustc_driver_impl/rustc_use_parallel_compiler']
3435
# tidy-alphabetical-end

Diff for: compiler/rustc_abi/src/layout.rs

+7-4
Original file line numberDiff line numberDiff line change
@@ -968,8 +968,8 @@ fn univariant<
968968
let mut align = if pack.is_some() { dl.i8_align } else { dl.aggregate_align };
969969
let mut max_repr_align = repr.align;
970970
let mut inverse_memory_index: IndexVec<u32, FieldIdx> = fields.indices().collect();
971-
let optimize = !repr.inhibit_struct_field_reordering();
972-
if optimize && fields.len() > 1 {
971+
let optimize_field_order = !repr.inhibit_struct_field_reordering();
972+
if optimize_field_order && fields.len() > 1 {
973973
let end = if let StructKind::MaybeUnsized = kind { fields.len() - 1 } else { fields.len() };
974974
let optimizing = &mut inverse_memory_index.raw[..end];
975975
let fields_excluding_tail = &fields.raw[..end];
@@ -1176,7 +1176,7 @@ fn univariant<
11761176
// If field 5 has offset 0, offsets[0] is 5, and memory_index[5] should be 0.
11771177
// Field 5 would be the first element, so memory_index is i:
11781178
// Note: if we didn't optimize, it's already right.
1179-
let memory_index = if optimize {
1179+
let memory_index = if optimize_field_order {
11801180
inverse_memory_index.invert_bijective_mapping()
11811181
} else {
11821182
debug_assert!(inverse_memory_index.iter().copied().eq(fields.indices()));
@@ -1189,6 +1189,9 @@ fn univariant<
11891189
}
11901190
let mut layout_of_single_non_zst_field = None;
11911191
let mut abi = Abi::Aggregate { sized };
1192+
1193+
let optimize_abi = !repr.inhibit_newtype_abi_optimization();
1194+
11921195
// Try to make this a Scalar/ScalarPair.
11931196
if sized && size.bytes() > 0 {
11941197
// We skip *all* ZST here and later check if we are good in terms of alignment.
@@ -1205,7 +1208,7 @@ fn univariant<
12051208
match field.abi {
12061209
// For plain scalars, or vectors of them, we can't unpack
12071210
// newtypes for `#[repr(C)]`, as that affects C ABIs.
1208-
Abi::Scalar(_) | Abi::Vector { .. } if optimize => {
1211+
Abi::Scalar(_) | Abi::Vector { .. } if optimize_abi => {
12091212
abi = field.abi;
12101213
}
12111214
// But scalar pairs are Rust-specific and get

Diff for: compiler/rustc_abi/src/lib.rs

+11-4
Original file line numberDiff line numberDiff line change
@@ -43,14 +43,17 @@ bitflags! {
4343
const IS_SIMD = 1 << 1;
4444
const IS_TRANSPARENT = 1 << 2;
4545
// Internal only for now. If true, don't reorder fields.
46+
// On its own it does not prevent ABI optimizations.
4647
const IS_LINEAR = 1 << 3;
47-
// If true, the type's layout can be randomized using
48-
// the seed stored in `ReprOptions.field_shuffle_seed`
48+
// If true, the type's crate has opted into layout randomization.
49+
// Other flags can still inhibit reordering and thus randomization.
50+
// The seed stored in `ReprOptions.field_shuffle_seed`.
4951
const RANDOMIZE_LAYOUT = 1 << 4;
5052
// Any of these flags being set prevent field reordering optimisation.
51-
const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits()
53+
const FIELD_ORDER_UNOPTIMIZABLE = ReprFlags::IS_C.bits()
5254
| ReprFlags::IS_SIMD.bits()
5355
| ReprFlags::IS_LINEAR.bits();
56+
const ABI_UNOPTIMIZABLE = ReprFlags::IS_C.bits() | ReprFlags::IS_SIMD.bits();
5457
}
5558
}
5659

@@ -139,10 +142,14 @@ impl ReprOptions {
139142
self.c() || self.int.is_some()
140143
}
141144

145+
pub fn inhibit_newtype_abi_optimization(&self) -> bool {
146+
self.flags.intersects(ReprFlags::ABI_UNOPTIMIZABLE)
147+
}
148+
142149
/// Returns `true` if this `#[repr()]` guarantees a fixed field order,
143150
/// e.g. `repr(C)` or `repr(<int>)`.
144151
pub fn inhibit_struct_field_reordering(&self) -> bool {
145-
self.flags.intersects(ReprFlags::IS_UNOPTIMISABLE) || self.int.is_some()
152+
self.flags.intersects(ReprFlags::FIELD_ORDER_UNOPTIMIZABLE) || self.int.is_some()
146153
}
147154

148155
/// Returns `true` if this type is valid for reordering and `-Z randomize-layout`

Diff for: compiler/rustc_ast/Cargo.toml

+1-2
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,9 @@ version = "0.0.0"
44
edition = "2021"
55

66
[dependencies]
7-
# FIXME: bumping memchr to 2.7.1 causes linker errors in MSVC thin-lto
87
# tidy-alphabetical-start
98
bitflags = "2.4.1"
10-
memchr = "=2.5.0"
9+
memchr = "2.7.4"
1110
rustc_ast_ir = { path = "../rustc_ast_ir" }
1211
rustc_data_structures = { path = "../rustc_data_structures" }
1312
rustc_index = { path = "../rustc_index" }

Diff for: compiler/rustc_driver_impl/Cargo.toml

+5
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ rustc_hir_analysis = { path = "../rustc_hir_analysis" }
2323
rustc_hir_pretty = { path = "../rustc_hir_pretty" }
2424
rustc_hir_typeck = { path = "../rustc_hir_typeck" }
2525
rustc_incremental = { path = "../rustc_incremental" }
26+
rustc_index = { path = "../rustc_index" }
2627
rustc_infer = { path = "../rustc_infer" }
2728
rustc_interface = { path = "../rustc_interface" }
2829
rustc_lint = { path = "../rustc_lint" }
@@ -72,6 +73,10 @@ ctrlc = "3.4.4"
7273
# tidy-alphabetical-start
7374
llvm = ['rustc_interface/llvm']
7475
max_level_info = ['rustc_log/max_level_info']
76+
rustc_randomized_layouts = [
77+
'rustc_index/rustc_randomized_layouts',
78+
'rustc_middle/rustc_randomized_layouts'
79+
]
7580
rustc_use_parallel_compiler = [
7681
'rustc_data_structures/rustc_use_parallel_compiler',
7782
'rustc_interface/rustc_use_parallel_compiler',

Diff for: compiler/rustc_hir_analysis/src/hir_ty_lowering/lint.rs

+55-23
Original file line numberDiff line numberDiff line change
@@ -133,9 +133,6 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
133133
return;
134134
};
135135
let sugg = self.add_generic_param_suggestion(generics, self_ty.span, &impl_trait_name);
136-
if sugg.is_empty() {
137-
return;
138-
};
139136
diag.multipart_suggestion(
140137
format!(
141138
"alternatively use a blanket implementation to implement `{of_trait_name}` for \
@@ -170,6 +167,10 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
170167
let parent_id = tcx.hir().get_parent_item(self_ty.hir_id).def_id;
171168
// FIXME: If `type_alias_impl_trait` is enabled, also look for `Trait0<Ty = Trait1>`
172169
// and suggest `Trait0<Ty = impl Trait1>`.
170+
// Functions are found in three different contexts.
171+
// 1. Independent functions
172+
// 2. Functions inside trait blocks
173+
// 3. Functions inside impl blocks
173174
let (sig, generics, owner) = match tcx.hir_node_by_def_id(parent_id) {
174175
hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, generics, _), .. }) => {
175176
(sig, generics, None)
@@ -180,13 +181,21 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
180181
owner_id,
181182
..
182183
}) => (sig, generics, Some(tcx.parent(owner_id.to_def_id()))),
184+
hir::Node::ImplItem(hir::ImplItem {
185+
kind: hir::ImplItemKind::Fn(sig, _),
186+
generics,
187+
owner_id,
188+
..
189+
}) => (sig, generics, Some(tcx.parent(owner_id.to_def_id()))),
183190
_ => return false,
184191
};
185192
let Ok(trait_name) = tcx.sess.source_map().span_to_snippet(self_ty.span) else {
186193
return false;
187194
};
188195
let impl_sugg = vec![(self_ty.span.shrink_to_lo(), "impl ".to_string())];
189196
let mut is_downgradable = true;
197+
198+
// Check if trait object is safe for suggesting dynamic dispatch.
190199
let is_object_safe = match self_ty.kind {
191200
hir::TyKind::TraitObject(objects, ..) => {
192201
objects.iter().all(|(o, _)| match o.trait_ref.path.res {
@@ -202,8 +211,15 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
202211
}
203212
_ => false,
204213
};
214+
215+
let borrowed = matches!(
216+
tcx.parent_hir_node(self_ty.hir_id),
217+
hir::Node::Ty(hir::Ty { kind: hir::TyKind::Ref(..), .. })
218+
);
219+
220+
// Suggestions for function return type.
205221
if let hir::FnRetTy::Return(ty) = sig.decl.output
206-
&& ty.hir_id == self_ty.hir_id
222+
&& ty.peel_refs().hir_id == self_ty.hir_id
207223
{
208224
let pre = if !is_object_safe {
209225
format!("`{trait_name}` is not object safe, ")
@@ -214,14 +230,26 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
214230
"{pre}use `impl {trait_name}` to return an opaque type, as long as you return a \
215231
single underlying type",
216232
);
233+
217234
diag.multipart_suggestion_verbose(msg, impl_sugg, Applicability::MachineApplicable);
235+
236+
// Suggest `Box<dyn Trait>` for return type
218237
if is_object_safe {
219-
diag.multipart_suggestion_verbose(
220-
"alternatively, you can return an owned trait object",
238+
// If the return type is `&Trait`, we don't want
239+
// the ampersand to be displayed in the `Box<dyn Trait>`
240+
// suggestion.
241+
let suggestion = if borrowed {
242+
vec![(ty.span, format!("Box<dyn {trait_name}>"))]
243+
} else {
221244
vec![
222245
(ty.span.shrink_to_lo(), "Box<dyn ".to_string()),
223246
(ty.span.shrink_to_hi(), ">".to_string()),
224-
],
247+
]
248+
};
249+
250+
diag.multipart_suggestion_verbose(
251+
"alternatively, you can return an owned trait object",
252+
suggestion,
225253
Applicability::MachineApplicable,
226254
);
227255
} else if is_downgradable {
@@ -230,39 +258,43 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
230258
}
231259
return true;
232260
}
261+
262+
// Suggestions for function parameters.
233263
for ty in sig.decl.inputs {
234-
if ty.hir_id != self_ty.hir_id {
264+
if ty.peel_refs().hir_id != self_ty.hir_id {
235265
continue;
236266
}
237267
let sugg = self.add_generic_param_suggestion(generics, self_ty.span, &trait_name);
238-
if !sugg.is_empty() {
239-
diag.multipart_suggestion_verbose(
240-
format!("use a new generic type parameter, constrained by `{trait_name}`"),
241-
sugg,
242-
Applicability::MachineApplicable,
243-
);
244-
diag.multipart_suggestion_verbose(
245-
"you can also use an opaque type, but users won't be able to specify the type \
246-
parameter when calling the `fn`, having to rely exclusively on type inference",
247-
impl_sugg,
248-
Applicability::MachineApplicable,
249-
);
250-
}
268+
diag.multipart_suggestion_verbose(
269+
format!("use a new generic type parameter, constrained by `{trait_name}`"),
270+
sugg,
271+
Applicability::MachineApplicable,
272+
);
273+
diag.multipart_suggestion_verbose(
274+
"you can also use an opaque type, but users won't be able to specify the type \
275+
parameter when calling the `fn`, having to rely exclusively on type inference",
276+
impl_sugg,
277+
Applicability::MachineApplicable,
278+
);
251279
if !is_object_safe {
252280
diag.note(format!("`{trait_name}` it is not object safe, so it can't be `dyn`"));
253281
if is_downgradable {
254282
// We'll emit the object safety error already, with a structured suggestion.
255283
diag.downgrade_to_delayed_bug();
256284
}
257285
} else {
286+
// No ampersand in suggestion if it's borrowed already
287+
let (dyn_str, paren_dyn_str) =
288+
if borrowed { ("dyn ", "(dyn ") } else { ("&dyn ", "&(dyn ") };
289+
258290
let sugg = if let hir::TyKind::TraitObject([_, _, ..], _, _) = self_ty.kind {
259291
// There are more than one trait bound, we need surrounding parentheses.
260292
vec![
261-
(self_ty.span.shrink_to_lo(), "&(dyn ".to_string()),
293+
(self_ty.span.shrink_to_lo(), paren_dyn_str.to_string()),
262294
(self_ty.span.shrink_to_hi(), ")".to_string()),
263295
]
264296
} else {
265-
vec![(self_ty.span.shrink_to_lo(), "&dyn ".to_string())]
297+
vec![(self_ty.span.shrink_to_lo(), dyn_str.to_string())]
266298
};
267299
diag.multipart_suggestion_verbose(
268300
format!(

Diff for: compiler/rustc_index/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -20,4 +20,5 @@ nightly = [
2020
"dep:rustc_macros",
2121
"rustc_index_macros/nightly",
2222
]
23+
rustc_randomized_layouts = []
2324
# tidy-alphabetical-end

Diff for: compiler/rustc_index/src/lib.rs

+11
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,19 @@ pub use vec::IndexVec;
3333
///
3434
/// </div>
3535
#[macro_export]
36+
#[cfg(not(feature = "rustc_randomized_layouts"))]
3637
macro_rules! static_assert_size {
3738
($ty:ty, $size:expr) => {
3839
const _: [(); $size] = [(); ::std::mem::size_of::<$ty>()];
3940
};
4041
}
42+
43+
#[macro_export]
44+
#[cfg(feature = "rustc_randomized_layouts")]
45+
macro_rules! static_assert_size {
46+
($ty:ty, $size:expr) => {
47+
// no effect other than using the statements.
48+
// struct sizes are not deterministic under randomized layouts
49+
const _: (usize, usize) = ($size, ::std::mem::size_of::<$ty>());
50+
};
51+
}

Diff for: compiler/rustc_middle/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -40,5 +40,6 @@ tracing = "0.1"
4040

4141
[features]
4242
# tidy-alphabetical-start
43+
rustc_randomized_layouts = []
4344
rustc_use_parallel_compiler = ["dep:rustc-rayon-core"]
4445
# tidy-alphabetical-end

Diff for: compiler/rustc_middle/src/mir/pretty.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -612,7 +612,9 @@ fn write_mir_sig(tcx: TyCtxt<'_>, body: &Body<'_>, w: &mut dyn io::Write) -> io:
612612
let def_id = body.source.def_id();
613613
let kind = tcx.def_kind(def_id);
614614
let is_function = match kind {
615-
DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..) => true,
615+
DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..) | DefKind::SyntheticCoroutineBody => {
616+
true
617+
}
616618
_ => tcx.is_closure_like(def_id),
617619
};
618620
match (kind, body.source.promoted) {

Diff for: compiler/rustc_middle/src/query/plumbing.rs

+1
Original file line numberDiff line numberDiff line change
@@ -337,6 +337,7 @@ macro_rules! define_callbacks {
337337
// Ensure that values grow no larger than 64 bytes by accident.
338338
// Increase this limit if necessary, but do try to keep the size low if possible
339339
#[cfg(target_pointer_width = "64")]
340+
#[cfg(not(feature = "rustc_randomized_layouts"))]
340341
const _: () = {
341342
if mem::size_of::<Value<'static>>() > 64 {
342343
panic!("{}", concat!(

Diff for: compiler/rustc_middle/src/ty/mod.rs

+9-1
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ use rustc_data_structures::tagged_ptr::CopyTaggedPtr;
3535
use rustc_errors::{Diag, ErrorGuaranteed, StashKey};
3636
use rustc_hir::def::{CtorKind, CtorOf, DefKind, DocLinkResMap, LifetimeRes, Res};
3737
use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, LocalDefIdMap};
38+
use rustc_hir::LangItem;
3839
use rustc_index::IndexVec;
3940
use rustc_macros::{
4041
extension, Decodable, Encodable, HashStable, TyDecodable, TyEncodable, TypeFoldable,
@@ -1570,8 +1571,15 @@ impl<'tcx> TyCtxt<'tcx> {
15701571
flags.insert(ReprFlags::RANDOMIZE_LAYOUT);
15711572
}
15721573

1574+
// box is special, on the one hand the compiler assumes an ordered layout, with the pointer
1575+
// always at offset zero. On the other hand we want scalar abi optimizations.
1576+
let is_box = self.is_lang_item(did.to_def_id(), LangItem::OwnedBox);
1577+
15731578
// This is here instead of layout because the choice must make it into metadata.
1574-
if !self.consider_optimizing(|| format!("Reorder fields of {:?}", self.def_path_str(did))) {
1579+
if is_box
1580+
|| !self
1581+
.consider_optimizing(|| format!("Reorder fields of {:?}", self.def_path_str(did)))
1582+
{
15751583
flags.insert(ReprFlags::IS_LINEAR);
15761584
}
15771585

Diff for: compiler/rustc_mir_transform/src/coroutine/by_move_body.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -207,11 +207,12 @@ pub fn coroutine_by_move_body_def_id<'tcx>(
207207

208208
let mut by_move_body = body.clone();
209209
MakeByMoveBody { tcx, field_remapping, by_move_coroutine_ty }.visit_body(&mut by_move_body);
210-
dump_mir(tcx, false, "coroutine_by_move", &0, &by_move_body, |_, _| Ok(()));
211210

212-
let body_def = tcx.create_def(coroutine_def_id, kw::Empty, DefKind::SyntheticCoroutineBody);
211+
// This will always be `{closure#1}`, since the original coroutine is `{closure#0}`.
212+
let body_def = tcx.create_def(parent_def_id, kw::Empty, DefKind::SyntheticCoroutineBody);
213213
by_move_body.source =
214214
mir::MirSource::from_instance(InstanceKind::Item(body_def.def_id().to_def_id()));
215+
dump_mir(tcx, false, "built", &"after", &by_move_body, |_, _| Ok(()));
215216

216217
// Inherited from the by-ref coroutine.
217218
body_def.codegen_fn_attrs(tcx.codegen_fn_attrs(coroutine_def_id).clone());

0 commit comments

Comments
 (0)