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

Replace visibility test with reachability test in dead code detection #119552

Merged
merged 9 commits into from
Mar 23, 2024
2 changes: 0 additions & 2 deletions compiler/rustc_borrowck/src/region_infer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2065,7 +2065,6 @@ impl<'tcx> RegionInferenceContext<'tcx> {
from_closure: constraint.from_closure,
cause: ObligationCause::new(constraint.span, CRATE_DEF_ID, cause_code.clone()),
variance_info: constraint.variance_info,
outlives_constraint: *constraint,
})
.collect();
debug!("categorized_path={:#?}", categorized_path);
Expand Down Expand Up @@ -2294,5 +2293,4 @@ pub struct BlameConstraint<'tcx> {
pub from_closure: bool,
pub cause: ObligationCause<'tcx>,
pub variance_info: ty::VarianceDiagInfo<'tcx>,
pub outlives_constraint: OutlivesConstraint<'tcx>,
}
2 changes: 1 addition & 1 deletion compiler/rustc_builtin_macros/src/deriving/debug.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ fn show_substructure(cx: &mut ExtCtxt<'_>, span: Span, substr: &Substructure<'_>

let (ident, vdata, fields) = match substr.fields {
Struct(vdata, fields) => (substr.type_ident, *vdata, fields),
EnumMatching(_, _, v, fields) => (v.ident, &v.data, fields),
EnumMatching(_, v, fields) => (v.ident, &v.data, fields),
AllFieldlessEnum(enum_def) => return show_fieldless_enum(cx, span, enum_def, substr),
EnumTag(..) | StaticStruct(..) | StaticEnum(..) => {
cx.dcx().span_bug(span, "nonsensical .fields in `#[derive(Debug)]`")
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_builtin_macros/src/deriving/encodable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ fn encodable_substructure(
BlockOrExpr::new_expr(expr)
}

EnumMatching(idx, _, variant, fields) => {
EnumMatching(idx, variant, fields) => {
// We're not generating an AST that the borrow checker is expecting,
// so we need to generate a unique local variable to take the
// mutable loan out on, otherwise we get conflicts which don't
Expand Down
10 changes: 5 additions & 5 deletions compiler/rustc_builtin_macros/src/deriving/generic/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -310,10 +310,10 @@ pub enum SubstructureFields<'a> {
/// variants has any fields).
AllFieldlessEnum(&'a ast::EnumDef),

/// Matching variants of the enum: variant index, variant count, ast::Variant,
/// Matching variants of the enum: variant index, ast::Variant,
/// fields: the field name is only non-`None` in the case of a struct
/// variant.
EnumMatching(usize, usize, &'a ast::Variant, Vec<FieldInfo>),
EnumMatching(usize, &'a ast::Variant, Vec<FieldInfo>),

/// The tag of an enum. The first field is a `FieldInfo` for the tags, as
/// if they were fields. The second field is the expression to combine the
Expand Down Expand Up @@ -1272,7 +1272,7 @@ impl<'a> MethodDef<'a> {
trait_,
type_ident,
nonselflike_args,
&EnumMatching(0, 1, &variants[0], Vec::new()),
&EnumMatching(0, &variants[0], Vec::new()),
);
}
}
Expand Down Expand Up @@ -1318,7 +1318,7 @@ impl<'a> MethodDef<'a> {
// expressions for referencing every field of every
// Self arg, assuming all are instances of VariantK.
// Build up code associated with such a case.
let substructure = EnumMatching(index, variants.len(), variant, fields);
let substructure = EnumMatching(index, variant, fields);
let arm_expr = self
.call_substructure_method(
cx,
Expand Down Expand Up @@ -1346,7 +1346,7 @@ impl<'a> MethodDef<'a> {
trait_,
type_ident,
nonselflike_args,
&EnumMatching(0, variants.len(), v, Vec::new()),
&EnumMatching(0, v, Vec::new()),
)
.into_expr(cx, span),
)
Expand Down
4 changes: 4 additions & 0 deletions compiler/rustc_codegen_gcc/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ pub struct CodegenCx<'gcc, 'tcx> {
local_gen_sym_counter: Cell<usize>,

eh_personality: Cell<Option<RValue<'gcc>>>,
#[cfg(feature="master")]
pub rust_try_fn: Cell<Option<(Type<'gcc>, Function<'gcc>)>>,

pub pointee_infos: RefCell<FxHashMap<(Ty<'tcx>, Size), Option<PointeeInfo>>>,
Expand All @@ -121,6 +122,7 @@ pub struct CodegenCx<'gcc, 'tcx> {
/// FIXME(antoyo): fix the rustc API to avoid having this hack.
pub structs_as_pointer: RefCell<FxHashSet<RValue<'gcc>>>,

#[cfg(feature="master")]
pub cleanup_blocks: RefCell<FxHashSet<Block<'gcc>>>,
}

Expand Down Expand Up @@ -325,9 +327,11 @@ impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> {
struct_types: Default::default(),
local_gen_sym_counter: Cell::new(0),
eh_personality: Cell::new(None),
#[cfg(feature="master")]
rust_try_fn: Cell::new(None),
krtab marked this conversation as resolved.
Show resolved Hide resolved
pointee_infos: Default::default(),
structs_as_pointer: Default::default(),
#[cfg(feature="master")]
cleanup_blocks: Default::default(),
krtab marked this conversation as resolved.
Show resolved Hide resolved
};
// TODO(antoyo): instead of doing this, add SsizeT to libgccjit.
Expand Down
6 changes: 1 addition & 5 deletions compiler/rustc_codegen_llvm/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,7 @@ use rustc_session::config::{CrateType, DebugInfo, PAuthKey, PacRet};
use rustc_session::Session;
use rustc_span::source_map::Spanned;
use rustc_span::Span;
use rustc_target::abi::{
call::FnAbi, HasDataLayout, PointeeInfo, Size, TargetDataLayout, VariantIdx,
};
use rustc_target::abi::{call::FnAbi, HasDataLayout, TargetDataLayout, VariantIdx};
use rustc_target::spec::{HasTargetSpec, RelocModel, Target, TlsModel};
use smallvec::SmallVec;

Expand Down Expand Up @@ -83,7 +81,6 @@ pub struct CodegenCx<'ll, 'tcx> {
/// Mapping of scalar types to llvm types.
pub scalar_lltypes: RefCell<FxHashMap<Ty<'tcx>, &'ll Type>>,

pub pointee_infos: RefCell<FxHashMap<(Ty<'tcx>, Size), Option<PointeeInfo>>>,
pub isize_ty: &'ll Type,

pub coverage_cx: Option<coverageinfo::CrateCoverageContext<'ll, 'tcx>>,
Expand Down Expand Up @@ -460,7 +457,6 @@ impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> {
compiler_used_statics: RefCell::new(Vec::new()),
type_lowering: Default::default(),
scalar_lltypes: Default::default(),
pointee_infos: Default::default(),
isize_ty,
coverage_cx,
dbg_cx,
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_mir_transform/src/gvn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ fn propagate_ssa<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
|local, value, location| {
let value = match value {
// We do not know anything of this assigned value.
AssignedValue::Arg | AssignedValue::Terminator(_) => None,
AssignedValue::Arg | AssignedValue::Terminator => None,
// Try to get some insight.
AssignedValue::Rvalue(rvalue) => {
let value = state.simplify_rvalue(rvalue, location);
Expand Down
5 changes: 2 additions & 3 deletions compiler/rustc_mir_transform/src/ssa.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ pub struct SsaLocals {
pub enum AssignedValue<'a, 'tcx> {
Arg,
Rvalue(&'a mut Rvalue<'tcx>),
Terminator(&'a mut TerminatorKind<'tcx>),
Terminator,
}

impl SsaLocals {
Expand Down Expand Up @@ -149,8 +149,7 @@ impl SsaLocals {
Set1::One(DefLocation::CallReturn { call, .. }) => {
let bb = &mut basic_blocks[call];
let loc = Location { block: call, statement_index: bb.statements.len() };
let term = bb.terminator_mut();
f(local, AssignedValue::Terminator(&mut term.kind), loc)
f(local, AssignedValue::Terminator, loc)
}
_ => {}
}
Expand Down
5 changes: 3 additions & 2 deletions compiler/rustc_passes/src/dead.rs
Original file line number Diff line number Diff line change
Expand Up @@ -529,15 +529,16 @@ impl<'tcx> Visitor<'tcx> for MarkSymbolVisitor<'tcx> {
let tcx = self.tcx;
let unconditionally_treat_fields_as_live = self.repr_unconditionally_treats_fields_as_live;
let has_repr_simd = self.repr_has_repr_simd;
let effective_visibilities = &tcx.effective_visibilities(());
let live_fields = def.fields().iter().filter_map(|f| {
let def_id = f.def_id;
if unconditionally_treat_fields_as_live || (f.is_positional() && has_repr_simd) {
return Some(def_id);
}
if !tcx.visibility(f.hir_id.owner.def_id).is_public() {
if !effective_visibilities.is_reachable(f.hir_id.owner.def_id) {
return None;
}
if tcx.visibility(def_id).is_public() { Some(def_id) } else { None }
if effective_visibilities.is_reachable(def_id) { Some(def_id) } else { None }
});
self.live_symbols.extend(live_fields);

Expand Down
6 changes: 3 additions & 3 deletions library/alloc/src/collections/btree/navigate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -655,7 +655,7 @@ impl<BorrowType: marker::BorrowType, K, V> NodeRef<BorrowType, K, V, marker::Lea
pub enum Position<BorrowType, K, V> {
Leaf(NodeRef<BorrowType, K, V, marker::Leaf>),
Internal(NodeRef<BorrowType, K, V, marker::Internal>),
InternalKV(Handle<NodeRef<BorrowType, K, V, marker::Internal>, marker::KV>),
InternalKV,
}

impl<'a, K: 'a, V: 'a> NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal> {
Expand All @@ -677,7 +677,7 @@ impl<'a, K: 'a, V: 'a> NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal>
visit(Position::Leaf(leaf));
match edge.next_kv() {
Ok(kv) => {
visit(Position::InternalKV(kv));
visit(Position::InternalKV);
kv.right_edge()
}
Err(_) => return,
Expand All @@ -699,7 +699,7 @@ impl<'a, K: 'a, V: 'a> NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal>
self.visit_nodes_in_order(|pos| match pos {
Position::Leaf(node) => result += node.len(),
Position::Internal(node) => result += node.len(),
Position::InternalKV(_) => (),
Position::InternalKV => (),
});
result
}
Expand Down
6 changes: 1 addition & 5 deletions library/alloc/src/collections/btree/node/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,7 @@ impl<'a, K: 'a, V: 'a> NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal>
result += &format!("\n{}{:?}", indent, leaf.keys());
}
navigate::Position::Internal(_) => {}
navigate::Position::InternalKV(kv) => {
let depth = self.height() - kv.into_node().height();
let indent = " ".repeat(depth);
result += &format!("\n{}{:?}", indent, kv.into_kv().0);
}
navigate::Position::InternalKV => {}
});
result
}
Expand Down
2 changes: 2 additions & 0 deletions library/std/src/sys/pal/sgx/net.rs
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,7 @@ pub mod netc {

#[derive(Copy, Clone)]
pub struct sockaddr_in {
#[allow(dead_code)]
pub sin_family: sa_family_t,
pub sin_port: u16,
pub sin_addr: in_addr,
Expand All @@ -536,6 +537,7 @@ pub mod netc {

#[derive(Copy, Clone)]
pub struct sockaddr_in6 {
#[allow(dead_code)]
pub sin6_family: sa_family_t,
pub sin6_port: u16,
pub sin6_addr: in6_addr,
Expand Down
2 changes: 1 addition & 1 deletion library/std/src/sys/pal/unix/thread_local_dtor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern "C" fn(*mut u8)) {
#[cfg(not(sanitizer_cfi_normalize_integers))]
#[cfi_encoding = "i"]
#[repr(transparent)]
pub struct c_int(pub libc::c_int);
pub struct c_int(#[allow(dead_code)] pub libc::c_int);

extern "C" {
#[linkage = "extern_weak"]
Expand Down
2 changes: 2 additions & 0 deletions library/std/src/sys/pal/unsupported/net.rs
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,7 @@ pub mod netc {

#[derive(Copy, Clone)]
pub struct sockaddr_in {
#[allow(dead_code)]
pub sin_family: sa_family_t,
pub sin_port: u16,
pub sin_addr: in_addr,
Expand All @@ -358,6 +359,7 @@ pub mod netc {

#[derive(Copy, Clone)]
pub struct sockaddr_in6 {
#[allow(dead_code)]
pub sin6_family: sa_family_t,
pub sin6_port: u16,
pub sin6_addr: in6_addr,
Expand Down
2 changes: 2 additions & 0 deletions library/std/src/sys/pal/wasi/net.rs
Original file line number Diff line number Diff line change
Expand Up @@ -520,6 +520,7 @@ pub mod netc {

#[derive(Copy, Clone)]
pub struct sockaddr_in {
#[allow(dead_code)]
pub sin_family: sa_family_t,
pub sin_port: u16,
pub sin_addr: in_addr,
Expand All @@ -532,6 +533,7 @@ pub mod netc {

#[derive(Copy, Clone)]
pub struct sockaddr_in6 {
#[allow(dead_code)]
pub sin6_family: sa_family_t,
pub sin6_port: u16,
pub sin6_addr: in6_addr,
Expand Down
9 changes: 1 addition & 8 deletions library/test/src/console.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ pub struct ConsoleTestDiscoveryState {
pub tests: usize,
pub benchmarks: usize,
pub ignored: usize,
pub options: Options,
}

impl ConsoleTestDiscoveryState {
Expand All @@ -56,13 +55,7 @@ impl ConsoleTestDiscoveryState {
None => None,
};

Ok(ConsoleTestDiscoveryState {
log_out,
tests: 0,
benchmarks: 0,
ignored: 0,
options: opts.options,
})
Ok(ConsoleTestDiscoveryState { log_out, tests: 0, benchmarks: 0, ignored: 0 })
}

pub fn write_log<F, S>(&mut self, msg: F) -> io::Result<()>
Expand Down
15 changes: 3 additions & 12 deletions src/bootstrap/src/core/build_steps/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2134,18 +2134,9 @@ pub struct CargoTarget<'a> {
#[derive(Deserialize)]
#[serde(tag = "reason", rename_all = "kebab-case")]
pub enum CargoMessage<'a> {
CompilerArtifact {
package_id: Cow<'a, str>,
features: Vec<Cow<'a, str>>,
filenames: Vec<Cow<'a, str>>,
target: CargoTarget<'a>,
},
BuildScriptExecuted {
package_id: Cow<'a, str>,
},
BuildFinished {
success: bool,
},
CompilerArtifact { filenames: Vec<Cow<'a, str>>, target: CargoTarget<'a> },
BuildScriptExecuted,
BuildFinished,
}

pub fn strip_debug(builder: &Builder<'_>, target: TargetSelection, path: &Path) {
Expand Down
6 changes: 4 additions & 2 deletions src/tools/clippy/clippy_lints/src/raw_strings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ impl EarlyLintPass for RawStrings {
}
}

let req = {
let mut req = {
let mut following_quote = false;
let mut req = 0;
// `once` so a raw string ending in hashes is still checked
Expand Down Expand Up @@ -136,7 +136,9 @@ impl EarlyLintPass for RawStrings {
ControlFlow::Continue(num) | ControlFlow::Break(num) => num,
}
};

if self.allow_one_hash_in_raw_strings {
req = req.max(1);
}
if req < max {
span_lint_and_then(
cx,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
allow-one-hash-in-raw-strings = true
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#![allow(clippy::no_effect, unused)]
#![warn(clippy::needless_raw_string_hashes)]

fn main() {
r#"\aaa"#;
r#"\aaa"#;
r#"Hello "world"!"#;
r####" "### "## "# "####;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#![allow(clippy::no_effect, unused)]
#![warn(clippy::needless_raw_string_hashes)]

fn main() {
r#"\aaa"#;
r##"\aaa"##;
r##"Hello "world"!"##;
r######" "### "## "# "######;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
error: unnecessary hashes around raw string literal
--> tests/ui-toml/needless_raw_string_hashes_one_allowed/needless_raw_string_hashes.rs:6:5
|
LL | r##"\aaa"##;
| ^^^^^^^^^^^
|
= note: `-D clippy::needless-raw-string-hashes` implied by `-D warnings`
= help: to override `-D warnings` add `#[allow(clippy::needless_raw_string_hashes)]`
help: remove one hash from both sides of the string literal
|
LL - r##"\aaa"##;
LL + r#"\aaa"#;
|

error: unnecessary hashes around raw string literal
--> tests/ui-toml/needless_raw_string_hashes_one_allowed/needless_raw_string_hashes.rs:7:5
|
LL | r##"Hello "world"!"##;
| ^^^^^^^^^^^^^^^^^^^^^
|
help: remove one hash from both sides of the string literal
|
LL - r##"Hello "world"!"##;
LL + r#"Hello "world"!"#;
|

error: unnecessary hashes around raw string literal
--> tests/ui-toml/needless_raw_string_hashes_one_allowed/needless_raw_string_hashes.rs:8:5
|
LL | r######" "### "## "# "######;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
help: remove 2 hashes from both sides of the string literal
|
LL - r######" "### "## "# "######;
LL + r####" "### "## "# "####;
|

error: aborting due to 3 previous errors

Loading
Loading