Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rollup of 8 pull requests #121345

Merged
merged 16 commits into from
Feb 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion compiler/rustc_builtin_macros/src/asm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -773,7 +773,7 @@ pub(super) fn expand_global_asm<'cx>(
kind: ast::VisibilityKind::Inherited,
tokens: None,
},
span: ecx.with_def_site_ctxt(sp),
span: sp,
tokens: None,
})])
} else {
Expand Down
5 changes: 4 additions & 1 deletion compiler/rustc_lint/messages.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,11 @@ lint_builtin_explicit_outlives = outlives requirements can be inferred

lint_builtin_export_name_fn = declaration of a function with `export_name`
lint_builtin_export_name_method = declaration of a method with `export_name`

lint_builtin_export_name_static = declaration of a static with `export_name`

lint_builtin_global_asm = usage of `core::arch::global_asm`
lint_builtin_global_macro_unsafety = using this macro is unsafe even though it does not need an `unsafe` block

lint_builtin_impl_unsafe_method = implementation of an `unsafe` method

lint_builtin_incomplete_features = the feature `{$name}` is incomplete and may not be safe to use and/or cause compiler crashes
Expand Down
4 changes: 4 additions & 0 deletions compiler/rustc_lint/src/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,10 @@ impl EarlyLintPass for UnsafeCode {
}
}

ast::ItemKind::GlobalAsm(..) => {
self.report_unsafe(cx, it.span, BuiltinUnsafe::GlobalAsm);
}

_ => {}
}
}
Expand Down
3 changes: 3 additions & 0 deletions compiler/rustc_lint/src/lints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,9 @@ pub enum BuiltinUnsafe {
DeclUnsafeMethod,
#[diag(lint_builtin_impl_unsafe_method)]
ImplUnsafeMethod,
#[diag(lint_builtin_global_asm)]
#[note(lint_builtin_global_macro_unsafety)]
GlobalAsm,
}

#[derive(LintDiagnostic)]
Expand Down
10 changes: 0 additions & 10 deletions compiler/rustc_metadata/src/creader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1070,16 +1070,6 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> {
pub fn maybe_process_path_extern(&mut self, name: Symbol) -> Option<CrateNum> {
self.maybe_resolve_crate(name, CrateDepKind::Explicit, None).ok()
}

pub fn unload_unused_crates(&mut self) {
for opt_cdata in &mut self.cstore.metas {
if let Some(cdata) = opt_cdata
&& !cdata.used()
{
*opt_cdata = None;
}
}
}
}

fn global_allocator_spans(krate: &ast::Crate) -> Vec<Span> {
Expand Down
10 changes: 10 additions & 0 deletions compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -519,6 +519,16 @@ pub(in crate::rmeta) fn provide(providers: &mut Providers) {
tcx.untracked().cstore.freeze();
tcx.arena.alloc_from_iter(CStore::from_tcx(tcx).iter_crate_data().map(|(cnum, _)| cnum))
},
used_crates: |tcx, ()| {
// The list of loaded crates is now frozen in query cache,
// so make sure cstore is not mutably accessed from here on.
tcx.untracked().cstore.freeze();
tcx.arena.alloc_from_iter(
CStore::from_tcx(tcx)
.iter_crate_data()
.filter_map(|(cnum, data)| data.used().then_some(cnum)),
)
},
..providers.queries
};
provide_extern(&mut providers.extern_queries);
Expand Down
7 changes: 7 additions & 0 deletions compiler/rustc_middle/src/query/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1872,6 +1872,13 @@ rustc_queries! {
eval_always
desc { "fetching all foreign CrateNum instances" }
}
// Crates that are loaded non-speculatively (not for diagnostics or doc links).
// FIXME: This is currently only used for collecting lang items, but should be used instead of
// `crates` in most other cases too.
query used_crates(_: ()) -> &'tcx [CrateNum] {
eval_always
desc { "fetching `CrateNum`s for all crates loaded non-speculatively" }
}

/// A list of all traits in a crate, used by rustdoc and error reporting.
query traits(_: CrateNum) -> &'tcx [DefId] {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
//! Propagates constants for early reporting of statically known
//! assertion failures
//! A lint that checks for known panics like
//! overflows, division by zero,
//! out-of-bound access etc.
//! Uses const propagation to determine the
//! values of operands during checks.

use std::fmt::Debug;

Expand All @@ -21,9 +24,9 @@ use crate::dataflow_const_prop::DummyMachine;
use crate::errors::{AssertLint, AssertLintKind};
use crate::MirLint;

pub struct ConstPropLint;
pub struct KnownPanicsLint;

impl<'tcx> MirLint<'tcx> for ConstPropLint {
impl<'tcx> MirLint<'tcx> for KnownPanicsLint {
fn run_lint(&self, tcx: TyCtxt<'tcx>, body: &Body<'tcx>) {
if body.tainted_by_errors.is_some() {
return;
Expand All @@ -37,31 +40,28 @@ impl<'tcx> MirLint<'tcx> for ConstPropLint {
// Only run const prop on functions, methods, closures and associated constants
if !is_fn_like && !is_assoc_const {
// skip anon_const/statics/consts because they'll be evaluated by miri anyway
trace!("ConstPropLint skipped for {:?}", def_id);
trace!("KnownPanicsLint skipped for {:?}", def_id);
return;
}

// FIXME(welseywiser) const prop doesn't work on coroutines because of query cycles
// computing their layout.
if tcx.is_coroutine(def_id.to_def_id()) {
trace!("ConstPropLint skipped for coroutine {:?}", def_id);
trace!("KnownPanicsLint skipped for coroutine {:?}", def_id);
return;
}

trace!("ConstPropLint starting for {:?}", def_id);
trace!("KnownPanicsLint starting for {:?}", def_id);

// FIXME(oli-obk, eddyb) Optimize locals (or even local paths) to hold
// constants, instead of just checking for const-folding succeeding.
// That would require a uniform one-def no-mutation analysis
// and RPO (or recursing when needing the value of a local).
let mut linter = ConstPropagator::new(body, tcx);
linter.visit_body(body);

trace!("ConstPropLint done for {:?}", def_id);
trace!("KnownPanicsLint done for {:?}", def_id);
}
}

/// Finds optimization opportunities on the MIR.
/// Visits MIR nodes, performs const propagation
/// and runs lint checks as it goes
struct ConstPropagator<'mir, 'tcx> {
ecx: InterpCx<'mir, 'tcx, DummyMachine>,
tcx: TyCtxt<'tcx>,
Expand Down Expand Up @@ -238,7 +238,7 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
// dedicated error variants should be introduced instead.
assert!(
!error.kind().formatted_string(),
"const-prop encountered formatting error: {}",
"known panics lint encountered formatting error: {}",
format_interp_error(self.ecx.tcx.dcx(), error),
);
None
Expand All @@ -253,7 +253,7 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
return None;
}

// Normalization needed b/c const prop lint runs in
// Normalization needed b/c known panics lint runs in
// `mir_drops_elaborated_and_const_checked`, which happens before
// optimized MIR. Only after optimizing the MIR can we guarantee
// that the `RevealAll` pass has happened and that the body's consts
Expand Down Expand Up @@ -864,6 +864,8 @@ pub enum ConstPropMode {
NoPropagation,
}

/// A visitor that determines locals in a MIR body
/// that can be const propagated
pub struct CanConstProp {
can_const_prop: IndexVec<Local, ConstPropMode>,
// False at the beginning. Once set, no more assignments are allowed to that local.
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_mir_transform/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,6 @@ mod remove_place_mention;
mod add_subtyping_projections;
pub mod cleanup_post_borrowck;
mod const_debuginfo;
mod const_prop_lint;
mod copy_prop;
mod coroutine;
mod cost_checker;
Expand All @@ -83,6 +82,7 @@ mod gvn;
pub mod inline;
mod instsimplify;
mod jump_threading;
mod known_panics_lint;
mod large_enums;
mod lint;
mod lower_intrinsics;
Expand Down Expand Up @@ -533,7 +533,7 @@ fn run_runtime_lowering_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
&elaborate_box_derefs::ElaborateBoxDerefs,
&coroutine::StateTransform,
&add_retag::AddRetag,
&Lint(const_prop_lint::ConstPropLint),
&Lint(known_panics_lint::KnownPanicsLint),
];
pm::run_passes_no_validate(tcx, body, passes, Some(MirPhase::Runtime(RuntimePhase::Initial)));
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_passes/src/lang_items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ fn get_lang_items(tcx: TyCtxt<'_>, (): ()) -> LanguageItems {
let mut collector = LanguageItemCollector::new(tcx, resolver);

// Collect lang items in other crates.
for &cnum in tcx.crates(()).iter() {
for &cnum in tcx.used_crates(()).iter() {
for &(def_id, lang_item) in tcx.defined_lang_items(cnum).iter() {
collector.collect_item(lang_item, def_id, None);
}
Expand Down
5 changes: 0 additions & 5 deletions compiler/rustc_resolve/src/late.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ use rustc_hir::def::Namespace::{self, *};
use rustc_hir::def::{self, CtorKind, DefKind, LifetimeRes, NonMacroAttrKind, PartialRes, PerNS};
use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID, LOCAL_CRATE};
use rustc_hir::{PrimTy, TraitCandidate};
use rustc_metadata::creader::CStore;
use rustc_middle::middle::resolve_bound_vars::Set1;
use rustc_middle::{bug, span_bug};
use rustc_session::config::{CrateType, ResolveDocLinks};
Expand Down Expand Up @@ -4574,10 +4573,6 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> {
// Encoding foreign def ids in proc macro crate metadata will ICE.
return None;
}
// Doc paths should be resolved speculatively and should not produce any
// diagnostics, but if they are indeed resolved, then we need to keep the
// corresponding crate alive.
CStore::from_tcx_mut(self.r.tcx).set_used_recursively(def_id.krate);
}
res
});
Expand Down
1 change: 0 additions & 1 deletion compiler/rustc_resolve/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1651,7 +1651,6 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
self.tcx
.sess
.time("resolve_postprocess", || self.crate_loader(|c| c.postprocess(krate)));
self.crate_loader(|c| c.unload_unused_crates());
});

// Make sure we don't mutate the cstore from here on.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::spec::{base, CodeModel, Target, TargetOptions};
use crate::spec::{base, Target, TargetOptions};

pub fn target() -> Target {
Target {
Expand All @@ -7,7 +7,6 @@ pub fn target() -> Target {
data_layout: "e-m:e-p:64:64-i64:64-i128:128-n64-S128".into(),
arch: "loongarch64".into(),
options: TargetOptions {
code_model: Some(CodeModel::Medium),
cpu: "generic".into(),
features: "+f,+d".into(),
llvm_abiname: "lp64d".into(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ pub fn target() -> Target {
max_atomic_width: Some(64),
relocation_model: RelocModel::Static,
panic_strategy: PanicStrategy::Abort,
code_model: Some(CodeModel::Medium),
code_model: Some(CodeModel::Small),
..Default::default()
},
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ pub fn target() -> Target {
max_atomic_width: Some(64),
relocation_model: RelocModel::Static,
panic_strategy: PanicStrategy::Abort,
code_model: Some(CodeModel::Medium),
code_model: Some(CodeModel::Small),
..Default::default()
},
}
Expand Down
9 changes: 8 additions & 1 deletion library/core/src/intrinsics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2575,6 +2575,7 @@ pub const fn is_val_statically_known<T: Copy>(_arg: T) -> bool {
/// assertions disabled. This intrinsic is primarily used by [`assert_unsafe_precondition`].
#[rustc_const_unstable(feature = "delayed_debug_assertions", issue = "none")]
#[unstable(feature = "core_intrinsics", issue = "none")]
#[inline(always)]
#[cfg_attr(not(bootstrap), rustc_intrinsic)]
pub(crate) const fn debug_assertions() -> bool {
cfg!(debug_assertions)
Expand Down Expand Up @@ -2659,7 +2660,13 @@ pub const unsafe fn const_deallocate(_ptr: *mut u8, _size: usize, _align: usize)
macro_rules! assert_unsafe_precondition {
($message:expr, ($($name:ident:$ty:ty = $arg:expr),*$(,)?) => $e:expr $(,)?) => {
{
#[inline(never)]
// When the standard library is compiled with debug assertions, we want the check to inline for better performance.
// This is important when working on the compiler, which is compiled with debug assertions locally.
// When not compiled with debug assertions (so the precompiled std) we outline the check to minimize the compile
// time impact when debug assertions are disabled.
// It is not clear whether that is the best solution, see #120848.
#[cfg_attr(debug_assertions, inline(always))]
#[cfg_attr(not(debug_assertions), inline(never))]
#[rustc_nounwind]
fn precondition_check($($name:$ty),*) {
if !$e {
Expand Down
Loading
Loading