Skip to content

Commit 603892d

Browse files
self-profile: Switch to new approach for event_id generation that enables query-invocation-specific event_ids.
1 parent 19bd934 commit 603892d

File tree

9 files changed

+254
-104
lines changed

9 files changed

+254
-104
lines changed

Cargo.lock

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2021,9 +2021,9 @@ dependencies = [
20212021

20222022
[[package]]
20232023
name = "measureme"
2024-
version = "0.5.0"
2024+
version = "0.6.0"
20252025
source = "registry+https://github.com/rust-lang/crates.io-index"
2026-
checksum = "c420bbc064623934620b5ab2dc0cf96451b34163329e82f95e7fa1b7b99a6ac8"
2026+
checksum = "36dcc09c1a633097649f7d48bde3d8a61d2a43c01ce75525e31fbbc82c0fccf4"
20272027
dependencies = [
20282028
"byteorder",
20292029
"memmap",

src/librustc/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,6 @@ byteorder = { version = "1.3" }
3737
chalk-engine = { version = "0.9.0", default-features=false }
3838
rustc_fs_util = { path = "../librustc_fs_util" }
3939
smallvec = { version = "1.0", features = ["union", "may_dangle"] }
40-
measureme = "0.5"
40+
measureme = "0.6.0"
4141
rustc_error_codes = { path = "../librustc_error_codes" }
4242
rustc_session = { path = "../librustc_session" }

src/librustc/dep_graph/graph.rs

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,10 @@ use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
33
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
44
use rustc_index::vec::{Idx, IndexVec};
55
use smallvec::SmallVec;
6+
use rustc_data_structures::profiling::QueryInvocationId;
67
use rustc_data_structures::sync::{Lrc, Lock, AtomicU32, AtomicU64, Ordering};
78
use rustc_data_structures::sharded::{self, Sharded};
8-
use std::sync::atomic::Ordering::SeqCst;
9+
use std::sync::atomic::Ordering::Relaxed;
910
use std::env;
1011
use std::hash::Hash;
1112
use std::collections::hash_map::Entry;
@@ -25,6 +26,12 @@ use super::prev::PreviousDepGraph;
2526
#[derive(Clone)]
2627
pub struct DepGraph {
2728
data: Option<Lrc<DepGraphData>>,
29+
30+
/// This field is used for assigning DepNodeIndices when running in
31+
/// non-incremental mode. Even in non-incremental mode we make sure that
32+
/// each task as a `DepNodeIndex` that uniquely identifies it. This unique
33+
/// ID is used for self-profiling.
34+
virtual_dep_node_index: Lrc<AtomicU32>,
2835
}
2936

3037
rustc_index::newtype_index! {
@@ -35,6 +42,13 @@ impl DepNodeIndex {
3542
pub const INVALID: DepNodeIndex = DepNodeIndex::MAX;
3643
}
3744

45+
impl std::convert::From<DepNodeIndex> for QueryInvocationId {
46+
#[inline]
47+
fn from(dep_node_index: DepNodeIndex) -> Self {
48+
QueryInvocationId(dep_node_index.as_u32())
49+
}
50+
}
51+
3852
#[derive(PartialEq)]
3953
pub enum DepNodeColor {
4054
Red,
@@ -103,12 +117,14 @@ impl DepGraph {
103117
previous: prev_graph,
104118
colors: DepNodeColorMap::new(prev_graph_node_count),
105119
})),
120+
virtual_dep_node_index: Lrc::new(AtomicU32::new(0)),
106121
}
107122
}
108123

109124
pub fn new_disabled() -> DepGraph {
110125
DepGraph {
111126
data: None,
127+
virtual_dep_node_index: Lrc::new(AtomicU32::new(0)),
112128
}
113129
}
114130

@@ -319,7 +335,7 @@ impl DepGraph {
319335

320336
(result, dep_node_index)
321337
} else {
322-
(task(cx, arg), DepNodeIndex::INVALID)
338+
(task(cx, arg), self.next_virtual_depnode_index())
323339
}
324340
}
325341

@@ -354,7 +370,7 @@ impl DepGraph {
354370
.complete_anon_task(dep_kind, task_deps);
355371
(result, dep_node_index)
356372
} else {
357-
(op(), DepNodeIndex::INVALID)
373+
(op(), self.next_virtual_depnode_index())
358374
}
359375
}
360376

@@ -877,6 +893,11 @@ impl DepGraph {
877893
}
878894
}
879895
}
896+
897+
fn next_virtual_depnode_index(&self) -> DepNodeIndex {
898+
let index = self.virtual_dep_node_index.fetch_add(1, Relaxed);
899+
DepNodeIndex::from_u32(index)
900+
}
880901
}
881902

882903
/// A "work product" is an intermediate result that we save into the

src/librustc/ty/query/config.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use crate::dep_graph::{DepKind, DepNode};
33
use crate::hir::def_id::{CrateNum, DefId};
44
use crate::ty::TyCtxt;
55
use crate::ty::query::queries;
6-
use crate::ty::query::{Query, QueryName};
6+
use crate::ty::query::{Query};
77
use crate::ty::query::QueryCache;
88
use crate::ty::query::plumbing::CycleError;
99
use rustc_data_structures::profiling::ProfileCategory;
@@ -20,7 +20,7 @@ use crate::ich::StableHashingContext;
2020
// FIXME(eddyb) false positive, the lifetime parameter is used for `Key`/`Value`.
2121
#[allow(unused_lifetimes)]
2222
pub trait QueryConfig<'tcx> {
23-
const NAME: QueryName;
23+
const NAME: &'static str;
2424
const CATEGORY: ProfileCategory;
2525

2626
type Key: Eq + Hash + Clone + Debug;

src/librustc/ty/query/plumbing.rs

Lines changed: 61 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ impl<'a, 'tcx, Q: QueryDescription<'tcx>> JobOwner<'a, 'tcx, Q> {
104104
if let Some((_, value)) =
105105
lock.results.raw_entry().from_key_hashed_nocheck(key_hash, key)
106106
{
107-
tcx.prof.query_cache_hit(Q::NAME);
107+
tcx.prof.query_cache_hit(value.index.into());
108108
let result = (value.value.clone(), value.index);
109109
#[cfg(debug_assertions)]
110110
{
@@ -356,7 +356,7 @@ impl<'tcx> TyCtxt<'tcx> {
356356
#[inline(never)]
357357
pub(super) fn get_query<Q: QueryDescription<'tcx>>(self, span: Span, key: Q::Key) -> Q::Value {
358358
debug!("ty::query::get_query<{}>(key={:?}, span={:?})",
359-
Q::NAME.as_str(),
359+
Q::NAME,
360360
key,
361361
span);
362362

@@ -378,7 +378,7 @@ impl<'tcx> TyCtxt<'tcx> {
378378

379379
if Q::ANON {
380380

381-
let prof_timer = self.prof.query_provider(Q::NAME);
381+
let prof_timer = self.prof.query_provider();
382382

383383
let ((result, dep_node_index), diagnostics) = with_diagnostics(|diagnostics| {
384384
self.start_query(job.job.clone(), diagnostics, |tcx| {
@@ -388,7 +388,7 @@ impl<'tcx> TyCtxt<'tcx> {
388388
})
389389
});
390390

391-
drop(prof_timer);
391+
prof_timer.finish_with_query_invocation_id(dep_node_index.into());
392392

393393
self.dep_graph.read_index(dep_node_index);
394394

@@ -445,8 +445,9 @@ impl<'tcx> TyCtxt<'tcx> {
445445
// First we try to load the result from the on-disk cache.
446446
let result = if Q::cache_on_disk(self, key.clone(), None) &&
447447
self.sess.opts.debugging_opts.incremental_queries {
448-
let _prof_timer = self.prof.incr_cache_loading(Q::NAME);
448+
let prof_timer = self.prof.incr_cache_loading();
449449
let result = Q::try_load_from_disk(self, prev_dep_node_index);
450+
prof_timer.finish_with_query_invocation_id(dep_node_index.into());
450451

451452
// We always expect to find a cached result for things that
452453
// can be forced from `DepNode`.
@@ -465,13 +466,15 @@ impl<'tcx> TyCtxt<'tcx> {
465466
} else {
466467
// We could not load a result from the on-disk cache, so
467468
// recompute.
468-
let _prof_timer = self.prof.query_provider(Q::NAME);
469+
let prof_timer = self.prof.query_provider();
469470

470471
// The dep-graph for this computation is already in-place.
471472
let result = self.dep_graph.with_ignore(|| {
472473
Q::compute(self, key)
473474
});
474475

476+
prof_timer.finish_with_query_invocation_id(dep_node_index.into());
477+
475478
result
476479
};
477480

@@ -534,7 +537,7 @@ impl<'tcx> TyCtxt<'tcx> {
534537
- dep-node: {:?}",
535538
key, dep_node);
536539

537-
let prof_timer = self.prof.query_provider(Q::NAME);
540+
let prof_timer = self.prof.query_provider();
538541

539542
let ((result, dep_node_index), diagnostics) = with_diagnostics(|diagnostics| {
540543
self.start_query(job.job.clone(), diagnostics, |tcx| {
@@ -554,7 +557,7 @@ impl<'tcx> TyCtxt<'tcx> {
554557
})
555558
});
556559

557-
drop(prof_timer);
560+
prof_timer.finish_with_query_invocation_id(dep_node_index.into());
558561

559562
if unlikely!(!diagnostics.is_empty()) {
560563
if dep_node.kind != crate::dep_graph::DepKind::Null {
@@ -586,17 +589,19 @@ impl<'tcx> TyCtxt<'tcx> {
586589

587590
let dep_node = Q::to_dep_node(self, &key);
588591

589-
if self.dep_graph.try_mark_green_and_read(self, &dep_node).is_none() {
590-
// A None return from `try_mark_green_and_read` means that this is either
591-
// a new dep node or that the dep node has already been marked red.
592-
// Either way, we can't call `dep_graph.read()` as we don't have the
593-
// DepNodeIndex. We must invoke the query itself. The performance cost
594-
// this introduces should be negligible as we'll immediately hit the
595-
// in-memory cache, or another query down the line will.
596-
597-
let _ = self.get_query::<Q>(DUMMY_SP, key);
598-
} else {
599-
self.prof.query_cache_hit(Q::NAME);
592+
match self.dep_graph.try_mark_green_and_read(self, &dep_node) {
593+
None => {
594+
// A None return from `try_mark_green_and_read` means that this is either
595+
// a new dep node or that the dep node has already been marked red.
596+
// Either way, we can't call `dep_graph.read()` as we don't have the
597+
// DepNodeIndex. We must invoke the query itself. The performance cost
598+
// this introduces should be negligible as we'll immediately hit the
599+
// in-memory cache, or another query down the line will.
600+
let _ = self.get_query::<Q>(DUMMY_SP, key);
601+
}
602+
Some((_, dep_node_index)) => {
603+
self.prof.query_cache_hit(dep_node_index.into());
604+
}
600605
}
601606
}
602607

@@ -713,6 +718,42 @@ macro_rules! define_queries_inner {
713718
}
714719
}
715720

721+
/// All self-profiling events generated by the query engine use a
722+
/// virtual `StringId`s for their `event_id`. This method makes all
723+
/// those virtual `StringId`s point to actual strings.
724+
///
725+
/// If we are recording only summary data, the ids will point to
726+
/// just the query names. If we are recording query keys too, we
727+
/// allocate the corresponding strings here. (The latter is not yet
728+
/// implemented.)
729+
pub fn allocate_self_profile_query_strings(
730+
&self,
731+
profiler: &rustc_data_structures::profiling::SelfProfiler
732+
) {
733+
// Walk the entire query cache and allocate the appropriate
734+
// string representation. Each cache entry is uniquely
735+
// identified by its dep_node_index.
736+
$({
737+
let query_name_string_id =
738+
profiler.get_or_alloc_cached_string(stringify!($name));
739+
740+
let result_cache = self.$name.lock_shards();
741+
742+
for shard in result_cache.iter() {
743+
let query_invocation_ids = shard
744+
.results
745+
.values()
746+
.map(|v| v.index)
747+
.map(|dep_node_index| dep_node_index.into());
748+
749+
profiler.bulk_map_query_invocation_id_to_single_string(
750+
query_invocation_ids,
751+
query_name_string_id
752+
);
753+
}
754+
})*
755+
}
756+
716757
#[cfg(parallel_compiler)]
717758
pub fn collect_active_jobs(&self) -> Vec<Lrc<QueryJob<$tcx>>> {
718759
let mut jobs = Vec::new();
@@ -830,36 +871,6 @@ macro_rules! define_queries_inner {
830871
}
831872
}
832873

833-
#[allow(nonstandard_style)]
834-
#[derive(Clone, Copy)]
835-
pub enum QueryName {
836-
$($name),*
837-
}
838-
839-
impl rustc_data_structures::profiling::QueryName for QueryName {
840-
fn discriminant(self) -> std::mem::Discriminant<QueryName> {
841-
std::mem::discriminant(&self)
842-
}
843-
844-
fn as_str(self) -> &'static str {
845-
QueryName::as_str(&self)
846-
}
847-
}
848-
849-
impl QueryName {
850-
pub fn register_with_profiler(
851-
profiler: &rustc_data_structures::profiling::SelfProfiler,
852-
) {
853-
$(profiler.register_query_name(QueryName::$name);)*
854-
}
855-
856-
pub fn as_str(&self) -> &'static str {
857-
match self {
858-
$(QueryName::$name => stringify!($name),)*
859-
}
860-
}
861-
}
862-
863874
#[allow(nonstandard_style)]
864875
#[derive(Clone, Debug)]
865876
pub enum Query<$tcx> {
@@ -900,12 +911,6 @@ macro_rules! define_queries_inner {
900911
$(Query::$name(key) => key.default_span(tcx),)*
901912
}
902913
}
903-
904-
pub fn query_name(&self) -> QueryName {
905-
match self {
906-
$(Query::$name(_) => QueryName::$name,)*
907-
}
908-
}
909914
}
910915

911916
impl<'a, $tcx> HashStable<StableHashingContext<'a>> for Query<$tcx> {
@@ -940,7 +945,7 @@ macro_rules! define_queries_inner {
940945
type Key = $K;
941946
type Value = $V;
942947

943-
const NAME: QueryName = QueryName::$name;
948+
const NAME: &'static str = stringify!($name);
944949
const CATEGORY: ProfileCategory = $category;
945950
}
946951

src/librustc_codegen_ssa/base.rs

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -502,7 +502,7 @@ pub fn codegen_crate<B: ExtraBackendMethods>(
502502

503503
ongoing_codegen.codegen_finished(tcx);
504504

505-
assert_and_save_dep_graph(tcx);
505+
finalize_tcx(tcx);
506506

507507
ongoing_codegen.check_for_errors(tcx.sess);
508508

@@ -647,7 +647,8 @@ pub fn codegen_crate<B: ExtraBackendMethods>(
647647

648648
ongoing_codegen.check_for_errors(tcx.sess);
649649

650-
assert_and_save_dep_graph(tcx);
650+
finalize_tcx(tcx);
651+
651652
ongoing_codegen.into_inner()
652653
}
653654

@@ -698,14 +699,22 @@ impl<B: ExtraBackendMethods> Drop for AbortCodegenOnDrop<B> {
698699
}
699700
}
700701

701-
fn assert_and_save_dep_graph(tcx: TyCtxt<'_>) {
702+
fn finalize_tcx(tcx: TyCtxt<'_>) {
702703
time(tcx.sess,
703704
"assert dep graph",
704705
|| ::rustc_incremental::assert_dep_graph(tcx));
705706

706707
time(tcx.sess,
707708
"serialize dep graph",
708709
|| ::rustc_incremental::save_dep_graph(tcx));
710+
711+
// We assume that no queries are run past here. If there are new queries
712+
// after this point, they'll show up as "<unknown>" in self-profiling data.
713+
tcx.prof.with_profiler(|profiler| {
714+
let _prof_timer =
715+
tcx.prof.generic_activity("self_profile_alloc_query_strings");
716+
tcx.queries.allocate_self_profile_query_strings(profiler);
717+
});
709718
}
710719

711720
impl CrateInfo {

src/librustc_data_structures/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ rustc-hash = "1.0.1"
2626
smallvec = { version = "1.0", features = ["union", "may_dangle"] }
2727
rustc_index = { path = "../librustc_index", package = "rustc_index" }
2828
bitflags = "1.2.1"
29-
measureme = "0.5"
29+
measureme = "0.6.0"
3030

3131
[dependencies.parking_lot]
3232
version = "0.9"

0 commit comments

Comments
 (0)