Skip to content

Commit a74589f

Browse files
committed
Auto merge of #136482 - jieyouxu:rollup-ffa9eh8, r=jieyouxu
Rollup of 8 pull requests Successful merges: - #134807 (fix(rustdoc): always use a channel when linking to doc.rust-lang.org) - #134814 (Add `kl` and `widekl` target features, and the feature gate) - #135836 (bootstrap: only build `crt{begin,end}.o` when compiling to MUSL) - #136022 (Port ui/simd tests to use the intrinsic macro) - #136235 (Pretty print pattern type values with transmute if they don't satisfy their pattern) - #136309 (set rustc dylib on manually constructed rustc command) - #136392 (bootstrap: add wrapper macros for `feature = "tracing"`-gated `tracing` macros) - #136462 (mir_build: Simplify `lower_pattern_range_endpoint`) r? `@ghost` `@rustbot` modify labels: rollup
2 parents 534d79a + 74901e2 commit a74589f

File tree

89 files changed

+779
-486
lines changed

Some content is hidden

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

89 files changed

+779
-486
lines changed

compiler/rustc_const_eval/src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,8 @@ pub fn provide(providers: &mut Providers) {
5757
providers.check_validity_requirement = |tcx, (init_kind, param_env_and_ty)| {
5858
util::check_validity_requirement(tcx, init_kind, param_env_and_ty)
5959
};
60+
providers.hooks.validate_scalar_in_layout =
61+
|tcx, scalar, layout| util::validate_scalar_in_layout(tcx, scalar, layout);
6062
}
6163

6264
/// `rustc_driver::main` installs a handler that will set this to `true` if

compiler/rustc_const_eval/src/util/check_validity_requirement.rs

+40-12
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
use rustc_abi::{BackendRepr, FieldsShape, Scalar, Variants};
2-
use rustc_middle::bug;
2+
use rustc_middle::query::TyCtxtAt;
33
use rustc_middle::ty::layout::{
44
HasTyCtxt, LayoutCx, LayoutError, LayoutOf, TyAndLayout, ValidityRequirement,
55
};
6-
use rustc_middle::ty::{PseudoCanonicalInput, Ty, TyCtxt};
6+
use rustc_middle::ty::{PseudoCanonicalInput, ScalarInt, Ty, TyCtxt};
7+
use rustc_middle::{bug, span_bug, ty};
78

89
use crate::const_eval::{CanAccessMutGlobal, CheckAlignment, CompileTimeMachine};
910
use crate::interpret::{InterpCx, MemoryKind};
@@ -34,7 +35,7 @@ pub fn check_validity_requirement<'tcx>(
3435

3536
let layout_cx = LayoutCx::new(tcx, input.typing_env);
3637
if kind == ValidityRequirement::Uninit || tcx.sess.opts.unstable_opts.strict_init_checks {
37-
check_validity_requirement_strict(layout, &layout_cx, kind)
38+
Ok(check_validity_requirement_strict(layout, &layout_cx, kind))
3839
} else {
3940
check_validity_requirement_lax(layout, &layout_cx, kind)
4041
}
@@ -46,7 +47,7 @@ fn check_validity_requirement_strict<'tcx>(
4647
ty: TyAndLayout<'tcx>,
4748
cx: &LayoutCx<'tcx>,
4849
kind: ValidityRequirement,
49-
) -> Result<bool, &'tcx LayoutError<'tcx>> {
50+
) -> bool {
5051
let machine = CompileTimeMachine::new(CanAccessMutGlobal::No, CheckAlignment::Error);
5152

5253
let mut cx = InterpCx::new(cx.tcx(), rustc_span::DUMMY_SP, cx.typing_env, machine);
@@ -69,14 +70,13 @@ fn check_validity_requirement_strict<'tcx>(
6970
// due to this.
7071
// The value we are validating is temporary and discarded at the end of this function, so
7172
// there is no point in reseting provenance and padding.
72-
Ok(cx
73-
.validate_operand(
74-
&allocated.into(),
75-
/*recursive*/ false,
76-
/*reset_provenance_and_padding*/ false,
77-
)
78-
.discard_err()
79-
.is_some())
73+
cx.validate_operand(
74+
&allocated.into(),
75+
/*recursive*/ false,
76+
/*reset_provenance_and_padding*/ false,
77+
)
78+
.discard_err()
79+
.is_some()
8080
}
8181

8282
/// Implements the 'lax' (default) version of the [`check_validity_requirement`] checks; see that
@@ -168,3 +168,31 @@ fn check_validity_requirement_lax<'tcx>(
168168

169169
Ok(true)
170170
}
171+
172+
pub(crate) fn validate_scalar_in_layout<'tcx>(
173+
tcx: TyCtxtAt<'tcx>,
174+
scalar: ScalarInt,
175+
ty: Ty<'tcx>,
176+
) -> bool {
177+
let machine = CompileTimeMachine::new(CanAccessMutGlobal::No, CheckAlignment::Error);
178+
179+
let typing_env = ty::TypingEnv::fully_monomorphized();
180+
let mut cx = InterpCx::new(tcx.tcx, tcx.span, typing_env, machine);
181+
182+
let Ok(layout) = cx.layout_of(ty) else {
183+
span_bug!(tcx.span, "could not compute layout of {scalar:?}:{ty:?}")
184+
};
185+
let allocated = cx
186+
.allocate(layout, MemoryKind::Machine(crate::const_eval::MemoryKind::Heap))
187+
.expect("OOM: failed to allocate for uninit check");
188+
189+
cx.write_scalar(scalar, &allocated).unwrap();
190+
191+
cx.validate_operand(
192+
&allocated.into(),
193+
/*recursive*/ false,
194+
/*reset_provenance_and_padding*/ false,
195+
)
196+
.discard_err()
197+
.is_some()
198+
}

compiler/rustc_const_eval/src/util/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ mod type_name;
88

99
pub use self::alignment::{is_disaligned, is_within_packed};
1010
pub use self::check_validity_requirement::check_validity_requirement;
11+
pub(crate) use self::check_validity_requirement::validate_scalar_in_layout;
1112
pub use self::compare_types::{relate_types, sub_types};
1213
pub use self::type_name::type_name;
1314

compiler/rustc_feature/src/unstable.rs

+2
Original file line numberDiff line numberDiff line change
@@ -529,6 +529,8 @@ declare_features! (
529529
(unstable, inline_const_pat, "1.58.0", Some(76001)),
530530
/// Allows using `pointer` and `reference` in intra-doc links
531531
(unstable, intra_doc_pointers, "1.51.0", Some(80896)),
532+
// Allows using the `kl` and `widekl` target features and the associated intrinsics
533+
(unstable, keylocker_x86, "CURRENT_RUSTC_VERSION", Some(134813)),
532534
// Allows setting the threshold for the `large_assignments` lint.
533535
(unstable, large_assignments, "1.52.0", Some(83518)),
534536
/// Allow to have type alias types for inter-crate use.

compiler/rustc_middle/src/hooks/mod.rs

+4
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,10 @@ declare_hooks! {
9898
hook save_dep_graph() -> ();
9999

100100
hook query_key_hash_verify_all() -> ();
101+
102+
/// Ensure the given scalar is valid for the given type.
103+
/// This checks non-recursive runtime validity.
104+
hook validate_scalar_in_layout(scalar: crate::ty::ScalarInt, ty: Ty<'tcx>) -> bool;
101105
}
102106

103107
#[cold]

compiler/rustc_middle/src/ty/print/pretty.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1741,7 +1741,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
17411741
" as ",
17421742
)?;
17431743
}
1744-
ty::Pat(base_ty, pat) => {
1744+
ty::Pat(base_ty, pat) if self.tcx().validate_scalar_in_layout(int, ty) => {
17451745
self.pretty_print_const_scalar_int(int, *base_ty, print_ty)?;
17461746
p!(write(" is {pat:?}"));
17471747
}

compiler/rustc_mir_build/src/thir/pattern/mod.rs

+42-39
Original file line numberDiff line numberDiff line change
@@ -155,42 +155,41 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
155155
fn lower_pattern_range_endpoint(
156156
&mut self,
157157
expr: Option<&'tcx hir::PatExpr<'tcx>>,
158-
) -> Result<
159-
(Option<PatRangeBoundary<'tcx>>, Option<Ascription<'tcx>>, Option<LocalDefId>),
160-
ErrorGuaranteed,
161-
> {
162-
match expr {
163-
None => Ok((None, None, None)),
164-
Some(expr) => {
165-
let (kind, ascr, inline_const) = match self.lower_lit(expr) {
166-
PatKind::ExpandedConstant { subpattern, def_id, is_inline: true } => {
167-
(subpattern.kind, None, def_id.as_local())
168-
}
169-
PatKind::ExpandedConstant { subpattern, is_inline: false, .. } => {
170-
(subpattern.kind, None, None)
171-
}
172-
PatKind::AscribeUserType { ascription, subpattern: box Pat { kind, .. } } => {
173-
(kind, Some(ascription), None)
174-
}
175-
kind => (kind, None, None),
176-
};
177-
let value = match kind {
178-
PatKind::Constant { value } => value,
179-
PatKind::ExpandedConstant { subpattern, .. }
180-
if let PatKind::Constant { value } = subpattern.kind =>
181-
{
182-
value
183-
}
184-
_ => {
185-
let msg = format!(
186-
"found bad range pattern endpoint `{expr:?}` outside of error recovery"
187-
);
188-
return Err(self.tcx.dcx().span_delayed_bug(expr.span, msg));
158+
// Out-parameters collecting extra data to be reapplied by the caller
159+
ascriptions: &mut Vec<Ascription<'tcx>>,
160+
inline_consts: &mut Vec<LocalDefId>,
161+
) -> Result<Option<PatRangeBoundary<'tcx>>, ErrorGuaranteed> {
162+
let Some(expr) = expr else { return Ok(None) };
163+
164+
// Lower the endpoint into a temporary `PatKind` that will then be
165+
// deconstructed to obtain the constant value and other data.
166+
let mut kind: PatKind<'tcx> = self.lower_lit(expr);
167+
168+
// Unpeel any ascription or inline-const wrapper nodes.
169+
loop {
170+
match kind {
171+
PatKind::AscribeUserType { ascription, subpattern } => {
172+
ascriptions.push(ascription);
173+
kind = subpattern.kind;
174+
}
175+
PatKind::ExpandedConstant { is_inline, def_id, subpattern } => {
176+
if is_inline {
177+
inline_consts.extend(def_id.as_local());
189178
}
190-
};
191-
Ok((Some(PatRangeBoundary::Finite(value)), ascr, inline_const))
179+
kind = subpattern.kind;
180+
}
181+
_ => break,
192182
}
193183
}
184+
185+
// The unpeeled kind should now be a constant, giving us the endpoint value.
186+
let PatKind::Constant { value } = kind else {
187+
let msg =
188+
format!("found bad range pattern endpoint `{expr:?}` outside of error recovery");
189+
return Err(self.tcx.dcx().span_delayed_bug(expr.span, msg));
190+
};
191+
192+
Ok(Some(PatRangeBoundary::Finite(value)))
194193
}
195194

196195
/// Overflowing literals are linted against in a late pass. This is mostly fine, except when we
@@ -253,11 +252,15 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
253252
self.tcx.dcx().span_bug(span, msg);
254253
}
255254

256-
let (lo, lo_ascr, lo_inline) = self.lower_pattern_range_endpoint(lo_expr)?;
257-
let (hi, hi_ascr, hi_inline) = self.lower_pattern_range_endpoint(hi_expr)?;
255+
// Collect extra data while lowering the endpoints, to be reapplied later.
256+
let mut ascriptions = vec![];
257+
let mut inline_consts = vec![];
258+
259+
let mut lower_endpoint =
260+
|expr| self.lower_pattern_range_endpoint(expr, &mut ascriptions, &mut inline_consts);
258261

259-
let lo = lo.unwrap_or(PatRangeBoundary::NegInfinity);
260-
let hi = hi.unwrap_or(PatRangeBoundary::PosInfinity);
262+
let lo = lower_endpoint(lo_expr)?.unwrap_or(PatRangeBoundary::NegInfinity);
263+
let hi = lower_endpoint(hi_expr)?.unwrap_or(PatRangeBoundary::PosInfinity);
261264

262265
let cmp = lo.compare_with(hi, ty, self.tcx, self.typing_env);
263266
let mut kind = PatKind::Range(Box::new(PatRange { lo, hi, end, ty }));
@@ -298,13 +301,13 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
298301
// If we are handling a range with associated constants (e.g.
299302
// `Foo::<'a>::A..=Foo::B`), we need to put the ascriptions for the associated
300303
// constants somewhere. Have them on the range pattern.
301-
for ascription in [lo_ascr, hi_ascr].into_iter().flatten() {
304+
for ascription in ascriptions {
302305
kind = PatKind::AscribeUserType {
303306
ascription,
304307
subpattern: Box::new(Pat { span, ty, kind }),
305308
};
306309
}
307-
for def in [lo_inline, hi_inline].into_iter().flatten() {
310+
for def in inline_consts {
308311
kind = PatKind::ExpandedConstant {
309312
def_id: def.to_def_id(),
310313
is_inline: true,

compiler/rustc_span/src/symbol.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1148,6 +1148,7 @@ symbols! {
11481148
iterator,
11491149
iterator_collect_fn,
11501150
kcfi,
1151+
keylocker_x86,
11511152
keyword,
11521153
kind,
11531154
kreg,

compiler/rustc_target/src/target_features.rs

+2
Original file line numberDiff line numberDiff line change
@@ -409,6 +409,7 @@ const X86_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[
409409
("fma", Stable, &["avx"]),
410410
("fxsr", Stable, &[]),
411411
("gfni", Unstable(sym::avx512_target_feature), &["sse2"]),
412+
("kl", Unstable(sym::keylocker_x86), &["sse2"]),
412413
("lahfsahf", Unstable(sym::lahfsahf_target_feature), &[]),
413414
("lzcnt", Stable, &[]),
414415
("movbe", Stable, &[]),
@@ -433,6 +434,7 @@ const X86_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[
433434
("tbm", Unstable(sym::tbm_target_feature), &[]),
434435
("vaes", Unstable(sym::avx512_target_feature), &["avx2", "aes"]),
435436
("vpclmulqdq", Unstable(sym::avx512_target_feature), &["avx", "pclmulqdq"]),
437+
("widekl", Unstable(sym::keylocker_x86), &["kl"]),
436438
("x87", Unstable(sym::x87_target_feature), &[]),
437439
("xop", Unstable(sym::xop_target_feature), &[/*"fma4", */ "avx", "sse4a"]),
438440
("xsave", Stable, &[]),

src/bootstrap/src/bin/main.rs

+5-7
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,12 @@ use std::str::FromStr;
1111
use std::{env, process};
1212

1313
use bootstrap::{
14-
Build, CONFIG_CHANGE_HISTORY, Config, Flags, Subcommand, find_recent_config_change_ids,
14+
Build, CONFIG_CHANGE_HISTORY, Config, Flags, Subcommand, debug, find_recent_config_change_ids,
1515
human_readable_changes, t,
1616
};
1717
use build_helper::ci::CiEnv;
1818
#[cfg(feature = "tracing")]
19-
use tracing::{debug, instrument};
19+
use tracing::instrument;
2020

2121
#[cfg_attr(feature = "tracing", instrument(level = "trace", name = "main"))]
2222
fn main() {
@@ -29,10 +29,8 @@ fn main() {
2929
return;
3030
}
3131

32-
#[cfg(feature = "tracing")]
3332
debug!("parsing flags");
3433
let flags = Flags::parse(&args);
35-
#[cfg(feature = "tracing")]
3634
debug!("parsing config based on flags");
3735
let config = Config::parse(flags);
3836

@@ -95,7 +93,6 @@ fn main() {
9593
let dump_bootstrap_shims = config.dump_bootstrap_shims;
9694
let out_dir = config.out.clone();
9795

98-
#[cfg(feature = "tracing")]
9996
debug!("creating new build based on config");
10097
Build::new(config).build();
10198

@@ -207,8 +204,9 @@ fn check_version(config: &Config) -> Option<String> {
207204
// Due to the conditional compilation via the `tracing` cargo feature, this means that `tracing`
208205
// usages in bootstrap need to be also gated behind the `tracing` feature:
209206
//
210-
// - `tracing` macros (like `trace!`) and anything from `tracing`, `tracing_subscriber` and
211-
// `tracing-tree` will need to be gated by `#[cfg(feature = "tracing")]`.
207+
// - `tracing` macros with log levels (`trace!`, `debug!`, `warn!`, `info`, `error`) should not be
208+
// used *directly*. You should use the wrapped `tracing` macros which gate the actual invocations
209+
// behind `feature = "tracing"`.
212210
// - `tracing`'s `#[instrument(..)]` macro will need to be gated like `#![cfg_attr(feature =
213211
// "tracing", instrument(..))]`.
214212
#[cfg(feature = "tracing")]

src/bootstrap/src/core/build_steps/compile.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -339,7 +339,7 @@ fn copy_self_contained_objects(
339339
// to using gcc from a glibc-targeting toolchain for linking.
340340
// To do that we have to distribute musl startup objects as a part of Rust toolchain
341341
// and link with them manually in the self-contained mode.
342-
if target.contains("musl") && !target.contains("unikraft") {
342+
if target.needs_crt_begin_end() {
343343
let srcdir = builder.musl_libdir(target).unwrap_or_else(|| {
344344
panic!("Target {:?} does not have a \"musl-libdir\" key", target.triple)
345345
});

src/bootstrap/src/core/build_steps/llvm.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -1295,7 +1295,9 @@ impl Step for CrtBeginEnd {
12951295
}
12961296

12971297
fn make_run(run: RunConfig<'_>) {
1298-
run.builder.ensure(CrtBeginEnd { target: run.target });
1298+
if run.target.needs_crt_begin_end() {
1299+
run.builder.ensure(CrtBeginEnd { target: run.target });
1300+
}
12991301
}
13001302

13011303
/// Build crtbegin.o/crtend.o for musl target.

src/bootstrap/src/core/builder/cargo.rs

+5-1
Original file line numberDiff line numberDiff line change
@@ -659,14 +659,18 @@ impl Builder<'_> {
659659
// Build proc macros both for the host and the target unless proc-macros are not
660660
// supported by the target.
661661
if target != compiler.host && cmd_kind != Kind::Check {
662-
let error = command(self.rustc(compiler))
662+
let mut rustc_cmd = command(self.rustc(compiler));
663+
self.add_rustc_lib_path(compiler, &mut rustc_cmd);
664+
665+
let error = rustc_cmd
663666
.arg("--target")
664667
.arg(target.rustc_target_arg())
665668
.arg("--print=file-names")
666669
.arg("--crate-type=proc-macro")
667670
.arg("-")
668671
.run_capture(self)
669672
.stderr();
673+
670674
let not_supported = error
671675
.lines()
672676
.any(|line| line.contains("unsupported crate type `proc-macro`"));

src/bootstrap/src/core/config/config.rs

+4
Original file line numberDiff line numberDiff line change
@@ -575,6 +575,10 @@ impl TargetSelection {
575575
env::var("OSTYPE").is_ok_and(|v| v.to_lowercase().contains("cygwin"))
576576
}
577577

578+
pub fn needs_crt_begin_end(&self) -> bool {
579+
self.contains("musl") && !self.contains("unikraft")
580+
}
581+
578582
/// Path to the file defining the custom target, if any.
579583
pub fn filepath(&self) -> Option<&Path> {
580584
self.file.as_ref().map(Path::new)

0 commit comments

Comments
 (0)