1 use errors::{Diagnostic, DiagnosticBuilder};
2 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
3 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
4 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
5 use smallvec::SmallVec;
6 use rustc_data_structures::sync::{Lrc, Lock, AtomicU32, Ordering};
9 use std::collections::hash_map::Entry;
10 use crate::ty::{self, TyCtxt};
11 use crate::util::common::{ProfileQueriesMsg, profq_msg};
12 use parking_lot::{Mutex, Condvar};
14 use crate::ich::{StableHashingContext, StableHashingContextProvider, Fingerprint};
16 use super::debug::EdgeFilter;
17 use super::dep_node::{DepNode, DepKind, WorkProductId};
18 use super::query::DepGraphQuery;
19 use super::safe::DepGraphSafe;
20 use super::serialized::{SerializedDepGraph, SerializedDepNodeIndex};
21 use super::prev::PreviousDepGraph;
25 data: Option<Lrc<DepGraphData>>,
29 pub struct DepNodeIndex { .. }
33 const INVALID: DepNodeIndex = DepNodeIndex::MAX;
36 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
37 pub enum DepNodeColor {
43 pub fn is_green(self) -> bool {
45 DepNodeColor::Red => false,
46 DepNodeColor::Green(_) => true,
52 /// The new encoding of the dependency graph, optimized for red/green
53 /// tracking. The `current` field is the dependency graph of only the
54 /// current compilation session: We don't merge the previous dep-graph into
55 /// current one anymore.
56 current: Lock<CurrentDepGraph>,
58 /// The dep-graph from the previous compilation session. It contains all
59 /// nodes and edges as well as all fingerprints of nodes that have them.
60 previous: PreviousDepGraph,
62 colors: DepNodeColorMap,
64 /// A set of loaded diagnostics that have been emitted.
65 emitted_diagnostics: Mutex<FxHashSet<DepNodeIndex>>,
67 /// Used to wait for diagnostics to be emitted.
68 emitted_diagnostics_cond_var: Condvar,
70 /// When we load, there may be `.o` files, cached MIR, or other such
71 /// things available to us. If we find that they are not dirty, we
72 /// load the path to the file storing those work-products here into
73 /// this map. We can later look for and extract that data.
74 previous_work_products: FxHashMap<WorkProductId, WorkProduct>,
76 dep_node_debug: Lock<FxHashMap<DepNode, String>>,
78 // Used for testing, only populated when -Zquery-dep-graph is specified.
79 loaded_from_cache: Lock<FxHashMap<DepNodeIndex, bool>>,
82 pub fn hash_result<R>(hcx: &mut StableHashingContext<'_>, result: &R) -> Option<Fingerprint>
84 R: for<'a> HashStable<StableHashingContext<'a>>,
86 let mut stable_hasher = StableHasher::new();
87 result.hash_stable(hcx, &mut stable_hasher);
89 Some(stable_hasher.finish())
94 pub fn new(prev_graph: PreviousDepGraph,
95 prev_work_products: FxHashMap<WorkProductId, WorkProduct>) -> DepGraph {
96 let prev_graph_node_count = prev_graph.node_count();
99 data: Some(Lrc::new(DepGraphData {
100 previous_work_products: prev_work_products,
101 dep_node_debug: Default::default(),
102 current: Lock::new(CurrentDepGraph::new(prev_graph_node_count)),
103 emitted_diagnostics: Default::default(),
104 emitted_diagnostics_cond_var: Condvar::new(),
105 previous: prev_graph,
106 colors: DepNodeColorMap::new(prev_graph_node_count),
107 loaded_from_cache: Default::default(),
112 pub fn new_disabled() -> DepGraph {
118 /// Returns `true` if we are actually building the full dep-graph, and `false` otherwise.
120 pub fn is_fully_enabled(&self) -> bool {
124 pub fn query(&self) -> DepGraphQuery {
125 let current_dep_graph = self.data.as_ref().unwrap().current.borrow();
126 let nodes: Vec<_> = current_dep_graph.data.iter().map(|n| n.node).collect();
127 let mut edges = Vec::new();
128 for (from, edge_targets) in current_dep_graph.data.iter()
129 .map(|d| (d.node, &d.edges)) {
130 for &edge_target in edge_targets.iter() {
131 let to = current_dep_graph.data[edge_target].node;
132 edges.push((from, to));
136 DepGraphQuery::new(&nodes[..], &edges[..])
139 pub fn assert_ignored(&self)
141 if let Some(..) = self.data {
142 ty::tls::with_context_opt(|icx| {
143 let icx = if let Some(icx) = icx { icx } else { return };
144 assert!(icx.task_deps.is_none(), "expected no task dependency tracking");
149 pub fn with_ignore<OP,R>(&self, op: OP) -> R
150 where OP: FnOnce() -> R
152 ty::tls::with_context(|icx| {
153 let icx = ty::tls::ImplicitCtxt {
158 ty::tls::enter_context(&icx, |_| {
164 /// Starts a new dep-graph task. Dep-graph tasks are specified
165 /// using a free function (`task`) and **not** a closure -- this
166 /// is intentional because we want to exercise tight control over
167 /// what state they have access to. In particular, we want to
168 /// prevent implicit 'leaks' of tracked state into the task (which
169 /// could then be read without generating correct edges in the
170 /// dep-graph -- see the [rustc guide] for more details on
171 /// the dep-graph). To this end, the task function gets exactly two
172 /// pieces of state: the context `cx` and an argument `arg`. Both
173 /// of these bits of state must be of some type that implements
174 /// `DepGraphSafe` and hence does not leak.
176 /// The choice of two arguments is not fundamental. One argument
177 /// would work just as well, since multiple values can be
178 /// collected using tuples. However, using two arguments works out
179 /// to be quite convenient, since it is common to need a context
180 /// (`cx`) and some argument (e.g., a `DefId` identifying what
181 /// item to process).
183 /// For cases where you need some other number of arguments:
185 /// - If you only need one argument, just use `()` for the `arg`
187 /// - If you need 3+ arguments, use a tuple for the
190 /// [rustc guide]: https://rust-lang.github.io/rustc-guide/incremental-compilation.html
191 pub fn with_task<'a, C, A, R>(
197 hash_result: impl FnOnce(&mut StableHashingContext<'_>, &R) -> Option<Fingerprint>,
198 ) -> (R, DepNodeIndex)
200 C: DepGraphSafe + StableHashingContextProvider<'a>,
202 self.with_task_impl(key, cx, arg, false, task,
203 |_key| Some(TaskDeps {
204 #[cfg(debug_assertions)]
206 reads: SmallVec::new(),
207 read_set: Default::default(),
209 |data, key, fingerprint, task| {
210 data.borrow_mut().complete_task(key, task.unwrap(), fingerprint)
215 /// Creates a new dep-graph input with value `input`
216 pub fn input_task<'a, C, R>(&self,
221 where C: DepGraphSafe + StableHashingContextProvider<'a>,
222 R: for<'b> HashStable<StableHashingContext<'b>>,
224 fn identity_fn<C, A>(_: C, arg: A) -> A {
228 self.with_task_impl(key, cx, input, true, identity_fn,
230 |data, key, fingerprint, _| {
231 data.borrow_mut().alloc_node(key, SmallVec::new(), fingerprint)
236 fn with_task_impl<'a, C, A, R>(
243 create_task: fn(DepNode) -> Option<TaskDeps>,
244 finish_task_and_alloc_depnode: fn(&Lock<CurrentDepGraph>,
247 Option<TaskDeps>) -> DepNodeIndex,
248 hash_result: impl FnOnce(&mut StableHashingContext<'_>, &R) -> Option<Fingerprint>,
249 ) -> (R, DepNodeIndex)
251 C: DepGraphSafe + StableHashingContextProvider<'a>,
253 if let Some(ref data) = self.data {
254 let task_deps = create_task(key).map(|deps| Lock::new(deps));
256 // In incremental mode, hash the result of the task. We don't
257 // do anything with the hash yet, but we are computing it
259 // - we make sure that the infrastructure works and
260 // - we can get an idea of the runtime cost.
261 let mut hcx = cx.get_stable_hashing_context();
263 if cfg!(debug_assertions) {
264 profq_msg(hcx.sess(), ProfileQueriesMsg::TaskBegin(key.clone()))
267 let result = if no_tcx {
270 ty::tls::with_context(|icx| {
271 let icx = ty::tls::ImplicitCtxt {
272 task_deps: task_deps.as_ref(),
276 ty::tls::enter_context(&icx, |_| {
282 if cfg!(debug_assertions) {
283 profq_msg(hcx.sess(), ProfileQueriesMsg::TaskEnd)
286 let current_fingerprint = hash_result(&mut hcx, &result);
288 let dep_node_index = finish_task_and_alloc_depnode(
291 current_fingerprint.unwrap_or(Fingerprint::ZERO),
292 task_deps.map(|lock| lock.into_inner()),
295 let print_status = cfg!(debug_assertions) && hcx.sess().opts.debugging_opts.dep_tasks;
297 // Determine the color of the new DepNode.
298 if let Some(prev_index) = data.previous.node_to_index_opt(&key) {
299 let prev_fingerprint = data.previous.fingerprint_by_index(prev_index);
301 let color = if let Some(current_fingerprint) = current_fingerprint {
302 if current_fingerprint == prev_fingerprint {
304 eprintln!("[task::green] {:?}", key);
306 DepNodeColor::Green(dep_node_index)
309 eprintln!("[task::red] {:?}", key);
315 eprintln!("[task::unknown] {:?}", key);
317 // Mark the node as Red if we can't hash the result
321 debug_assert!(data.colors.get(prev_index).is_none(),
322 "DepGraph::with_task() - Duplicate DepNodeColor \
323 insertion for {:?}", key);
325 data.colors.insert(prev_index, color);
328 eprintln!("[task::new] {:?}", key);
332 (result, dep_node_index)
334 (task(cx, arg), DepNodeIndex::INVALID)
338 /// Executes something within an "anonymous" task, that is, a task the
339 /// `DepNode` of which is determined by the list of inputs it read from.
340 pub fn with_anon_task<OP,R>(&self, dep_kind: DepKind, op: OP) -> (R, DepNodeIndex)
341 where OP: FnOnce() -> R
343 if let Some(ref data) = self.data {
344 let (result, task_deps) = ty::tls::with_context(|icx| {
345 let task_deps = Lock::new(TaskDeps {
346 #[cfg(debug_assertions)]
348 reads: SmallVec::new(),
349 read_set: Default::default(),
353 let icx = ty::tls::ImplicitCtxt {
354 task_deps: Some(&task_deps),
358 ty::tls::enter_context(&icx, |_| {
363 (r, task_deps.into_inner())
365 let dep_node_index = data.current
367 .complete_anon_task(dep_kind, task_deps);
368 (result, dep_node_index)
370 (op(), DepNodeIndex::INVALID)
374 /// Executes something within an "eval-always" task which is a task
375 /// that runs whenever anything changes.
376 pub fn with_eval_always_task<'a, C, A, R>(
382 hash_result: impl FnOnce(&mut StableHashingContext<'_>, &R) -> Option<Fingerprint>,
383 ) -> (R, DepNodeIndex)
385 C: DepGraphSafe + StableHashingContextProvider<'a>,
387 self.with_task_impl(key, cx, arg, false, task,
389 |data, key, fingerprint, _| {
390 let mut current = data.borrow_mut();
391 current.alloc_node(key, smallvec![], fingerprint)
397 pub fn read(&self, v: DepNode) {
398 if let Some(ref data) = self.data {
399 let current = data.current.borrow_mut();
400 if let Some(&dep_node_index) = current.node_to_node_index.get(&v) {
401 std::mem::drop(current);
402 data.read_index(dep_node_index);
404 bug!("DepKind {:?} should be pre-allocated but isn't.", v.kind)
410 pub fn read_index(&self, dep_node_index: DepNodeIndex) {
411 if let Some(ref data) = self.data {
412 data.read_index(dep_node_index);
417 pub fn dep_node_index_of(&self, dep_node: &DepNode) -> DepNodeIndex {
430 pub fn dep_node_exists(&self, dep_node: &DepNode) -> bool {
431 if let Some(ref data) = self.data {
432 data.current.borrow_mut().node_to_node_index.contains_key(dep_node)
439 pub fn fingerprint_of(&self, dep_node_index: DepNodeIndex) -> Fingerprint {
440 let current = self.data.as_ref().expect("dep graph enabled").current.borrow_mut();
441 current.data[dep_node_index].fingerprint
444 pub fn prev_fingerprint_of(&self, dep_node: &DepNode) -> Option<Fingerprint> {
445 self.data.as_ref().unwrap().previous.fingerprint_of(dep_node)
449 pub fn prev_dep_node_index_of(&self, dep_node: &DepNode) -> SerializedDepNodeIndex {
450 self.data.as_ref().unwrap().previous.node_to_index(dep_node)
453 /// Checks whether a previous work product exists for `v` and, if
454 /// so, return the path that leads to it. Used to skip doing work.
455 pub fn previous_work_product(&self, v: &WorkProductId) -> Option<WorkProduct> {
459 data.previous_work_products.get(v).cloned()
463 /// Access the map of work-products created during the cached run. Only
464 /// used during saving of the dep-graph.
465 pub fn previous_work_products(&self) -> &FxHashMap<WorkProductId, WorkProduct> {
466 &self.data.as_ref().unwrap().previous_work_products
470 pub fn register_dep_node_debug_str<F>(&self,
473 where F: FnOnce() -> String
475 let dep_node_debug = &self.data.as_ref().unwrap().dep_node_debug;
477 if dep_node_debug.borrow().contains_key(&dep_node) {
480 let debug_str = debug_str_gen();
481 dep_node_debug.borrow_mut().insert(dep_node, debug_str);
484 pub(super) fn dep_node_debug_str(&self, dep_node: DepNode) -> Option<String> {
493 pub fn edge_deduplication_data(&self) -> Option<(u64, u64)> {
494 if cfg!(debug_assertions) {
495 let current_dep_graph = self.data.as_ref().unwrap().current.borrow();
497 Some((current_dep_graph.total_read_count,
498 current_dep_graph.total_duplicate_read_count))
504 pub fn serialize(&self) -> SerializedDepGraph {
505 let current_dep_graph = self.data.as_ref().unwrap().current.borrow();
507 let fingerprints: IndexVec<SerializedDepNodeIndex, _> =
508 current_dep_graph.data.iter().map(|d| d.fingerprint).collect();
509 let nodes: IndexVec<SerializedDepNodeIndex, _> =
510 current_dep_graph.data.iter().map(|d| d.node).collect();
512 let total_edge_count: usize = current_dep_graph.data.iter()
513 .map(|d| d.edges.len())
516 let mut edge_list_indices = IndexVec::with_capacity(nodes.len());
517 let mut edge_list_data = Vec::with_capacity(total_edge_count);
519 for (current_dep_node_index, edges) in current_dep_graph.data.iter_enumerated()
520 .map(|(i, d)| (i, &d.edges)) {
521 let start = edge_list_data.len() as u32;
522 // This should really just be a memcpy :/
523 edge_list_data.extend(edges.iter().map(|i| SerializedDepNodeIndex::new(i.index())));
524 let end = edge_list_data.len() as u32;
526 debug_assert_eq!(current_dep_node_index.index(), edge_list_indices.len());
527 edge_list_indices.push((start, end));
530 debug_assert!(edge_list_data.len() <= ::std::u32::MAX as usize);
531 debug_assert_eq!(edge_list_data.len(), total_edge_count);
541 pub fn node_color(&self, dep_node: &DepNode) -> Option<DepNodeColor> {
542 if let Some(ref data) = self.data {
543 if let Some(prev_index) = data.previous.node_to_index_opt(dep_node) {
544 return data.colors.get(prev_index)
546 // This is a node that did not exist in the previous compilation
547 // session, so we consider it to be red.
548 return Some(DepNodeColor::Red)
555 /// Try to read a node index for the node dep_node.
556 /// A node will have an index, when it's already been marked green, or when we can mark it
557 /// green. This function will mark the current task as a reader of the specified node, when
558 /// a node index can be found for that node.
559 pub fn try_mark_green_and_read(
561 tcx: TyCtxt<'_, '_, '_>,
563 ) -> Option<(SerializedDepNodeIndex, DepNodeIndex)> {
564 self.try_mark_green(tcx, dep_node).map(|(prev_index, dep_node_index)| {
565 debug_assert!(self.is_green(&dep_node));
566 self.read_index(dep_node_index);
567 (prev_index, dep_node_index)
571 pub fn try_mark_green(
573 tcx: TyCtxt<'_, '_, '_>,
575 ) -> Option<(SerializedDepNodeIndex, DepNodeIndex)> {
576 debug_assert!(!dep_node.kind.is_eval_always());
578 // Return None if the dep graph is disabled
579 let data = self.data.as_ref()?;
581 // Return None if the dep node didn't exist in the previous session
582 let prev_index = data.previous.node_to_index_opt(dep_node)?;
584 match data.colors.get(prev_index) {
585 Some(DepNodeColor::Green(dep_node_index)) => Some((prev_index, dep_node_index)),
586 Some(DepNodeColor::Red) => None,
588 // This DepNode and the corresponding query invocation existed
589 // in the previous compilation session too, so we can try to
590 // mark it as green by recursively marking all of its
591 // dependencies green.
592 self.try_mark_previous_green(
597 ).map(|dep_node_index| {
598 (prev_index, dep_node_index)
604 /// Try to mark a dep-node which existed in the previous compilation session as green.
605 fn try_mark_previous_green<'tcx>(
607 tcx: TyCtxt<'_, 'tcx, 'tcx>,
609 prev_dep_node_index: SerializedDepNodeIndex,
611 ) -> Option<DepNodeIndex> {
612 debug!("try_mark_previous_green({:?}) - BEGIN", dep_node);
614 #[cfg(not(parallel_compiler))]
616 debug_assert!(!data.current.borrow().node_to_node_index.contains_key(dep_node));
617 debug_assert!(data.colors.get(prev_dep_node_index).is_none());
620 // We never try to mark eval_always nodes as green
621 debug_assert!(!dep_node.kind.is_eval_always());
623 debug_assert_eq!(data.previous.index_to_node(prev_dep_node_index), *dep_node);
625 let prev_deps = data.previous.edge_targets_from(prev_dep_node_index);
627 let mut current_deps = SmallVec::new();
629 for &dep_dep_node_index in prev_deps {
630 let dep_dep_node_color = data.colors.get(dep_dep_node_index);
632 match dep_dep_node_color {
633 Some(DepNodeColor::Green(node_index)) => {
634 // This dependency has been marked as green before, we are
635 // still fine and can continue with checking the other
637 debug!("try_mark_previous_green({:?}) --- found dependency {:?} to \
638 be immediately green",
640 data.previous.index_to_node(dep_dep_node_index));
641 current_deps.push(node_index);
643 Some(DepNodeColor::Red) => {
644 // We found a dependency the value of which has changed
645 // compared to the previous compilation session. We cannot
646 // mark the DepNode as green and also don't need to bother
647 // with checking any of the other dependencies.
648 debug!("try_mark_previous_green({:?}) - END - dependency {:?} was \
651 data.previous.index_to_node(dep_dep_node_index));
655 let dep_dep_node = &data.previous.index_to_node(dep_dep_node_index);
657 // We don't know the state of this dependency. If it isn't
658 // an eval_always node, let's try to mark it green recursively.
659 if !dep_dep_node.kind.is_eval_always() {
660 debug!("try_mark_previous_green({:?}) --- state of dependency {:?} \
661 is unknown, trying to mark it green", dep_node,
664 let node_index = self.try_mark_previous_green(
670 if let Some(node_index) = node_index {
671 debug!("try_mark_previous_green({:?}) --- managed to MARK \
672 dependency {:?} as green", dep_node, dep_dep_node);
673 current_deps.push(node_index);
677 match dep_dep_node.kind {
680 DepKind::CrateMetadata => {
681 if dep_dep_node.extract_def_id(tcx).is_none() {
682 // If the node does not exist anymore, we
683 // just fail to mark green.
686 // If the node does exist, it should have
687 // been pre-allocated.
688 bug!("DepNode {:?} should have been \
689 pre-allocated but wasn't.",
694 // For other kinds of nodes it's OK to be
700 // We failed to mark it green, so we try to force the query.
701 debug!("try_mark_previous_green({:?}) --- trying to force \
702 dependency {:?}", dep_node, dep_dep_node);
703 if crate::ty::query::force_from_dep_node(tcx, dep_dep_node) {
704 let dep_dep_node_color = data.colors.get(dep_dep_node_index);
706 match dep_dep_node_color {
707 Some(DepNodeColor::Green(node_index)) => {
708 debug!("try_mark_previous_green({:?}) --- managed to \
709 FORCE dependency {:?} to green",
710 dep_node, dep_dep_node);
711 current_deps.push(node_index);
713 Some(DepNodeColor::Red) => {
714 debug!("try_mark_previous_green({:?}) - END - \
715 dependency {:?} was red after forcing",
721 if !tcx.sess.has_errors() {
722 bug!("try_mark_previous_green() - Forcing the DepNode \
723 should have set its color")
725 // If the query we just forced has resulted
726 // in some kind of compilation error, we
727 // don't expect that the corresponding
728 // dep-node color has been updated.
733 // The DepNode could not be forced.
734 debug!("try_mark_previous_green({:?}) - END - dependency {:?} \
735 could not be forced", dep_node, dep_dep_node);
742 // If we got here without hitting a `return` that means that all
743 // dependencies of this DepNode could be marked as green. Therefore we
744 // can also mark this DepNode as green.
746 // There may be multiple threads trying to mark the same dep node green concurrently
748 let (dep_node_index, did_allocation) = {
749 let mut current = data.current.borrow_mut();
751 // Copy the fingerprint from the previous graph,
752 // so we don't have to recompute it
753 let fingerprint = data.previous.fingerprint_by_index(prev_dep_node_index);
755 // We allocating an entry for the node in the current dependency graph and
756 // adding all the appropriate edges imported from the previous graph
757 current.intern_node(*dep_node, current_deps, fingerprint)
760 // ... emitting any stored diagnostic ...
762 let diagnostics = tcx.queries.on_disk_cache
763 .load_diagnostics(tcx, prev_dep_node_index);
765 if unlikely!(diagnostics.len() > 0) {
766 self.emit_diagnostics(
775 // ... and finally storing a "Green" entry in the color map.
776 // Multiple threads can all write the same color here
777 #[cfg(not(parallel_compiler))]
778 debug_assert!(data.colors.get(prev_dep_node_index).is_none(),
779 "DepGraph::try_mark_previous_green() - Duplicate DepNodeColor \
780 insertion for {:?}", dep_node);
782 data.colors.insert(prev_dep_node_index, DepNodeColor::Green(dep_node_index));
784 debug!("try_mark_previous_green({:?}) - END - successfully marked as green", dep_node);
788 /// Atomically emits some loaded diagnotics, assuming that this only gets called with
789 /// `did_allocation` set to `true` on a single thread.
792 fn emit_diagnostics<'tcx>(
794 tcx: TyCtxt<'_, 'tcx, 'tcx>,
796 dep_node_index: DepNodeIndex,
797 did_allocation: bool,
798 diagnostics: Vec<Diagnostic>,
800 if did_allocation || !cfg!(parallel_compiler) {
801 // Only the thread which did the allocation emits the error messages
802 let handle = tcx.sess.diagnostic();
804 // Promote the previous diagnostics to the current session.
805 tcx.queries.on_disk_cache
806 .store_diagnostics(dep_node_index, diagnostics.clone().into());
808 for diagnostic in diagnostics {
809 DiagnosticBuilder::new_diagnostic(handle, diagnostic).emit();
812 #[cfg(parallel_compiler)]
814 // Mark the diagnostics and emitted and wake up waiters
815 data.emitted_diagnostics.lock().insert(dep_node_index);
816 data.emitted_diagnostics_cond_var.notify_all();
819 // The other threads will wait for the diagnostics to be emitted
821 let mut emitted_diagnostics = data.emitted_diagnostics.lock();
823 if emitted_diagnostics.contains(&dep_node_index) {
826 data.emitted_diagnostics_cond_var.wait(&mut emitted_diagnostics);
831 // Returns true if the given node has been marked as green during the
832 // current compilation session. Used in various assertions
833 pub fn is_green(&self, dep_node: &DepNode) -> bool {
834 self.node_color(dep_node).map(|c| c.is_green()).unwrap_or(false)
837 // This method loads all on-disk cacheable query results into memory, so
838 // they can be written out to the new cache file again. Most query results
839 // will already be in memory but in the case where we marked something as
840 // green but then did not need the value, that value will never have been
843 // This method will only load queries that will end up in the disk cache.
844 // Other queries will not be executed.
845 pub fn exec_cache_promotions<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) {
846 let green_nodes: Vec<DepNode> = {
847 let data = self.data.as_ref().unwrap();
848 data.colors.values.indices().filter_map(|prev_index| {
849 match data.colors.get(prev_index) {
850 Some(DepNodeColor::Green(_)) => {
851 let dep_node = data.previous.index_to_node(prev_index);
852 if dep_node.cache_on_disk(tcx) {
859 Some(DepNodeColor::Red) => {
860 // We can skip red nodes because a node can only be marked
861 // as red if the query result was recomputed and thus is
862 // already in memory.
869 for dep_node in green_nodes {
870 dep_node.load_from_on_disk_cache(tcx);
874 pub fn mark_loaded_from_cache(&self, dep_node_index: DepNodeIndex, state: bool) {
875 debug!("mark_loaded_from_cache({:?}, {})",
876 self.data.as_ref().unwrap().current.borrow().data[dep_node_index].node,
884 .insert(dep_node_index, state);
887 pub fn was_loaded_from_cache(&self, dep_node: &DepNode) -> Option<bool> {
888 let data = self.data.as_ref().unwrap();
889 let dep_node_index = data.current.borrow().node_to_node_index[dep_node];
890 data.loaded_from_cache.borrow().get(&dep_node_index).cloned()
894 /// A "work product" is an intermediate result that we save into the
895 /// incremental directory for later re-use. The primary example are
896 /// the object files that we save for each partition at code
899 /// Each work product is associated with a dep-node, representing the
900 /// process that produced the work-product. If that dep-node is found
901 /// to be dirty when we load up, then we will delete the work-product
902 /// at load time. If the work-product is found to be clean, then we
903 /// will keep a record in the `previous_work_products` list.
905 /// In addition, work products have an associated hash. This hash is
906 /// an extra hash that can be used to decide if the work-product from
907 /// a previous compilation can be re-used (in addition to the dirty
910 /// As the primary example, consider the object files we generate for
911 /// each partition. In the first run, we create partitions based on
912 /// the symbols that need to be compiled. For each partition P, we
913 /// hash the symbols in P and create a `WorkProduct` record associated
914 /// with `DepNode::CodegenUnit(P)`; the hash is the set of symbols
917 /// The next time we compile, if the `DepNode::CodegenUnit(P)` is
918 /// judged to be clean (which means none of the things we read to
919 /// generate the partition were found to be dirty), it will be loaded
920 /// into previous work products. We will then regenerate the set of
921 /// symbols in the partition P and hash them (note that new symbols
922 /// may be added -- for example, new monomorphizations -- even if
923 /// nothing in P changed!). We will compare that hash against the
924 /// previous hash. If it matches up, we can reuse the object file.
925 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
926 pub struct WorkProduct {
927 pub cgu_name: String,
928 /// Saved files associated with this CGU.
929 pub saved_files: Vec<(WorkProductFileKind, String)>,
932 #[derive(Clone, Copy, Debug, RustcEncodable, RustcDecodable, PartialEq)]
933 pub enum WorkProductFileKind {
942 edges: SmallVec<[DepNodeIndex; 8]>,
943 fingerprint: Fingerprint,
946 pub(super) struct CurrentDepGraph {
947 data: IndexVec<DepNodeIndex, DepNodeData>,
948 node_to_node_index: FxHashMap<DepNode, DepNodeIndex>,
950 forbidden_edge: Option<EdgeFilter>,
952 /// Anonymous `DepNode`s are nodes whose IDs we compute from the list of
953 /// their edges. This has the beneficial side-effect that multiple anonymous
954 /// nodes can be coalesced into one without changing the semantics of the
955 /// dependency graph. However, the merging of nodes can lead to a subtle
956 /// problem during red-green marking: The color of an anonymous node from
957 /// the current session might "shadow" the color of the node with the same
958 /// ID from the previous session. In order to side-step this problem, we make
959 /// sure that anonymous `NodeId`s allocated in different sessions don't overlap.
960 /// This is implemented by mixing a session-key into the ID fingerprint of
961 /// each anon node. The session-key is just a random number generated when
962 /// the `DepGraph` is created.
963 anon_id_seed: Fingerprint,
965 total_read_count: u64,
966 total_duplicate_read_count: u64,
969 impl CurrentDepGraph {
970 fn new(prev_graph_node_count: usize) -> CurrentDepGraph {
971 use std::time::{SystemTime, UNIX_EPOCH};
973 let duration = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
974 let nanos = duration.as_secs() * 1_000_000_000 +
975 duration.subsec_nanos() as u64;
976 let mut stable_hasher = StableHasher::new();
977 nanos.hash(&mut stable_hasher);
979 let forbidden_edge = if cfg!(debug_assertions) {
980 match env::var("RUST_FORBID_DEP_GRAPH_EDGE") {
982 match EdgeFilter::new(&s) {
984 Err(err) => bug!("RUST_FORBID_DEP_GRAPH_EDGE invalid: {}", err),
993 // Pre-allocate the dep node structures. We over-allocate a little so
994 // that we hopefully don't have to re-allocate during this compilation
996 let new_node_count_estimate = (prev_graph_node_count * 115) / 100;
999 data: IndexVec::with_capacity(new_node_count_estimate),
1000 node_to_node_index: FxHashMap::with_capacity_and_hasher(
1001 new_node_count_estimate,
1004 anon_id_seed: stable_hasher.finish(),
1006 total_read_count: 0,
1007 total_duplicate_read_count: 0,
1014 task_deps: TaskDeps,
1015 fingerprint: Fingerprint
1017 self.alloc_node(node, task_deps.reads, fingerprint)
1020 fn complete_anon_task(&mut self, kind: DepKind, task_deps: TaskDeps) -> DepNodeIndex {
1021 debug_assert!(!kind.is_eval_always());
1023 let mut fingerprint = self.anon_id_seed;
1024 let mut hasher = StableHasher::new();
1026 for &read in task_deps.reads.iter() {
1027 let read_dep_node = self.data[read].node;
1029 ::std::mem::discriminant(&read_dep_node.kind).hash(&mut hasher);
1031 // Fingerprint::combine() is faster than sending Fingerprint
1032 // through the StableHasher (at least as long as StableHasher
1034 fingerprint = fingerprint.combine(read_dep_node.hash);
1037 fingerprint = fingerprint.combine(hasher.finish());
1039 let target_dep_node = DepNode {
1044 self.intern_node(target_dep_node, task_deps.reads, Fingerprint::ZERO).0
1050 edges: SmallVec<[DepNodeIndex; 8]>,
1051 fingerprint: Fingerprint
1053 debug_assert!(!self.node_to_node_index.contains_key(&dep_node));
1054 self.intern_node(dep_node, edges, fingerprint).0
1060 edges: SmallVec<[DepNodeIndex; 8]>,
1061 fingerprint: Fingerprint
1062 ) -> (DepNodeIndex, bool) {
1063 debug_assert_eq!(self.node_to_node_index.len(), self.data.len());
1065 match self.node_to_node_index.entry(dep_node) {
1066 Entry::Occupied(entry) => (*entry.get(), false),
1067 Entry::Vacant(entry) => {
1068 let dep_node_index = DepNodeIndex::new(self.data.len());
1069 self.data.push(DepNodeData {
1074 entry.insert(dep_node_index);
1075 (dep_node_index, true)
1082 fn read_index(&self, source: DepNodeIndex) {
1083 ty::tls::with_context_opt(|icx| {
1084 let icx = if let Some(icx) = icx { icx } else { return };
1085 if let Some(task_deps) = icx.task_deps {
1086 let mut task_deps = task_deps.lock();
1087 if cfg!(debug_assertions) {
1088 self.current.lock().total_read_count += 1;
1090 if task_deps.read_set.insert(source) {
1091 task_deps.reads.push(source);
1093 #[cfg(debug_assertions)]
1095 if let Some(target) = task_deps.node {
1096 let graph = self.current.lock();
1097 if let Some(ref forbidden_edge) = graph.forbidden_edge {
1098 let source = graph.data[source].node;
1099 if forbidden_edge.test(&source, &target) {
1100 bug!("forbidden edge {:?} -> {:?} created",
1107 } else if cfg!(debug_assertions) {
1108 self.current.lock().total_duplicate_read_count += 1;
1115 pub struct TaskDeps {
1116 #[cfg(debug_assertions)]
1117 node: Option<DepNode>,
1118 reads: SmallVec<[DepNodeIndex; 8]>,
1119 read_set: FxHashSet<DepNodeIndex>,
1122 // A data structure that stores Option<DepNodeColor> values as a contiguous
1123 // array, using one u32 per entry.
1124 struct DepNodeColorMap {
1125 values: IndexVec<SerializedDepNodeIndex, AtomicU32>,
1128 const COMPRESSED_NONE: u32 = 0;
1129 const COMPRESSED_RED: u32 = 1;
1130 const COMPRESSED_FIRST_GREEN: u32 = 2;
1132 impl DepNodeColorMap {
1133 fn new(size: usize) -> DepNodeColorMap {
1135 values: (0..size).map(|_| AtomicU32::new(COMPRESSED_NONE)).collect(),
1139 fn get(&self, index: SerializedDepNodeIndex) -> Option<DepNodeColor> {
1140 match self.values[index].load(Ordering::Acquire) {
1141 COMPRESSED_NONE => None,
1142 COMPRESSED_RED => Some(DepNodeColor::Red),
1143 value => Some(DepNodeColor::Green(DepNodeIndex::from_u32(
1144 value - COMPRESSED_FIRST_GREEN
1149 fn insert(&self, index: SerializedDepNodeIndex, color: DepNodeColor) {
1150 self.values[index].store(match color {
1151 DepNodeColor::Red => COMPRESSED_RED,
1152 DepNodeColor::Green(index) => index.as_u32() + COMPRESSED_FIRST_GREEN,
1153 }, Ordering::Release)