-
-
Notifications
You must be signed in to change notification settings - Fork 15.5k
Resolver: Parallelize the import resolution loop #158845
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
Open
LorrensP-2158466
wants to merge
3
commits into
rust-lang:main
Choose a base branch
from
LorrensP-2158466:parallel-import-resolution
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -24,7 +24,7 @@ | |
| use std::cell::RefMut; | ||
| use std::collections::BTreeSet; | ||
| use std::ops::ControlFlow; | ||
| use std::sync::{Arc, OnceLock}; | ||
| use std::sync::{Arc, Mutex, OnceLock}; | ||
| use std::{fmt, mem}; | ||
|
|
||
| use diagnostics::{ParamKindInEnumDiscriminant, ParamKindInNonTrivialAnonConst}; | ||
|
|
@@ -46,7 +46,7 @@ use rustc_ast::{ | |
| use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet, default}; | ||
| use rustc_data_structures::intern::Interned; | ||
| use rustc_data_structures::steal::Steal; | ||
| use rustc_data_structures::sync::{FreezeReadGuard, FreezeWriteGuard, WorkerLocal}; | ||
| use rustc_data_structures::sync::{FreezeReadGuard, FreezeWriteGuard, RwLock, WorkerLocal}; | ||
| use rustc_data_structures::unord::{UnordItems, UnordMap, UnordSet}; | ||
| use rustc_errors::{Applicability, Diag, ErrCode, ErrorGuaranteed, LintBuffer}; | ||
| use rustc_expand::base::{DeriveResolution, SyntaxExtension, SyntaxExtensionKind}; | ||
|
|
@@ -1274,7 +1274,7 @@ struct ExternPreludeEntry<'ra> { | |
| item_decl: Option<(Decl<'ra>, Span, /* introduced by item */ bool)>, | ||
| /// Name declaration from an `--extern` flag, lazily populated on first use. | ||
| flag_decl: Option< | ||
| CacheCell<( | ||
| Mutex<( | ||
| PendingDecl<'ra>, | ||
| /* finalized */ bool, | ||
| /* open flag (namespaced crate) */ bool, | ||
|
|
@@ -1290,14 +1290,14 @@ impl ExternPreludeEntry<'_> { | |
| fn flag() -> Self { | ||
| ExternPreludeEntry { | ||
| item_decl: None, | ||
| flag_decl: Some(CacheCell::new((PendingDecl::Pending, false, false))), | ||
| flag_decl: Some(Mutex::new((PendingDecl::Pending, false, false))), | ||
| } | ||
| } | ||
|
|
||
| fn open_flag() -> Self { | ||
| ExternPreludeEntry { | ||
| item_decl: None, | ||
| flag_decl: Some(CacheCell::new((PendingDecl::Pending, false, true))), | ||
| flag_decl: Some(Mutex::new((PendingDecl::Pending, false, true))), | ||
| } | ||
| } | ||
|
|
||
|
|
@@ -1397,7 +1397,7 @@ pub struct Resolver<'ra, 'tcx> { | |
| /// Eagerly populated map of all local non-block modules. | ||
| local_module_map: FxIndexMap<LocalDefId, LocalModule<'ra>>, | ||
| /// Lazily populated cache of modules loaded from external crates. | ||
| extern_module_map: CacheRefCell<FxIndexMap<DefId, ExternModule<'ra>>>, | ||
| extern_module_map: RwLock<FxIndexMap<DefId, ExternModule<'ra>>>, | ||
|
|
||
| /// Maps glob imports to the names of items actually imported. | ||
| glob_map: FxIndexMap<LocalDefId, FxIndexSet<Symbol>>, | ||
|
|
@@ -1429,7 +1429,7 @@ pub struct Resolver<'ra, 'tcx> { | |
| /// Eagerly populated map of all local macro definitions. | ||
| local_macro_map: FxHashMap<LocalDefId, &'ra Arc<SyntaxExtension>> = default::fx_hash_map(), | ||
| /// Lazily populated cache of macro definitions loaded from external crates. | ||
| extern_macro_map: CacheRefCell<FxHashMap<DefId, &'ra Arc<SyntaxExtension>>>, | ||
| extern_macro_map: RwLock<FxHashMap<DefId, &'ra Arc<SyntaxExtension>>>, | ||
| dummy_ext_bang: &'ra Arc<SyntaxExtension>, | ||
| dummy_ext_derive: &'ra Arc<SyntaxExtension>, | ||
| non_macro_attr: &'ra Arc<SyntaxExtension>, | ||
|
|
@@ -1602,7 +1602,7 @@ impl<'ra> ResolverArenas<'ra> { | |
| Interned::new_unchecked(self.name_resolutions.alloc(CmRefCell::new(resolution))) | ||
| } | ||
| fn alloc_macro_rules_scope(&'ra self, scope: MacroRulesScope<'ra>) -> MacroRulesScopeRef<'ra> { | ||
| self.dropless.alloc(CacheCell::new(scope)) | ||
| self.dropless.alloc(RwLock::new(scope)) | ||
| } | ||
| fn alloc_macro_rules_decl(&'ra self, decl: MacroRulesDecl<'ra>) -> &'ra MacroRulesDecl<'ra> { | ||
| self.dropless.alloc(decl) | ||
|
|
@@ -2456,7 +2456,8 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { | |
| ) -> Option<Decl<'ra>> { | ||
| let entry = self.extern_prelude.get(&ident); | ||
| entry.and_then(|entry| entry.flag_decl.as_ref()).and_then(|flag_decl| { | ||
| let (pending_decl, finalized, is_open) = flag_decl.get(); | ||
| let mut flag_decl = flag_decl.lock().unwrap(); // Lock for this entire process | ||
| let (pending_decl, finalized, is_open) = *flag_decl; | ||
| let decl = match pending_decl { | ||
| PendingDecl::Ready(decl) => { | ||
| if finalize && !finalized && !is_open { | ||
|
|
@@ -2491,7 +2492,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { | |
| } | ||
| } | ||
| }; | ||
| flag_decl.set((PendingDecl::Ready(decl), finalize || finalized, is_open)); | ||
| *flag_decl = (PendingDecl::Ready(decl), finalize || finalized, is_open); | ||
| decl.or_else(|| finalize.then_some(self.dummy_decl)) | ||
| }) | ||
| } | ||
|
|
@@ -2831,16 +2832,31 @@ pub fn provide(providers: &mut Providers) { | |
| /// Prefer constructing it through `Resolver::cm(_mut)` to ensure correctness. | ||
| type CmResolver<'r, 'ra, 'tcx> = ref_mut::RefOrMut<'r, Resolver<'ra, 'tcx>>; | ||
|
|
||
| // FIXME: These are cells for caches that can be populated even during speculative resolution, | ||
| // and should be replaced with mutexes, atomics, or other synchronized data when migrating to | ||
| // parallel name resolution. | ||
|
LorrensP-2158466 marked this conversation as resolved.
|
||
| use std::cell::{Cell as CacheCell, RefCell as CacheRefCell}; | ||
|
|
||
| /// The [`Resolver`] has different resolution phases, which share most of the resolution logic. | ||
| /// Some of these phases mutate the resolver (`&mut Resolver`) during resolution. However, we are | ||
| /// transforming import resolution (one of these phases), often referred to as | ||
| /// "speculative resolution", to a parallel algorithm, which requires 2 things to change: | ||
| /// - A `&Resolver`, because cannot mutate any fields in it. | ||
| /// - Some fields with interior mutability may not be changed during import resolution, as | ||
| /// this can conflict with other in progress resolutions (so locks are not the solution). | ||
| /// But these fields do require interior mutability during the other phases. | ||
| /// | ||
| /// Because refactoring the entire name resolution code to be split into "immutable" and "mutable" | ||
| /// logic, we opted for a more "developer friendly" and "unsafe" approach using data structures | ||
| /// that are immutable during import resolution. This module is the collection of 3 data structures | ||
| /// that offer use the above 2 points: | ||
| /// - a `RefOrMut<'a, T>` smart pointer that gates a `&'a mut T` through a flag | ||
| /// (i.e. are we in import res?). | ||
| /// - `CmCell` and `CmRefCell`, which are conditionally mutable through a flag. | ||
| /// | ||
| /// We hope one day to not have to do this :D | ||
| mod ref_mut { | ||
| use std::cell::{BorrowMutError, Cell, Ref, RefCell, RefMut}; | ||
| use std::fmt; | ||
| use std::ops::Deref; | ||
|
|
||
| use rustc_data_structures::sync::DynSync; | ||
|
|
||
| use crate::Resolver; | ||
|
|
||
| /// A reference type that conditionally allows mutable access. | ||
|
|
@@ -2893,6 +2909,12 @@ mod ref_mut { | |
| #[derive(Default)] | ||
| pub(crate) struct CmCell<T>(Cell<T>); | ||
|
|
||
| // SAFETY: `CmCell<T>` is `Sync` only because every path that can call `Cell::set` | ||
| // (i.e. `CmCell::set`, and `update`, which is built on top of it) first checks | ||
| // `r.assert_speculative` and panics if it's set, refusing to mutate. Soundness | ||
| // therefore depends on proper usage of the `assert_speculative` field in the `Resolver`. | ||
| unsafe impl<T: DynSync> DynSync for CmCell<T> {} | ||
|
|
||
| impl<T: Copy + fmt::Debug> fmt::Debug for CmCell<T> { | ||
| fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
| f.debug_tuple("CmCell").field(&self.get()).finish() | ||
|
|
@@ -2981,10 +3003,20 @@ mod ref_mut { | |
| } | ||
| } | ||
|
|
||
| /// A wrapper around a [`RefCell`] that only allows writes (mutable borrows) based on a condition in the resolver. | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Lost a comment. |
||
| #[derive(Default)] | ||
| pub(crate) struct CmRefCell<T>(RefCell<T>); | ||
|
|
||
| // SAFETY: This is safe because we can only mutate the inner state (borrow counter and `T`) | ||
| // if we are not in speculative resolution, which is run in parallel. This is checked | ||
| // dynamically with the `resolver.speculative_flag` field: | ||
| // | ||
| // - Any form of `borrow_mut` causes an immediate panic if that flag is set to ture. | ||
| // - We can only ever update the read counter in `borrow` if we have a `&mut Resolver`, | ||
| // thus proving no speculative resolution exists. If we do need a shared borrow, the | ||
| // `borrow_checked` function can be used, which gives out a `CmRef`. (see the safety comment | ||
| // in `borrow_checked` for why this works) | ||
| unsafe impl<T: DynSync> DynSync for CmRefCell<T> {} | ||
|
|
||
| impl<T> CmRefCell<T> { | ||
| pub(crate) fn new(value: T) -> CmRefCell<T> { | ||
| CmRefCell(RefCell::new(value)) | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm not sure this is algorithmically correct.
We may need to protect a larger piece of logic by a lock, maybe the whole loop.
I need to think (but I'm busy this and next week).
View changes since the review
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I am not entirely familiar with the chained scopes of
macro_rules!, but I can assume there are no cycles, so this should be correct.Example chain:
If multiple threads try to compress the path
A -> Estarting atA, then no matter the ordering, they will always end up atE.t1reads nodeAand writes on that nodeB, thent2will readB.t1andt2read nodeA, both will then writeB, which is the result we expect.I see it as a recursive property as well, so it will hold until both threads read
Ein their last step.If multiple threads are compressing on the same path, their results will be the same as well. For example:
t1compressesA -> Eandt2will compressC -> E.Since both only overwrite their respective nodes,
Afort1andCfort2, they can never interfere with each other. It doesn't matter whatt2is doing on its path, because fort1the full path still "exists", ift2managed to overwriteCbeforet1gets to it, it just does one step less.Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm still not convinced.
Assume we have a slow thread t_slow and a fast thread t_fast.
MacroRulesScope::Invocationinscope = *next.borrow();.MacroRulesScope::Invocationfrom the step 1 in particularmacro_rules_scope.set(scope);puttingMacroRulesScope::Invocationback into themacro_rules_scopeagain.MacroRulesScope::Invocations -> "never observe invocation scopes for macros that were already expanded" invariant from the comment above is broken.