Skip to content

Commit

Permalink
Auto merge of #94062 - Mark-Simulacrum:drop-print-cfg, r=oli-obk
Browse files Browse the repository at this point in the history
Move ty::print methods to Drop-based scope guards

Primary goal is reducing codegen of the TLS access for each closure, which shaves ~3 seconds of bootstrap time over rustc as a whole.
  • Loading branch information
bors committed Feb 20, 2022
2 parents c1aa854 + 9763486 commit 523a1b1
Show file tree
Hide file tree
Showing 30 changed files with 140 additions and 140 deletions.
36 changes: 21 additions & 15 deletions compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs
Expand Up @@ -779,29 +779,35 @@ pub(crate) fn codegen_intrinsic_call<'tcx>(
assert_inhabited | assert_zero_valid | assert_uninit_valid, <T> () {
let layout = fx.layout_of(T);
if layout.abi.is_uninhabited() {
with_no_trimmed_paths(|| crate::base::codegen_panic(
fx,
&format!("attempted to instantiate uninhabited type `{}`", T),
span,
));
with_no_trimmed_paths!({
crate::base::codegen_panic(
fx,
&format!("attempted to instantiate uninhabited type `{}`", T),
span,
)
});
return;
}

if intrinsic == sym::assert_zero_valid && !layout.might_permit_raw_init(fx, /*zero:*/ true) {
with_no_trimmed_paths(|| crate::base::codegen_panic(
fx,
&format!("attempted to zero-initialize type `{}`, which is invalid", T),
span,
));
with_no_trimmed_paths!({
crate::base::codegen_panic(
fx,
&format!("attempted to zero-initialize type `{}`, which is invalid", T),
span,
);
});
return;
}

if intrinsic == sym::assert_uninit_valid && !layout.might_permit_raw_init(fx, /*zero:*/ false) {
with_no_trimmed_paths(|| crate::base::codegen_panic(
fx,
&format!("attempted to leave type `{}` uninitialized, which is invalid", T),
span,
));
with_no_trimmed_paths!({
crate::base::codegen_panic(
fx,
&format!("attempted to leave type `{}` uninitialized, which is invalid", T),
span,
)
});
return;
}
};
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_gcc/src/type_of.rs
Expand Up @@ -52,7 +52,7 @@ pub fn uncached_gcc_type<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, layout: TyAndLa
ty::Adt(..) | ty::Closure(..) | ty::Foreign(..) | ty::Generator(..) | ty::Str
if !cx.sess().fewer_names() =>
{
let mut name = with_no_trimmed_paths(|| layout.ty.to_string());
let mut name = with_no_trimmed_paths!(layout.ty.to_string());
if let (&ty::Adt(def, _), &Variants::Single { index }) =
(layout.ty.kind(), &layout.variants)
{
Expand Down
3 changes: 1 addition & 2 deletions compiler/rustc_codegen_llvm/src/type_of.rs
Expand Up @@ -43,8 +43,7 @@ fn uncached_llvm_type<'a, 'tcx>(
// in problematically distinct types due to HRTB and subtyping (see #47638).
// ty::Dynamic(..) |
ty::Adt(..) | ty::Closure(..) | ty::Foreign(..) | ty::Generator(..) | ty::Str => {
let mut name =
with_no_visible_paths(|| with_no_trimmed_paths(|| layout.ty.to_string()));
let mut name = with_no_visible_paths!(with_no_trimmed_paths!(layout.ty.to_string()));
if let (&ty::Adt(def, _), &Variants::Single { index }) =
(layout.ty.kind(), &layout.variants)
{
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_codegen_ssa/src/mir/block.rs
Expand Up @@ -549,8 +549,8 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
UninitValid => !layout.might_permit_raw_init(bx, /*zero:*/ false),
};
if do_panic {
let msg_str = with_no_visible_paths(|| {
with_no_trimmed_paths(|| {
let msg_str = with_no_visible_paths!({
with_no_trimmed_paths!({
if layout.abi.is_uninhabited() {
// Use this error even for the other intrinsics as it is more precise.
format!("attempted to instantiate uninhabited type `{}`", ty)
Expand Down
6 changes: 3 additions & 3 deletions compiler/rustc_const_eval/src/const_eval/eval_queries.rs
Expand Up @@ -53,7 +53,7 @@ fn eval_body_using_ecx<'mir, 'tcx>(

trace!(
"eval_body_using_ecx: pushing stack frame for global: {}{}",
with_no_trimmed_paths(|| ty::tls::with(|tcx| tcx.def_path_str(cid.instance.def_id()))),
with_no_trimmed_paths!(ty::tls::with(|tcx| tcx.def_path_str(cid.instance.def_id()))),
cid.promoted.map_or_else(String::new, |p| format!("::promoted[{:?}]", p))
);

Expand Down Expand Up @@ -274,7 +274,7 @@ pub fn eval_to_allocation_raw_provider<'tcx>(
// The next two lines concatenated contain some discussion:
// https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/
// subject/anon_const_instance_printing/near/135980032
let instance = with_no_trimmed_paths(|| key.value.instance.to_string());
let instance = with_no_trimmed_paths!(key.value.instance.to_string());
trace!("const eval: {:?} ({})", key, instance);
}

Expand Down Expand Up @@ -317,7 +317,7 @@ pub fn eval_to_allocation_raw_provider<'tcx>(
// the expression, leading to the const eval error.
let instance = &key.value.instance;
if !instance.substs.is_empty() {
let instance = with_no_trimmed_paths(|| instance.to_string());
let instance = with_no_trimmed_paths!(instance.to_string());
let msg = format!("evaluation of `{}` failed", instance);
Cow::from(msg)
} else {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_const_eval/src/interpret/validity.rs
Expand Up @@ -33,7 +33,7 @@ macro_rules! throw_validation_failure {
msg.push_str(", but expected ");
write!(&mut msg, $($expected_fmt),+).unwrap();
)?
let path = rustc_middle::ty::print::with_no_trimmed_paths(|| {
let path = rustc_middle::ty::print::with_no_trimmed_paths!({
let where_ = &$where;
if !where_.is_empty() {
let mut path = String::new();
Expand Down
7 changes: 4 additions & 3 deletions compiler/rustc_const_eval/src/transform/check_consts/ops.rs
Expand Up @@ -108,9 +108,10 @@ impl<'tcx> NonConstOp<'tcx> for FnCallNonConst<'tcx> {
.as_ref()
.and_then(|node| node.generics())
{
let constraint = with_no_trimmed_paths(|| {
format!("~const {}", trait_ref.print_only_trait_path())
});
let constraint = with_no_trimmed_paths!(format!(
"~const {}",
trait_ref.print_only_trait_path()
));
suggest_constraining_type_param(
tcx,
generics,
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_lint/src/builtin.rs
Expand Up @@ -2634,7 +2634,7 @@ impl<'tcx> LateLintPass<'tcx> for InvalidValue {
// We are extremely conservative with what we warn about.
let conjured_ty = cx.typeck_results().expr_ty(expr);
if let Some((msg, span)) =
with_no_trimmed_paths(|| ty_find_init_error(cx.tcx, conjured_ty, init))
with_no_trimmed_paths!(ty_find_init_error(cx.tcx, conjured_ty, init))
{
cx.struct_span_lint(INVALID_VALUE, expr.span, |lint| {
let mut err = lint.build(&format!(
Expand Down
12 changes: 6 additions & 6 deletions compiler/rustc_lint/src/context.rs
Expand Up @@ -993,7 +993,7 @@ impl<'tcx> LateContext<'tcx> {
}

// This shouldn't ever be needed, but just in case:
with_no_trimmed_paths(|| {
with_no_trimmed_paths!({
Ok(vec![match trait_ref {
Some(trait_ref) => Symbol::intern(&format!("{:?}", trait_ref)),
None => Symbol::intern(&format!("<{}>", self_ty)),
Expand All @@ -1012,15 +1012,15 @@ impl<'tcx> LateContext<'tcx> {

// This shouldn't ever be needed, but just in case:
path.push(match trait_ref {
Some(trait_ref) => with_no_trimmed_paths(|| {
Symbol::intern(&format!(
Some(trait_ref) => {
with_no_trimmed_paths!(Symbol::intern(&format!(
"<impl {} for {}>",
trait_ref.print_only_trait_path(),
self_ty
))
}),
)))
}
None => {
with_no_trimmed_paths(|| Symbol::intern(&format!("<impl {}>", self_ty)))
with_no_trimmed_paths!(Symbol::intern(&format!("<impl {}>", self_ty)))
}
});

Expand Down
4 changes: 3 additions & 1 deletion compiler/rustc_macros/src/query.rs
Expand Up @@ -434,7 +434,9 @@ fn add_query_description_impl(
#[allow(unused_variables)]
fn describe(tcx: QueryCtxt<$tcx>, key: Self::Key) -> String {
let (#tcx, #key) = (*tcx, key);
::rustc_middle::ty::print::with_no_trimmed_paths(|| format!(#desc).into())
::rustc_middle::ty::print::with_no_trimmed_paths!(
format!(#desc)
)
}
};

Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_middle/src/lib.rs
Expand Up @@ -55,6 +55,7 @@
#![feature(try_reserve_kind)]
#![feature(nonzero_ops)]
#![feature(unwrap_infallible)]
#![feature(decl_macro)]
#![recursion_limit = "512"]
#![cfg_attr(not(bootstrap), allow(rustc::potential_query_instability))]

Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_middle/src/middle/stability.rs
Expand Up @@ -367,7 +367,7 @@ impl<'tcx> TyCtxt<'tcx> {
let is_in_effect = deprecation_in_effect(depr_attr);
let lint = deprecation_lint(is_in_effect);
if self.lint_level_at_node(lint, id).0 != Level::Allow {
let def_path = &with_no_trimmed_paths(|| self.def_path_str(def_id));
let def_path = with_no_trimmed_paths!(self.def_path_str(def_id));
let def_kind = self.def_kind(def_id).descr(def_id);

late_report_deprecation(
Expand All @@ -377,7 +377,7 @@ impl<'tcx> TyCtxt<'tcx> {
depr_attr.since,
depr_attr.note,
def_kind,
def_path,
&def_path,
),
depr_attr.suggestion,
lint,
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/mir/interpret/mod.rs
Expand Up @@ -147,7 +147,7 @@ pub struct GlobalId<'tcx> {

impl<'tcx> GlobalId<'tcx> {
pub fn display(self, tcx: TyCtxt<'tcx>) -> String {
let instance_name = with_no_trimmed_paths(|| tcx.def_path_str(self.instance.def.def_id()));
let instance_name = with_no_trimmed_paths!(tcx.def_path_str(self.instance.def.def_id()));
if let Some(promoted) = self.promoted {
format!("{}::{:?}", instance_name, promoted)
} else {
Expand Down
19 changes: 8 additions & 11 deletions compiler/rustc_middle/src/mir/pretty.rs
Expand Up @@ -92,10 +92,8 @@ pub fn dump_enabled<'tcx>(tcx: TyCtxt<'tcx>, pass_name: &str, def_id: DefId) ->
let Some(ref filters) = tcx.sess.opts.debugging_opts.dump_mir else {
return false;
};
let node_path = ty::print::with_forced_impl_filename_line(|| {
// see notes on #41697 below
tcx.def_path_str(def_id)
});
// see notes on #41697 below
let node_path = ty::print::with_forced_impl_filename_line!(tcx.def_path_str(def_id));
filters.split('|').any(|or_filter| {
or_filter.split('&').all(|and_filter| {
let and_filter_trimmed = and_filter.trim();
Expand Down Expand Up @@ -123,10 +121,9 @@ fn dump_matched_mir_node<'tcx, F>(
let _: io::Result<()> = try {
let mut file =
create_dump_file(tcx, "mir", pass_num, pass_name, disambiguator, body.source)?;
let def_path = ty::print::with_forced_impl_filename_line(|| {
// see notes on #41697 above
tcx.def_path_str(body.source.def_id())
});
// see notes on #41697 above
let def_path =
ty::print::with_forced_impl_filename_line!(tcx.def_path_str(body.source.def_id()));
write!(file, "// MIR for `{}", def_path)?;
match body.source.promoted {
None => write!(file, "`")?,
Expand Down Expand Up @@ -969,10 +966,10 @@ fn write_mir_sig(tcx: TyCtxt<'_>, body: &Body<'_>, w: &mut dyn Write) -> io::Res
_ => bug!("Unexpected def kind {:?}", kind),
}

ty::print::with_forced_impl_filename_line(|| {
ty::print::with_forced_impl_filename_line! {
// see notes on #41697 elsewhere
write!(w, "{}", tcx.def_path_str(def_id))
})?;
write!(w, "{}", tcx.def_path_str(def_id))?
}

if body.source.promoted.is_none() && is_function {
write!(w, "(")?;
Expand Down
109 changes: 51 additions & 58 deletions compiler/rustc_middle/src/ty/print/pretty.rs
Expand Up @@ -63,66 +63,59 @@ thread_local! {
static NO_VISIBLE_PATH: Cell<bool> = const { Cell::new(false) };
}

/// Avoids running any queries during any prints that occur
/// during the closure. This may alter the appearance of some
/// types (e.g. forcing verbose printing for opaque types).
/// This method is used during some queries (e.g. `explicit_item_bounds`
/// for opaque types), to ensure that any debug printing that
/// occurs during the query computation does not end up recursively
/// calling the same query.
pub fn with_no_queries<F: FnOnce() -> R, R>(f: F) -> R {
NO_QUERIES.with(|no_queries| {
let old = no_queries.replace(true);
let result = f();
no_queries.set(old);
result
})
}

/// Force us to name impls with just the filename/line number. We
/// normally try to use types. But at some points, notably while printing
/// cycle errors, this can result in extra or suboptimal error output,
/// so this variable disables that check.
pub fn with_forced_impl_filename_line<F: FnOnce() -> R, R>(f: F) -> R {
FORCE_IMPL_FILENAME_LINE.with(|force| {
let old = force.replace(true);
let result = f();
force.set(old);
result
})
}
macro_rules! define_helper {
($($(#[$a:meta])* fn $name:ident($helper:ident, $tl:ident);)+) => {
$(
#[must_use]
pub struct $helper(bool);

impl $helper {
pub fn new() -> $helper {
$helper($tl.with(|c| c.replace(true)))
}
}

/// Adds the `crate::` prefix to paths where appropriate.
pub fn with_crate_prefix<F: FnOnce() -> R, R>(f: F) -> R {
SHOULD_PREFIX_WITH_CRATE.with(|flag| {
let old = flag.replace(true);
let result = f();
flag.set(old);
result
})
}
$(#[$a])*
pub macro $name($e:expr) {
{
let _guard = $helper::new();
$e
}
}

/// Prevent path trimming if it is turned on. Path trimming affects `Display` impl
/// of various rustc types, for example `std::vec::Vec` would be trimmed to `Vec`,
/// if no other `Vec` is found.
pub fn with_no_trimmed_paths<F: FnOnce() -> R, R>(f: F) -> R {
NO_TRIMMED_PATH.with(|flag| {
let old = flag.replace(true);
let result = f();
flag.set(old);
result
})
impl Drop for $helper {
fn drop(&mut self) {
$tl.with(|c| c.set(self.0))
}
}
)+
}
}

/// Prevent selection of visible paths. `Display` impl of DefId will prefer visible (public) reexports of types as paths.
pub fn with_no_visible_paths<F: FnOnce() -> R, R>(f: F) -> R {
NO_VISIBLE_PATH.with(|flag| {
let old = flag.replace(true);
let result = f();
flag.set(old);
result
})
}
define_helper!(
/// Avoids running any queries during any prints that occur
/// during the closure. This may alter the appearance of some
/// types (e.g. forcing verbose printing for opaque types).
/// This method is used during some queries (e.g. `explicit_item_bounds`
/// for opaque types), to ensure that any debug printing that
/// occurs during the query computation does not end up recursively
/// calling the same query.
fn with_no_queries(NoQueriesGuard, NO_QUERIES);
/// Force us to name impls with just the filename/line number. We
/// normally try to use types. But at some points, notably while printing
/// cycle errors, this can result in extra or suboptimal error output,
/// so this variable disables that check.
fn with_forced_impl_filename_line(ForcedImplGuard, FORCE_IMPL_FILENAME_LINE);
/// Adds the `crate::` prefix to paths where appropriate.
fn with_crate_prefix(CratePrefixGuard, SHOULD_PREFIX_WITH_CRATE);
/// Prevent path trimming if it is turned on. Path trimming affects `Display` impl
/// of various rustc types, for example `std::vec::Vec` would be trimmed to `Vec`,
/// if no other `Vec` is found.
fn with_no_trimmed_paths(NoTrimmedGuard, NO_TRIMMED_PATH);
/// Prevent selection of visible paths. `Display` impl of DefId will prefer
/// visible (public) reexports of types as paths.
fn with_no_visible_paths(NoVisibleGuard, NO_VISIBLE_PATH);
);

/// The "region highlights" are used to control region printing during
/// specific error messages. When a "region highlight" is enabled, it
Expand Down Expand Up @@ -379,7 +372,7 @@ pub trait PrettyPrinter<'tcx>:
// in cases where the `extern crate foo` has non-trivial
// parents, e.g. it's nested in `impl foo::Trait for Bar`
// (see also issues #55779 and #87932).
self = with_no_visible_paths(|| self.print_def_path(def_id, &[]))?;
self = with_no_visible_paths!(self.print_def_path(def_id, &[])?);

return Ok((self, true));
}
Expand Down Expand Up @@ -654,7 +647,7 @@ pub trait PrettyPrinter<'tcx>:
return Ok(self);
}

return with_no_queries(|| {
return with_no_queries!({
let def_key = self.tcx().def_key(def_id);
if let Some(name) = def_key.disambiguated_data.data.get_opt_name() {
p!(write("{}", name));
Expand Down

0 comments on commit 523a1b1

Please sign in to comment.