Skip to content

Rollup of 5 pull requests #71513

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

Closed
wants to merge 15 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
6 changes: 3 additions & 3 deletions src/bootstrap/toolstate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,12 +93,12 @@ static NIGHTLY_TOOLS: &[(&str, &str)] = &[
];

fn print_error(tool: &str, submodule: &str) {
eprintln!("");
eprintln!();
eprintln!("We detected that this PR updated '{}', but its tests failed.", tool);
eprintln!("");
eprintln!();
eprintln!("If you do intend to update '{}', please check the error messages above and", tool);
eprintln!("commit another update.");
eprintln!("");
eprintln!();
eprintln!("If you do NOT intend to update '{}', please ensure you did not accidentally", tool);
eprintln!("change the submodule at '{}'. You may ask your reviewer for the", submodule);
eprintln!("proper steps.");
Expand Down
28 changes: 28 additions & 0 deletions src/liballoc/collections/binary_heap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -665,6 +665,34 @@ impl<T: Ord> BinaryHeap<T> {
pub fn drain_sorted(&mut self) -> DrainSorted<'_, T> {
DrainSorted { inner: self }
}

/// Retains only the elements specified by the predicate.
///
/// In other words, remove all elements `e` such that `f(&e)` returns
/// `false`. The elements are visited in unsorted (and unspecified) order.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(binary_heap_retain)]
/// use std::collections::BinaryHeap;
///
/// let mut heap = BinaryHeap::from(vec![-10, -5, 1, 2, 4, 13]);
///
/// heap.retain(|x| x % 2 == 0); // only keep even numbers
///
/// assert_eq!(heap.into_sorted_vec(), [-10, 2, 4])
/// ```
#[unstable(feature = "binary_heap_retain", issue = "71503")]
pub fn retain<F>(&mut self, f: F)
where
F: FnMut(&T) -> bool,
{
self.data.retain(f);
self.rebuild();
}
}

impl<T> BinaryHeap<T> {
Expand Down
8 changes: 8 additions & 0 deletions src/liballoc/tests/binary_heap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,14 @@ fn assert_covariance() {
}
}

#[test]
fn test_retain() {
let mut a = BinaryHeap::from(vec![-10, -5, 1, 2, 4, 13]);
a.retain(|x| x % 2 == 0);

assert_eq!(a.into_sorted_vec(), [-10, 2, 4])
}

// old binaryheap failed this test
//
// Integrity means that all elements are present after a comparison panics,
Expand Down
1 change: 1 addition & 0 deletions src/liballoc/tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
#![feature(binary_heap_drain_sorted)]
#![feature(vec_remove_item)]
#![feature(split_inclusive)]
#![feature(binary_heap_retain)]

use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
Expand Down
12 changes: 9 additions & 3 deletions src/libcore/panic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,11 @@ impl<'a> PanicInfo<'a> {
/// use std::panic;
///
/// panic::set_hook(Box::new(|panic_info| {
/// println!("panic occurred: {:?}", panic_info.payload().downcast_ref::<&str>().unwrap());
/// if let Some(s) = panic_info.payload().downcast_ref::<&str>() {
/// println!("panic occurred: {:?}", s);
/// } else {
/// println!("panic occurred");
/// }
/// }));
///
/// panic!("Normal panic");
Expand Down Expand Up @@ -112,8 +116,10 @@ impl<'a> PanicInfo<'a> {
///
/// panic::set_hook(Box::new(|panic_info| {
/// if let Some(location) = panic_info.location() {
/// println!("panic occurred in file '{}' at line {}", location.file(),
/// location.line());
/// println!("panic occurred in file '{}' at line {}",
/// location.file(),
/// location.line(),
/// );
/// } else {
/// println!("panic occurred but can't get location information...");
/// }
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_codegen_ssa/mir/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ pub fn codegen_mir<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
let cleanup_kinds = analyze::cleanup_kinds(&mir);
// Allocate a `Block` for every basic block, except
// the start block, if nothing loops back to it.
let reentrant_start_block = !mir.predecessors_for(mir::START_BLOCK).is_empty();
let reentrant_start_block = !mir.predecessors()[mir::START_BLOCK].is_empty();
let block_bxs: IndexVec<mir::BasicBlock, Bx::BasicBlock> = mir
.basic_blocks()
.indices()
Expand Down
15 changes: 2 additions & 13 deletions src/librustc_middle/mir/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,12 @@ use rustc_ast::ast::Name;
use rustc_data_structures::fx::FxHashSet;
use rustc_data_structures::graph::dominators::{dominators, Dominators};
use rustc_data_structures::graph::{self, GraphSuccessors};
use rustc_data_structures::sync::MappedLockGuard;
use rustc_index::bit_set::BitMatrix;
use rustc_index::vec::{Idx, IndexVec};
use rustc_macros::HashStable;
use rustc_serialize::{Decodable, Encodable};
use rustc_span::symbol::Symbol;
use rustc_span::{Span, DUMMY_SP};
use smallvec::SmallVec;
use std::borrow::Cow;
use std::fmt::{self, Debug, Display, Formatter, Write};
use std::ops::{Index, IndexMut};
Expand Down Expand Up @@ -170,7 +168,7 @@ pub struct Body<'tcx> {
/// FIXME(oli-obk): rewrite the promoted during promotion to eliminate the cell components.
pub ignore_interior_mut_in_const_validation: bool,

pub predecessor_cache: PredecessorCache,
predecessor_cache: PredecessorCache,
}

impl<'tcx> Body<'tcx> {
Expand Down Expand Up @@ -398,15 +396,6 @@ impl<'tcx> Body<'tcx> {
Location { block: bb, statement_index: self[bb].statements.len() }
}

#[inline]
pub fn predecessors_for(
&self,
bb: BasicBlock,
) -> impl std::ops::Deref<Target = SmallVec<[BasicBlock; 4]>> + '_ {
let predecessors = self.predecessor_cache.compute(&self.basic_blocks);
MappedLockGuard::map(predecessors, |preds| &mut preds[bb])
}

#[inline]
pub fn predecessors(&self) -> impl std::ops::Deref<Target = Predecessors> + '_ {
self.predecessor_cache.compute(&self.basic_blocks)
Expand Down Expand Up @@ -2684,7 +2673,7 @@ impl graph::GraphPredecessors<'graph> for Body<'tcx> {
impl graph::WithPredecessors for Body<'tcx> {
#[inline]
fn predecessors(&self, node: Self::Node) -> <Self as graph::GraphPredecessors<'_>>::Iter {
self.predecessors_for(node).clone().into_iter()
self.predecessors()[node].clone().into_iter()
}
}

Expand Down
47 changes: 29 additions & 18 deletions src/librustc_middle/mir/predecessors.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
//! Lazily compute the reverse control-flow graph for the MIR.

use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_data_structures::sync::{Lock, LockGuard, MappedLockGuard};
use rustc_data_structures::sync::{Lock, Lrc};
use rustc_index::vec::IndexVec;
use rustc_serialize as serialize;
use smallvec::SmallVec;
Expand All @@ -10,40 +12,49 @@ use crate::mir::{BasicBlock, BasicBlockData};
pub type Predecessors = IndexVec<BasicBlock, SmallVec<[BasicBlock; 4]>>;

#[derive(Clone, Debug)]
pub struct PredecessorCache {
cache: Lock<Option<Predecessors>>,
pub(super) struct PredecessorCache {
cache: Lock<Option<Lrc<Predecessors>>>,
}

impl PredecessorCache {
#[inline]
pub fn new() -> Self {
pub(super) fn new() -> Self {
PredecessorCache { cache: Lock::new(None) }
}

/// Invalidates the predecessor cache.
///
/// Invalidating the predecessor cache requires mutating the MIR, which in turn requires a
/// unique reference (`&mut`) to the `mir::Body`. Because of this, we can assume that all
/// callers of `invalidate` have a unique reference to the MIR and thus to the predecessor
/// cache. This means we don't actually need to take a lock when `invalidate` is called.
#[inline]
pub fn invalidate(&mut self) {
pub(super) fn invalidate(&mut self) {
*self.cache.get_mut() = None;
}

/// Returns a ref-counted smart pointer containing the predecessor graph for this MIR.
///
/// We use ref-counting instead of a mapped `LockGuard` here to ensure that the lock for
/// `cache` is only held inside this function. As long as no other locks are taken while
/// computing the predecessor graph, deadlock is impossible.
#[inline]
pub fn compute(
pub(super) fn compute(
&self,
basic_blocks: &IndexVec<BasicBlock, BasicBlockData<'_>>,
) -> MappedLockGuard<'_, Predecessors> {
LockGuard::map(self.cache.lock(), |cache| {
cache.get_or_insert_with(|| {
let mut preds = IndexVec::from_elem(SmallVec::new(), basic_blocks);
for (bb, data) in basic_blocks.iter_enumerated() {
if let Some(term) = &data.terminator {
for &succ in term.successors() {
preds[succ].push(bb);
}
) -> Lrc<Predecessors> {
Lrc::clone(self.cache.lock().get_or_insert_with(|| {
let mut preds = IndexVec::from_elem(SmallVec::new(), basic_blocks);
for (bb, data) in basic_blocks.iter_enumerated() {
if let Some(term) = &data.terminator {
for &succ in term.successors() {
preds[succ].push(bb);
}
}
}

preds
})
})
Lrc::new(preds)
}))
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1269,7 +1269,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
location: Location,
) -> impl Iterator<Item = Location> + 'a {
if location.statement_index == 0 {
let predecessors = body.predecessors_for(location.block).to_vec();
let predecessors = body.predecessors()[location.block].to_vec();
Either::Left(predecessors.into_iter().map(move |bb| body.terminator_loc(bb)))
} else {
Either::Right(std::iter::once(Location {
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_mir/borrow_check/region_infer/values.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ impl RegionValueElements {
// If this is a basic block head, then the predecessors are
// the terminators of other basic blocks
stack.extend(
body.predecessors_for(block)
body.predecessors()[block]
.iter()
.map(|&pred_bb| body.terminator_loc(pred_bb))
.map(|pred_loc| self.point_from_location(pred_loc)),
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_mir/borrow_check/type_check/liveness/trace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ impl LivenessResults<'me, 'typeck, 'flow, 'tcx> {
}

let body = self.cx.body;
for &pred_block in body.predecessors_for(block).iter() {
for &pred_block in body.predecessors()[block].iter() {
debug!("compute_drop_live_points_for_block: pred_block = {:?}", pred_block,);

// Check whether the variable is (at least partially)
Expand Down
Loading