rustc_middle/query/
mod.rs

1//!
2//! # The rustc Query System: Query Definitions and Modifiers
3//!
4//! The core processes in rustc are shipped as queries. Each query is a demand-driven function from some key to a value.
5//! The execution result of the function is cached and directly read during the next request, thereby improving compilation efficiency.
6//! Some results are saved locally and directly read during the next compilation, which are core of incremental compilation.
7//!
8//! ## How to Read This Module
9//!
10//! Each `query` block in this file defines a single query, specifying its key and value types, along with various modifiers.
11//! These query definitions are processed by the [`rustc_macros`], which expands them into the necessary boilerplate code
12//! for the query system—including the [`Providers`] struct (a function table for all query implementations, where each field is
13//! a function pointer to the actual provider), caching, and dependency graph integration.
14//! **Note:** The `Providers` struct is not a Rust trait, but a struct generated by the `rustc_macros` to hold all provider functions.
15//! The `rustc_macros` also supports a set of **query modifiers** (see below) that control the behavior of each query.
16//!
17//! The actual provider functions are implemented in various modules and registered into the `Providers` struct
18//! during compiler initialization (see [`rustc_interface::passes::DEFAULT_QUERY_PROVIDERS`]).
19//!
20//! [`rustc_macros`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_macros/index.html
21//! [`rustc_interface::passes::DEFAULT_QUERY_PROVIDERS`]: ../../rustc_interface/passes/static.DEFAULT_QUERY_PROVIDERS.html
22//!
23//! ## Query Modifiers
24//!
25//! Query modifiers are special flags that alter the behavior of a query. They are parsed and processed by the `rustc_macros`
26//! The main modifiers are:
27//!
28//! - `desc { ... }`: Sets the human-readable description for diagnostics and profiling. Required for every query.
29//! - `arena_cache`: Use an arena for in-memory caching of the query result.
30//! - `cache_on_disk_if { ... }`: Cache the query result to disk if the provided block evaluates to true.
31//! - `fatal_cycle`: If a dependency cycle is detected, abort compilation with a fatal error.
32//! - `cycle_delay_bug`: If a dependency cycle is detected, emit a delayed bug instead of aborting immediately.
33//! - `cycle_stash`: If a dependency cycle is detected, stash the error for later handling.
34//! - `no_hash`: Do not hash the query result for incremental compilation; just mark as dirty if recomputed.
35//! - `anon`: Make the query anonymous in the dependency graph (no dep node is created).
36//! - `eval_always`: Always evaluate the query, ignoring its dependencies and cached results.
37//! - `depth_limit`: Impose a recursion depth limit on the query to prevent stack overflows.
38//! - `separate_provide_extern`: Use separate provider functions for local and external crates.
39//! - `feedable`: Allow the query result to be set from another query ("fed" externally).
40//! - `return_result_from_ensure_ok`: When called via `tcx.ensure_ok()`, return `Result<(), ErrorGuaranteed>` instead of `()`.
41//!   If the query needs to be executed and returns an error, the error is returned to the caller.
42//!   Only valid for queries returning `Result<_, ErrorGuaranteed>`.
43//!
44//! For the up-to-date list, see the `QueryModifiers` struct in
45//! [`rustc_macros/src/query.rs`](https://github.com/rust-lang/rust/blob/HEAD/compiler/rustc_macros/src/query.rs)
46//! and for more details in incremental compilation, see the
47//! [Query modifiers in incremental compilation](https://rustc-dev-guide.rust-lang.org/queries/incremental-compilation-in-detail.html#query-modifiers) section of the rustc-dev-guide.
48//!
49//! ## Query Expansion and Code Generation
50//!
51//! The [`rustc_macros::rustc_queries`] macro expands each query definition into:
52//! - A method on [`TyCtxt`] (and [`TyCtxtAt`]) for invoking the query.
53//! - Provider traits and structs for supplying the query's value.
54//! - Caching and dependency graph integration.
55//! - Support for incremental compilation, disk caching, and arena allocation as controlled by the modifiers.
56//!
57//! [`rustc_macros::rustc_queries`]: ../../rustc_macros/macro.rustc_queries.html
58//!
59//! The macro-based approach allows the query system to be highly flexible and maintainable, while minimizing boilerplate.
60//!
61//! For more details, see the [rustc-dev-guide](https://rustc-dev-guide.rust-lang.org/query.html).
62
63#![allow(unused_parens)]
64
65use std::ffi::OsStr;
66use std::mem;
67use std::path::PathBuf;
68use std::sync::Arc;
69
70use rustc_abi::Align;
71use rustc_arena::TypedArena;
72use rustc_ast::expand::allocator::AllocatorKind;
73use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
74use rustc_data_structures::sorted_map::SortedMap;
75use rustc_data_structures::steal::Steal;
76use rustc_data_structures::svh::Svh;
77use rustc_data_structures::unord::{UnordMap, UnordSet};
78use rustc_errors::ErrorGuaranteed;
79use rustc_hir::attrs::{EiiDecl, EiiImpl, StrippedCfgItem};
80use rustc_hir::def::{DefKind, DocLinkResMap};
81use rustc_hir::def_id::{
82    CrateNum, DefId, DefIdMap, LocalDefId, LocalDefIdMap, LocalDefIdSet, LocalModDefId,
83};
84use rustc_hir::lang_items::{LangItem, LanguageItems};
85use rustc_hir::{Crate, ItemLocalId, ItemLocalMap, PreciseCapturingArgKind, TraitCandidate};
86use rustc_index::IndexVec;
87use rustc_lint_defs::LintId;
88use rustc_macros::rustc_queries;
89use rustc_query_system::ich::StableHashingContext;
90use rustc_query_system::query::{QueryMode, QueryStackDeferred, QueryState};
91use rustc_session::Limits;
92use rustc_session::config::{EntryFnType, OptLevel, OutputFilenames, SymbolManglingVersion};
93use rustc_session::cstore::{
94    CrateDepKind, CrateSource, ExternCrate, ForeignModule, LinkagePreference, NativeLib,
95};
96use rustc_session::lint::LintExpectationId;
97use rustc_span::def_id::LOCAL_CRATE;
98use rustc_span::source_map::Spanned;
99use rustc_span::{DUMMY_SP, Span, Symbol};
100use rustc_target::spec::PanicStrategy;
101use {rustc_abi as abi, rustc_ast as ast, rustc_hir as hir};
102
103pub use self::keys::{AsLocalKey, Key, LocalCrate};
104pub use self::plumbing::{IntoQueryParam, TyCtxtAt, TyCtxtEnsureDone, TyCtxtEnsureOk};
105use crate::infer::canonical::{self, Canonical};
106use crate::lint::LintExpectation;
107use crate::metadata::ModChild;
108use crate::middle::codegen_fn_attrs::{CodegenFnAttrs, SanitizerFnAttrs};
109use crate::middle::debugger_visualizer::DebuggerVisualizerFile;
110use crate::middle::deduced_param_attrs::DeducedParamAttrs;
111use crate::middle::exported_symbols::{ExportedSymbol, SymbolExportInfo};
112use crate::middle::lib_features::LibFeatures;
113use crate::middle::privacy::EffectiveVisibilities;
114use crate::middle::resolve_bound_vars::{ObjectLifetimeDefault, ResolveBoundVars, ResolvedArg};
115use crate::middle::stability::DeprecationEntry;
116use crate::mir::interpret::{
117    EvalStaticInitializerRawResult, EvalToAllocationRawResult, EvalToConstValueResult,
118    EvalToValTreeResult, GlobalId, LitToConstInput,
119};
120use crate::mir::mono::{
121    CodegenUnit, CollectionMode, MonoItem, MonoItemPartitions, NormalizationErrorInMono,
122};
123use crate::query::erase::{Erase, erase, restore};
124use crate::query::plumbing::{CyclePlaceholder, DynamicQuery};
125use crate::traits::query::{
126    CanonicalAliasGoal, CanonicalDropckOutlivesGoal, CanonicalImpliedOutlivesBoundsGoal,
127    CanonicalMethodAutoderefStepsGoal, CanonicalPredicateGoal, CanonicalTypeOpAscribeUserTypeGoal,
128    CanonicalTypeOpNormalizeGoal, CanonicalTypeOpProvePredicateGoal, DropckConstraint,
129    DropckOutlivesResult, MethodAutoderefStepsResult, NoSolution, NormalizationResult,
130    OutlivesBound,
131};
132use crate::traits::{
133    CodegenObligationError, DynCompatibilityViolation, EvaluationResult, ImplSource,
134    ObligationCause, OverflowError, WellFormedLoc, solve, specialization_graph,
135};
136use crate::ty::fast_reject::SimplifiedType;
137use crate::ty::layout::ValidityRequirement;
138use crate::ty::print::PrintTraitRefExt;
139use crate::ty::util::AlwaysRequiresDrop;
140use crate::ty::{
141    self, CrateInherentImpls, GenericArg, GenericArgsRef, PseudoCanonicalInput, SizedTraitKind, Ty,
142    TyCtxt, TyCtxtFeed,
143};
144use crate::{dep_graph, mir, thir};
145
146mod arena_cached;
147pub mod erase;
148pub(crate) mod inner;
149mod keys;
150pub mod on_disk_cache;
151#[macro_use]
152pub mod plumbing;
153
154// Each of these queries corresponds to a function pointer field in the
155// `Providers` struct for requesting a value of that type, and a method
156// on `tcx: TyCtxt` (and `tcx.at(span)`) for doing that request in a way
157// which memoizes and does dep-graph tracking, wrapping around the actual
158// `Providers` that the driver creates (using several `rustc_*` crates).
159//
160// The result type of each query must implement `Clone`, and additionally
161// `ty::query::values::Value`, which produces an appropriate placeholder
162// (error) value if the query resulted in a query cycle.
163// Queries marked with `fatal_cycle` do not need the latter implementation,
164// as they will raise an fatal error on query cycles instead.
165rustc_queries! {
166    /// This exists purely for testing the interactions between delayed bugs and incremental.
167    query trigger_delayed_bug(key: DefId) {
168        desc { "triggering a delayed bug for testing incremental" }
169    }
170
171    /// Collects the list of all tools registered using `#![register_tool]`.
172    query registered_tools(_: ()) -> &'tcx ty::RegisteredTools {
173        arena_cache
174        desc { "compute registered tools for crate" }
175    }
176
177    query early_lint_checks(_: ()) {
178        desc { "perform lints prior to AST lowering" }
179    }
180
181    /// Tracked access to environment variables.
182    ///
183    /// Useful for the implementation of `std::env!`, `proc-macro`s change
184    /// detection and other changes in the compiler's behaviour that is easier
185    /// to control with an environment variable than a flag.
186    ///
187    /// NOTE: This currently does not work with dependency info in the
188    /// analysis, codegen and linking passes, place extra code at the top of
189    /// `rustc_interface::passes::write_dep_info` to make that work.
190    query env_var_os(key: &'tcx OsStr) -> Option<&'tcx OsStr> {
191        // Environment variables are global state
192        eval_always
193        desc { "get the value of an environment variable" }
194    }
195
196    query resolutions(_: ()) -> &'tcx ty::ResolverGlobalCtxt {
197        desc { "getting the resolver outputs" }
198    }
199
200    query resolver_for_lowering_raw(_: ()) -> (&'tcx Steal<(ty::ResolverAstLowering, Arc<ast::Crate>)>, &'tcx ty::ResolverGlobalCtxt) {
201        eval_always
202        no_hash
203        desc { "getting the resolver for lowering" }
204    }
205
206    /// Return the span for a definition.
207    ///
208    /// Contrary to `def_span` below, this query returns the full absolute span of the definition.
209    /// This span is meant for dep-tracking rather than diagnostics. It should not be used outside
210    /// of rustc_middle::hir::source_map.
211    query source_span(key: LocalDefId) -> Span {
212        // Accesses untracked data
213        eval_always
214        desc { "getting the source span" }
215    }
216
217    /// Represents crate as a whole (as distinct from the top-level crate module).
218    ///
219    /// If you call `tcx.hir_crate(())` we will have to assume that any change
220    /// means that you need to be recompiled. This is because the `hir_crate`
221    /// query gives you access to all other items. To avoid this fate, do not
222    /// call `tcx.hir_crate(())`; instead, prefer wrappers like
223    /// [`TyCtxt::hir_visit_all_item_likes_in_crate`].
224    query hir_crate(key: ()) -> &'tcx Crate<'tcx> {
225        arena_cache
226        eval_always
227        desc { "getting the crate HIR" }
228    }
229
230    /// All items in the crate.
231    query hir_crate_items(_: ()) -> &'tcx rustc_middle::hir::ModuleItems {
232        arena_cache
233        eval_always
234        desc { "getting HIR crate items" }
235    }
236
237    /// The items in a module.
238    ///
239    /// This can be conveniently accessed by `tcx.hir_visit_item_likes_in_module`.
240    /// Avoid calling this query directly.
241    query hir_module_items(key: LocalModDefId) -> &'tcx rustc_middle::hir::ModuleItems {
242        arena_cache
243        desc { |tcx| "getting HIR module items in `{}`", tcx.def_path_str(key) }
244        cache_on_disk_if { true }
245    }
246
247    /// Returns HIR ID for the given `LocalDefId`.
248    query local_def_id_to_hir_id(key: LocalDefId) -> hir::HirId {
249        desc { |tcx| "getting HIR ID of `{}`", tcx.def_path_str(key) }
250        feedable
251    }
252
253    /// Gives access to the HIR node's parent for the HIR owner `key`.
254    ///
255    /// This can be conveniently accessed by `tcx.hir_*` methods.
256    /// Avoid calling this query directly.
257    query hir_owner_parent(key: hir::OwnerId) -> hir::HirId {
258        desc { |tcx| "getting HIR parent of `{}`", tcx.def_path_str(key) }
259    }
260
261    /// Gives access to the HIR nodes and bodies inside `key` if it's a HIR owner.
262    ///
263    /// This can be conveniently accessed by `tcx.hir_*` methods.
264    /// Avoid calling this query directly.
265    query opt_hir_owner_nodes(key: LocalDefId) -> Option<&'tcx hir::OwnerNodes<'tcx>> {
266        desc { |tcx| "getting HIR owner items in `{}`", tcx.def_path_str(key) }
267        feedable
268    }
269
270    /// Gives access to the HIR attributes inside the HIR owner `key`.
271    ///
272    /// This can be conveniently accessed by `tcx.hir_*` methods.
273    /// Avoid calling this query directly.
274    query hir_attr_map(key: hir::OwnerId) -> &'tcx hir::AttributeMap<'tcx> {
275        desc { |tcx| "getting HIR owner attributes in `{}`", tcx.def_path_str(key) }
276        feedable
277    }
278
279    /// Gives access to lints emitted during ast lowering.
280    ///
281    /// This can be conveniently accessed by `tcx.hir_*` methods.
282    /// Avoid calling this query directly.
283    query opt_ast_lowering_delayed_lints(key: hir::OwnerId) -> Option<&'tcx hir::lints::DelayedLints> {
284        desc { |tcx| "getting AST lowering delayed lints in `{}`", tcx.def_path_str(key) }
285    }
286
287    /// Returns the *default* of the const pararameter given by `DefId`.
288    ///
289    /// E.g., given `struct Ty<const N: usize = 3>;` this returns `3` for `N`.
290    query const_param_default(param: DefId) -> ty::EarlyBinder<'tcx, ty::Const<'tcx>> {
291        desc { |tcx| "computing the default for const parameter `{}`", tcx.def_path_str(param)  }
292        cache_on_disk_if { param.is_local() }
293        separate_provide_extern
294    }
295
296    /// Returns the const of the RHS of a (free or assoc) const item, if it is a `#[type_const]`.
297    ///
298    /// When a const item is used in a type-level expression, like in equality for an assoc const
299    /// projection, this allows us to retrieve the typesystem-appropriate representation of the
300    /// const value.
301    ///
302    /// This query will ICE if given a const that is not marked with `#[type_const]`.
303    query const_of_item(def_id: DefId) -> ty::EarlyBinder<'tcx, ty::Const<'tcx>> {
304        desc { |tcx| "computing the type-level value for `{}`", tcx.def_path_str(def_id)  }
305        cache_on_disk_if { def_id.is_local() }
306        separate_provide_extern
307    }
308
309    /// Returns the *type* of the definition given by `DefId`.
310    ///
311    /// For type aliases (whether eager or lazy) and associated types, this returns
312    /// the underlying aliased type (not the corresponding [alias type]).
313    ///
314    /// For opaque types, this returns and thus reveals the hidden type! If you
315    /// want to detect cycle errors use `type_of_opaque` instead.
316    ///
317    /// To clarify, for type definitions, this does *not* return the "type of a type"
318    /// (aka *kind* or *sort*) in the type-theoretical sense! It merely returns
319    /// the type primarily *associated with* it.
320    ///
321    /// # Panics
322    ///
323    /// This query will panic if the given definition doesn't (and can't
324    /// conceptually) have an (underlying) type.
325    ///
326    /// [alias type]: rustc_middle::ty::AliasTy
327    query type_of(key: DefId) -> ty::EarlyBinder<'tcx, Ty<'tcx>> {
328        desc { |tcx|
329            "{action} `{path}`",
330            action = match tcx.def_kind(key) {
331                DefKind::TyAlias => "expanding type alias",
332                DefKind::TraitAlias => "expanding trait alias",
333                _ => "computing type of",
334            },
335            path = tcx.def_path_str(key),
336        }
337        cache_on_disk_if { key.is_local() }
338        separate_provide_extern
339        feedable
340    }
341
342    /// Returns the *hidden type* of the opaque type given by `DefId` unless a cycle occurred.
343    ///
344    /// This is a specialized instance of [`Self::type_of`] that detects query cycles.
345    /// Unless `CyclePlaceholder` needs to be handled separately, call [`Self::type_of`] instead.
346    /// This is used to improve the error message in cases where revealing the hidden type
347    /// for auto-trait leakage cycles.
348    ///
349    /// # Panics
350    ///
351    /// This query will panic if the given definition is not an opaque type.
352    query type_of_opaque(key: DefId) -> Result<ty::EarlyBinder<'tcx, Ty<'tcx>>, CyclePlaceholder> {
353        desc { |tcx|
354            "computing type of opaque `{path}`",
355            path = tcx.def_path_str(key),
356        }
357        cycle_stash
358    }
359    query type_of_opaque_hir_typeck(key: LocalDefId) -> ty::EarlyBinder<'tcx, Ty<'tcx>> {
360        desc { |tcx|
361            "computing type of opaque `{path}` via HIR typeck",
362            path = tcx.def_path_str(key),
363        }
364    }
365
366    /// Returns whether the type alias given by `DefId` is lazy.
367    ///
368    /// I.e., if the type alias expands / ought to expand to a [free] [alias type]
369    /// instead of the underlying aliased type.
370    ///
371    /// Relevant for features `lazy_type_alias` and `type_alias_impl_trait`.
372    ///
373    /// # Panics
374    ///
375    /// This query *may* panic if the given definition is not a type alias.
376    ///
377    /// [free]: rustc_middle::ty::Free
378    /// [alias type]: rustc_middle::ty::AliasTy
379    query type_alias_is_lazy(key: DefId) -> bool {
380        desc { |tcx|
381            "computing whether the type alias `{path}` is lazy",
382            path = tcx.def_path_str(key),
383        }
384        separate_provide_extern
385    }
386
387    query collect_return_position_impl_trait_in_trait_tys(key: DefId)
388        -> Result<&'tcx DefIdMap<ty::EarlyBinder<'tcx, Ty<'tcx>>>, ErrorGuaranteed>
389    {
390        desc { "comparing an impl and trait method signature, inferring any hidden `impl Trait` types in the process" }
391        cache_on_disk_if { key.is_local() }
392        separate_provide_extern
393    }
394
395    query opaque_ty_origin(key: DefId) -> hir::OpaqueTyOrigin<DefId>
396    {
397        desc { "determine where the opaque originates from" }
398        separate_provide_extern
399    }
400
401    query unsizing_params_for_adt(key: DefId) -> &'tcx rustc_index::bit_set::DenseBitSet<u32>
402    {
403        arena_cache
404        desc { |tcx|
405            "determining what parameters of `{}` can participate in unsizing",
406            tcx.def_path_str(key),
407        }
408    }
409
410    /// The root query triggering all analysis passes like typeck or borrowck.
411    query analysis(key: ()) {
412        eval_always
413        desc { |tcx|
414            "running analysis passes on crate `{}`",
415            tcx.crate_name(LOCAL_CRATE),
416        }
417    }
418
419    /// This query checks the fulfillment of collected lint expectations.
420    /// All lint emitting queries have to be done before this is executed
421    /// to ensure that all expectations can be fulfilled.
422    ///
423    /// This is an extra query to enable other drivers (like rustdoc) to
424    /// only execute a small subset of the `analysis` query, while allowing
425    /// lints to be expected. In rustc, this query will be executed as part of
426    /// the `analysis` query and doesn't have to be called a second time.
427    ///
428    /// Tools can additionally pass in a tool filter. That will restrict the
429    /// expectations to only trigger for lints starting with the listed tool
430    /// name. This is useful for cases were not all linting code from rustc
431    /// was called. With the default `None` all registered lints will also
432    /// be checked for expectation fulfillment.
433    query check_expectations(key: Option<Symbol>) {
434        eval_always
435        desc { "checking lint expectations (RFC 2383)" }
436    }
437
438    /// Returns the *generics* of the definition given by `DefId`.
439    query generics_of(key: DefId) -> &'tcx ty::Generics {
440        desc { |tcx| "computing generics of `{}`", tcx.def_path_str(key) }
441        arena_cache
442        cache_on_disk_if { key.is_local() }
443        separate_provide_extern
444        feedable
445    }
446
447    /// Returns the (elaborated) *predicates* of the definition given by `DefId`
448    /// that must be proven true at usage sites (and which can be assumed at definition site).
449    ///
450    /// This is almost always *the* "predicates query" that you want.
451    ///
452    /// **Tip**: You can use `#[rustc_dump_predicates]` on an item to basically print
453    /// the result of this query for use in UI tests or for debugging purposes.
454    query predicates_of(key: DefId) -> ty::GenericPredicates<'tcx> {
455        desc { |tcx| "computing predicates of `{}`", tcx.def_path_str(key) }
456        cache_on_disk_if { key.is_local() }
457    }
458
459    query opaque_types_defined_by(
460        key: LocalDefId
461    ) -> &'tcx ty::List<LocalDefId> {
462        desc {
463            |tcx| "computing the opaque types defined by `{}`",
464            tcx.def_path_str(key.to_def_id())
465        }
466    }
467
468    /// A list of all bodies inside of `key`, nested bodies are always stored
469    /// before their parent.
470    query nested_bodies_within(
471        key: LocalDefId
472    ) -> &'tcx ty::List<LocalDefId> {
473        desc {
474            |tcx| "computing the coroutines defined within `{}`",
475            tcx.def_path_str(key.to_def_id())
476        }
477    }
478
479    /// Returns the explicitly user-written *bounds* on the associated or opaque type given by `DefId`
480    /// that must be proven true at definition site (and which can be assumed at usage sites).
481    ///
482    /// For associated types, these must be satisfied for an implementation
483    /// to be well-formed, and for opaque types, these are required to be
484    /// satisfied by the hidden type of the opaque.
485    ///
486    /// Bounds from the parent (e.g. with nested `impl Trait`) are not included.
487    ///
488    /// Syntactially, these are the bounds written on associated types in trait
489    /// definitions, or those after the `impl` keyword for an opaque:
490    ///
491    /// ```ignore (illustrative)
492    /// trait Trait { type X: Bound + 'lt; }
493    /// //                    ^^^^^^^^^^^
494    /// fn function() -> impl Debug + Display { /*...*/ }
495    /// //                    ^^^^^^^^^^^^^^^
496    /// ```
497    query explicit_item_bounds(key: DefId) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]> {
498        desc { |tcx| "finding item bounds for `{}`", tcx.def_path_str(key) }
499        cache_on_disk_if { key.is_local() }
500        separate_provide_extern
501        feedable
502    }
503
504    /// Returns the explicitly user-written *bounds* that share the `Self` type of the item.
505    ///
506    /// These are a subset of the [explicit item bounds] that may explicitly be used for things
507    /// like closure signature deduction.
508    ///
509    /// [explicit item bounds]: Self::explicit_item_bounds
510    query explicit_item_self_bounds(key: DefId) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]> {
511        desc { |tcx| "finding item bounds for `{}`", tcx.def_path_str(key) }
512        cache_on_disk_if { key.is_local() }
513        separate_provide_extern
514        feedable
515    }
516
517    /// Returns the (elaborated) *bounds* on the associated or opaque type given by `DefId`
518    /// that must be proven true at definition site (and which can be assumed at usage sites).
519    ///
520    /// Bounds from the parent (e.g. with nested `impl Trait`) are not included.
521    ///
522    /// **Tip**: You can use `#[rustc_dump_item_bounds]` on an item to basically print
523    /// the result of this query for use in UI tests or for debugging purposes.
524    ///
525    /// # Examples
526    ///
527    /// ```
528    /// trait Trait { type Assoc: Eq + ?Sized; }
529    /// ```
530    ///
531    /// While [`Self::explicit_item_bounds`] returns `[<Self as Trait>::Assoc: Eq]`
532    /// here, `item_bounds` returns:
533    ///
534    /// ```text
535    /// [
536    ///     <Self as Trait>::Assoc: Eq,
537    ///     <Self as Trait>::Assoc: PartialEq<<Self as Trait>::Assoc>
538    /// ]
539    /// ```
540    query item_bounds(key: DefId) -> ty::EarlyBinder<'tcx, ty::Clauses<'tcx>> {
541        desc { |tcx| "elaborating item bounds for `{}`", tcx.def_path_str(key) }
542    }
543
544    query item_self_bounds(key: DefId) -> ty::EarlyBinder<'tcx, ty::Clauses<'tcx>> {
545        desc { |tcx| "elaborating item assumptions for `{}`", tcx.def_path_str(key) }
546    }
547
548    query item_non_self_bounds(key: DefId) -> ty::EarlyBinder<'tcx, ty::Clauses<'tcx>> {
549        desc { |tcx| "elaborating item assumptions for `{}`", tcx.def_path_str(key) }
550    }
551
552    query impl_super_outlives(key: DefId) -> ty::EarlyBinder<'tcx, ty::Clauses<'tcx>> {
553        desc { |tcx| "elaborating supertrait outlives for trait of `{}`", tcx.def_path_str(key) }
554    }
555
556    /// Look up all native libraries this crate depends on.
557    /// These are assembled from the following places:
558    /// - `extern` blocks (depending on their `link` attributes)
559    /// - the `libs` (`-l`) option
560    query native_libraries(_: CrateNum) -> &'tcx Vec<NativeLib> {
561        arena_cache
562        desc { "looking up the native libraries of a linked crate" }
563        separate_provide_extern
564    }
565
566    query shallow_lint_levels_on(key: hir::OwnerId) -> &'tcx rustc_middle::lint::ShallowLintLevelMap {
567        arena_cache
568        desc { |tcx| "looking up lint levels for `{}`", tcx.def_path_str(key) }
569    }
570
571    query lint_expectations(_: ()) -> &'tcx Vec<(LintExpectationId, LintExpectation)> {
572        arena_cache
573        desc { "computing `#[expect]`ed lints in this crate" }
574    }
575
576    query lints_that_dont_need_to_run(_: ()) -> &'tcx UnordSet<LintId> {
577        arena_cache
578        desc { "Computing all lints that are explicitly enabled or with a default level greater than Allow" }
579    }
580
581    query expn_that_defined(key: DefId) -> rustc_span::ExpnId {
582        desc { |tcx| "getting the expansion that defined `{}`", tcx.def_path_str(key) }
583        separate_provide_extern
584    }
585
586    query is_panic_runtime(_: CrateNum) -> bool {
587        fatal_cycle
588        desc { "checking if the crate is_panic_runtime" }
589        separate_provide_extern
590    }
591
592    /// Checks whether a type is representable or infinitely sized
593    query representability(_: LocalDefId) -> rustc_middle::ty::Representability {
594        desc { "checking if `{}` is representable", tcx.def_path_str(key) }
595        // infinitely sized types will cause a cycle
596        cycle_delay_bug
597        // we don't want recursive representability calls to be forced with
598        // incremental compilation because, if a cycle occurs, we need the
599        // entire cycle to be in memory for diagnostics
600        anon
601    }
602
603    /// An implementation detail for the `representability` query
604    query representability_adt_ty(_: Ty<'tcx>) -> rustc_middle::ty::Representability {
605        desc { "checking if `{}` is representable", key }
606        cycle_delay_bug
607        anon
608    }
609
610    /// Set of param indexes for type params that are in the type's representation
611    query params_in_repr(key: DefId) -> &'tcx rustc_index::bit_set::DenseBitSet<u32> {
612        desc { "finding type parameters in the representation" }
613        arena_cache
614        no_hash
615        separate_provide_extern
616    }
617
618    /// Fetch the THIR for a given body. The THIR body gets stolen by unsafety checking unless
619    /// `-Zno-steal-thir` is on.
620    query thir_body(key: LocalDefId) -> Result<(&'tcx Steal<thir::Thir<'tcx>>, thir::ExprId), ErrorGuaranteed> {
621        // Perf tests revealed that hashing THIR is inefficient (see #85729).
622        no_hash
623        desc { |tcx| "building THIR for `{}`", tcx.def_path_str(key) }
624    }
625
626    /// Set of all the `DefId`s in this crate that have MIR associated with
627    /// them. This includes all the body owners, but also things like struct
628    /// constructors.
629    query mir_keys(_: ()) -> &'tcx rustc_data_structures::fx::FxIndexSet<LocalDefId> {
630        arena_cache
631        desc { "getting a list of all mir_keys" }
632    }
633
634    /// Maps DefId's that have an associated `mir::Body` to the result
635    /// of the MIR const-checking pass. This is the set of qualifs in
636    /// the final value of a `const`.
637    query mir_const_qualif(key: DefId) -> mir::ConstQualifs {
638        desc { |tcx| "const checking `{}`", tcx.def_path_str(key) }
639        cache_on_disk_if { key.is_local() }
640        separate_provide_extern
641    }
642
643    /// Build the MIR for a given `DefId` and prepare it for const qualification.
644    ///
645    /// See the [rustc dev guide] for more info.
646    ///
647    /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/mir/construction.html
648    query mir_built(key: LocalDefId) -> &'tcx Steal<mir::Body<'tcx>> {
649        desc { |tcx| "building MIR for `{}`", tcx.def_path_str(key) }
650        feedable
651    }
652
653    /// Try to build an abstract representation of the given constant.
654    query thir_abstract_const(
655        key: DefId
656    ) -> Result<Option<ty::EarlyBinder<'tcx, ty::Const<'tcx>>>, ErrorGuaranteed> {
657        desc {
658            |tcx| "building an abstract representation for `{}`", tcx.def_path_str(key),
659        }
660        separate_provide_extern
661    }
662
663    query mir_drops_elaborated_and_const_checked(key: LocalDefId) -> &'tcx Steal<mir::Body<'tcx>> {
664        no_hash
665        desc { |tcx| "elaborating drops for `{}`", tcx.def_path_str(key) }
666    }
667
668    query mir_for_ctfe(
669        key: DefId
670    ) -> &'tcx mir::Body<'tcx> {
671        desc { |tcx| "caching mir of `{}` for CTFE", tcx.def_path_str(key) }
672        cache_on_disk_if { key.is_local() }
673        separate_provide_extern
674    }
675
676    query mir_promoted(key: LocalDefId) -> (
677        &'tcx Steal<mir::Body<'tcx>>,
678        &'tcx Steal<IndexVec<mir::Promoted, mir::Body<'tcx>>>
679    ) {
680        no_hash
681        desc { |tcx| "promoting constants in MIR for `{}`", tcx.def_path_str(key) }
682    }
683
684    query closure_typeinfo(key: LocalDefId) -> ty::ClosureTypeInfo<'tcx> {
685        desc {
686            |tcx| "finding symbols for captures of closure `{}`",
687            tcx.def_path_str(key)
688        }
689    }
690
691    /// Returns names of captured upvars for closures and coroutines.
692    ///
693    /// Here are some examples:
694    ///  - `name__field1__field2` when the upvar is captured by value.
695    ///  - `_ref__name__field` when the upvar is captured by reference.
696    ///
697    /// For coroutines this only contains upvars that are shared by all states.
698    query closure_saved_names_of_captured_variables(def_id: DefId) -> &'tcx IndexVec<abi::FieldIdx, Symbol> {
699        arena_cache
700        desc { |tcx| "computing debuginfo for closure `{}`", tcx.def_path_str(def_id) }
701        separate_provide_extern
702    }
703
704    query mir_coroutine_witnesses(key: DefId) -> Option<&'tcx mir::CoroutineLayout<'tcx>> {
705        arena_cache
706        desc { |tcx| "coroutine witness types for `{}`", tcx.def_path_str(key) }
707        cache_on_disk_if { key.is_local() }
708        separate_provide_extern
709    }
710
711    query check_coroutine_obligations(key: LocalDefId) -> Result<(), ErrorGuaranteed> {
712        desc { |tcx| "verify auto trait bounds for coroutine interior type `{}`", tcx.def_path_str(key) }
713        return_result_from_ensure_ok
714    }
715
716    /// Used in case `mir_borrowck` fails to prove an obligation. We generally assume that
717    /// all goals we prove in MIR type check hold as we've already checked them in HIR typeck.
718    ///
719    /// However, we replace each free region in the MIR body with a unique region inference
720    /// variable. As we may rely on structural identity when proving goals this may cause a
721    /// goal to no longer hold. We store obligations for which this may happen during HIR
722    /// typeck in the `TypeckResults`. We then uniquify and reprove them in case MIR typeck
723    /// encounters an unexpected error. We expect this to result in an error when used and
724    /// delay a bug if it does not.
725    query check_potentially_region_dependent_goals(key: LocalDefId) -> Result<(), ErrorGuaranteed> {
726        desc {
727            |tcx| "reproving potentially region dependent HIR typeck goals for `{}",
728            tcx.def_path_str(key)
729        }
730    }
731
732    /// MIR after our optimization passes have run. This is MIR that is ready
733    /// for codegen. This is also the only query that can fetch non-local MIR, at present.
734    query optimized_mir(key: DefId) -> &'tcx mir::Body<'tcx> {
735        desc { |tcx| "optimizing MIR for `{}`", tcx.def_path_str(key) }
736        cache_on_disk_if { key.is_local() }
737        separate_provide_extern
738    }
739
740    /// Checks for the nearest `#[coverage(off)]` or `#[coverage(on)]` on
741    /// this def and any enclosing defs, up to the crate root.
742    ///
743    /// Returns `false` if `#[coverage(off)]` was found, or `true` if
744    /// either `#[coverage(on)]` or no coverage attribute was found.
745    query coverage_attr_on(key: LocalDefId) -> bool {
746        desc { |tcx| "checking for `#[coverage(..)]` on `{}`", tcx.def_path_str(key) }
747        feedable
748    }
749
750    /// Scans through a function's MIR after MIR optimizations, to prepare the
751    /// information needed by codegen when `-Cinstrument-coverage` is active.
752    ///
753    /// This includes the details of where to insert `llvm.instrprof.increment`
754    /// intrinsics, and the expression tables to be embedded in the function's
755    /// coverage metadata.
756    ///
757    /// FIXME(Zalathar): This query's purpose has drifted a bit and should
758    /// probably be renamed, but that can wait until after the potential
759    /// follow-ups to #136053 have settled down.
760    ///
761    /// Returns `None` for functions that were not instrumented.
762    query coverage_ids_info(key: ty::InstanceKind<'tcx>) -> Option<&'tcx mir::coverage::CoverageIdsInfo> {
763        desc { |tcx| "retrieving coverage IDs info from MIR for `{}`", tcx.def_path_str(key.def_id()) }
764        arena_cache
765    }
766
767    /// The `DefId` is the `DefId` of the containing MIR body. Promoteds do not have their own
768    /// `DefId`. This function returns all promoteds in the specified body. The body references
769    /// promoteds by the `DefId` and the `mir::Promoted` index. This is necessary, because
770    /// after inlining a body may refer to promoteds from other bodies. In that case you still
771    /// need to use the `DefId` of the original body.
772    query promoted_mir(key: DefId) -> &'tcx IndexVec<mir::Promoted, mir::Body<'tcx>> {
773        desc { |tcx| "optimizing promoted MIR for `{}`", tcx.def_path_str(key) }
774        cache_on_disk_if { key.is_local() }
775        separate_provide_extern
776    }
777
778    /// Erases regions from `ty` to yield a new type.
779    /// Normally you would just use `tcx.erase_and_anonymize_regions(value)`,
780    /// however, which uses this query as a kind of cache.
781    query erase_and_anonymize_regions_ty(ty: Ty<'tcx>) -> Ty<'tcx> {
782        // This query is not expected to have input -- as a result, it
783        // is not a good candidates for "replay" because it is essentially a
784        // pure function of its input (and hence the expectation is that
785        // no caller would be green **apart** from just these
786        // queries). Making it anonymous avoids hashing the result, which
787        // may save a bit of time.
788        anon
789        desc { "erasing regions from `{}`", ty }
790    }
791
792    query wasm_import_module_map(_: CrateNum) -> &'tcx DefIdMap<String> {
793        arena_cache
794        desc { "getting wasm import module map" }
795    }
796
797    /// Returns the explicitly user-written *predicates and bounds* of the trait given by `DefId`.
798    ///
799    /// Traits are unusual, because predicates on associated types are
800    /// converted into bounds on that type for backwards compatibility:
801    ///
802    /// ```
803    /// trait X where Self::U: Copy { type U; }
804    /// ```
805    ///
806    /// becomes
807    ///
808    /// ```
809    /// trait X { type U: Copy; }
810    /// ```
811    ///
812    /// [`Self::explicit_predicates_of`] and [`Self::explicit_item_bounds`] will
813    /// then take the appropriate subsets of the predicates here.
814    ///
815    /// # Panics
816    ///
817    /// This query will panic if the given definition is not a trait.
818    query trait_explicit_predicates_and_bounds(key: LocalDefId) -> ty::GenericPredicates<'tcx> {
819        desc { |tcx| "computing explicit predicates of trait `{}`", tcx.def_path_str(key) }
820    }
821
822    /// Returns the explicitly user-written *predicates* of the definition given by `DefId`
823    /// that must be proven true at usage sites (and which can be assumed at definition site).
824    ///
825    /// You should probably use [`Self::predicates_of`] unless you're looking for
826    /// predicates with explicit spans for diagnostics purposes.
827    query explicit_predicates_of(key: DefId) -> ty::GenericPredicates<'tcx> {
828        desc { |tcx| "computing explicit predicates of `{}`", tcx.def_path_str(key) }
829        cache_on_disk_if { key.is_local() }
830        separate_provide_extern
831        feedable
832    }
833
834    /// Returns the *inferred outlives-predicates* of the item given by `DefId`.
835    ///
836    /// E.g., for `struct Foo<'a, T> { x: &'a T }`, this would return `[T: 'a]`.
837    ///
838    /// **Tip**: You can use `#[rustc_outlives]` on an item to basically print the
839    /// result of this query for use in UI tests or for debugging purposes.
840    query inferred_outlives_of(key: DefId) -> &'tcx [(ty::Clause<'tcx>, Span)] {
841        desc { |tcx| "computing inferred outlives-predicates of `{}`", tcx.def_path_str(key) }
842        cache_on_disk_if { key.is_local() }
843        separate_provide_extern
844        feedable
845    }
846
847    /// Returns the explicitly user-written *super-predicates* of the trait given by `DefId`.
848    ///
849    /// These predicates are unelaborated and consequently don't contain transitive super-predicates.
850    ///
851    /// This is a subset of the full list of predicates. We store these in a separate map
852    /// because we must evaluate them even during type conversion, often before the full
853    /// predicates are available (note that super-predicates must not be cyclic).
854    query explicit_super_predicates_of(key: DefId) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]> {
855        desc { |tcx| "computing the super predicates of `{}`", tcx.def_path_str(key) }
856        cache_on_disk_if { key.is_local() }
857        separate_provide_extern
858    }
859
860    /// The predicates of the trait that are implied during elaboration.
861    ///
862    /// This is a superset of the super-predicates of the trait, but a subset of the predicates
863    /// of the trait. For regular traits, this includes all super-predicates and their
864    /// associated type bounds. For trait aliases, currently, this includes all of the
865    /// predicates of the trait alias.
866    query explicit_implied_predicates_of(key: DefId) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]> {
867        desc { |tcx| "computing the implied predicates of `{}`", tcx.def_path_str(key) }
868        cache_on_disk_if { key.is_local() }
869        separate_provide_extern
870    }
871
872    /// The Ident is the name of an associated type.The query returns only the subset
873    /// of supertraits that define the given associated type. This is used to avoid
874    /// cycles in resolving type-dependent associated item paths like `T::Item`.
875    query explicit_supertraits_containing_assoc_item(
876        key: (DefId, rustc_span::Ident)
877    ) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]> {
878        desc { |tcx| "computing the super traits of `{}` with associated type name `{}`",
879            tcx.def_path_str(key.0),
880            key.1
881        }
882    }
883
884    /// Compute the conditions that need to hold for a conditionally-const item to be const.
885    /// That is, compute the set of `[const]` where clauses for a given item.
886    ///
887    /// This can be thought of as the `[const]` equivalent of `predicates_of`. These are the
888    /// predicates that need to be proven at usage sites, and can be assumed at definition.
889    ///
890    /// This query also computes the `[const]` where clauses for associated types, which are
891    /// not "const", but which have item bounds which may be `[const]`. These must hold for
892    /// the `[const]` item bound to hold.
893    query const_conditions(
894        key: DefId
895    ) -> ty::ConstConditions<'tcx> {
896        desc { |tcx| "computing the conditions for `{}` to be considered const",
897            tcx.def_path_str(key)
898        }
899        separate_provide_extern
900    }
901
902    /// Compute the const bounds that are implied for a conditionally-const item.
903    ///
904    /// This can be though of as the `[const]` equivalent of `explicit_item_bounds`. These
905    /// are the predicates that need to proven at definition sites, and can be assumed at
906    /// usage sites.
907    query explicit_implied_const_bounds(
908        key: DefId
909    ) -> ty::EarlyBinder<'tcx, &'tcx [(ty::PolyTraitRef<'tcx>, Span)]> {
910        desc { |tcx| "computing the implied `[const]` bounds for `{}`",
911            tcx.def_path_str(key)
912        }
913        separate_provide_extern
914    }
915
916    /// To avoid cycles within the predicates of a single item we compute
917    /// per-type-parameter predicates for resolving `T::AssocTy`.
918    query type_param_predicates(
919        key: (LocalDefId, LocalDefId, rustc_span::Ident)
920    ) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]> {
921        desc { |tcx| "computing the bounds for type parameter `{}`", tcx.hir_ty_param_name(key.1) }
922    }
923
924    query trait_def(key: DefId) -> &'tcx ty::TraitDef {
925        desc { |tcx| "computing trait definition for `{}`", tcx.def_path_str(key) }
926        arena_cache
927        cache_on_disk_if { key.is_local() }
928        separate_provide_extern
929    }
930    query adt_def(key: DefId) -> ty::AdtDef<'tcx> {
931        desc { |tcx| "computing ADT definition for `{}`", tcx.def_path_str(key) }
932        cache_on_disk_if { key.is_local() }
933        separate_provide_extern
934    }
935    query adt_destructor(key: DefId) -> Option<ty::Destructor> {
936        desc { |tcx| "computing `Drop` impl for `{}`", tcx.def_path_str(key) }
937        cache_on_disk_if { key.is_local() }
938        separate_provide_extern
939    }
940    query adt_async_destructor(key: DefId) -> Option<ty::AsyncDestructor> {
941        desc { |tcx| "computing `AsyncDrop` impl for `{}`", tcx.def_path_str(key) }
942        cache_on_disk_if { key.is_local() }
943        separate_provide_extern
944    }
945    query adt_sizedness_constraint(
946        key: (DefId, SizedTraitKind)
947    ) -> Option<ty::EarlyBinder<'tcx, Ty<'tcx>>> {
948        desc { |tcx| "computing the sizedness constraint for `{}`", tcx.def_path_str(key.0) }
949    }
950
951    query adt_dtorck_constraint(
952        key: DefId
953    ) -> &'tcx DropckConstraint<'tcx> {
954        desc { |tcx| "computing drop-check constraints for `{}`", tcx.def_path_str(key) }
955    }
956
957    /// Returns the constness of the function-like[^1] definition given by `DefId`.
958    ///
959    /// Tuple struct/variant constructors are *always* const, foreign functions are
960    /// *never* const. The rest is const iff marked with keyword `const` (or rather
961    /// its parent in the case of associated functions).
962    ///
963    /// <div class="warning">
964    ///
965    /// **Do not call this query** directly. It is only meant to cache the base data for the
966    /// higher-level functions. Consider using `is_const_fn` or `is_const_trait_impl` instead.
967    ///
968    /// Also note that neither of them takes into account feature gates, stability and
969    /// const predicates/conditions!
970    ///
971    /// </div>
972    ///
973    /// # Panics
974    ///
975    /// This query will panic if the given definition is not function-like[^1].
976    ///
977    /// [^1]: Tuple struct/variant constructors, closures and free, associated and foreign functions.
978    query constness(key: DefId) -> hir::Constness {
979        desc { |tcx| "checking if item is const: `{}`", tcx.def_path_str(key) }
980        separate_provide_extern
981        feedable
982    }
983
984    query asyncness(key: DefId) -> ty::Asyncness {
985        desc { |tcx| "checking if the function is async: `{}`", tcx.def_path_str(key) }
986        separate_provide_extern
987    }
988
989    /// Returns `true` if calls to the function may be promoted.
990    ///
991    /// This is either because the function is e.g., a tuple-struct or tuple-variant
992    /// constructor, or because it has the `#[rustc_promotable]` attribute. The attribute should
993    /// be removed in the future in favour of some form of check which figures out whether the
994    /// function does not inspect the bits of any of its arguments (so is essentially just a
995    /// constructor function).
996    query is_promotable_const_fn(key: DefId) -> bool {
997        desc { |tcx| "checking if item is promotable: `{}`", tcx.def_path_str(key) }
998    }
999
1000    /// The body of the coroutine, modified to take its upvars by move rather than by ref.
1001    ///
1002    /// This is used by coroutine-closures, which must return a different flavor of coroutine
1003    /// when called using `AsyncFnOnce::call_once`. It is produced by the `ByMoveBody` pass which
1004    /// is run right after building the initial MIR, and will only be populated for coroutines
1005    /// which come out of the async closure desugaring.
1006    query coroutine_by_move_body_def_id(def_id: DefId) -> DefId {
1007        desc { |tcx| "looking up the coroutine by-move body for `{}`", tcx.def_path_str(def_id) }
1008        separate_provide_extern
1009    }
1010
1011    /// Returns `Some(coroutine_kind)` if the node pointed to by `def_id` is a coroutine.
1012    query coroutine_kind(def_id: DefId) -> Option<hir::CoroutineKind> {
1013        desc { |tcx| "looking up coroutine kind of `{}`", tcx.def_path_str(def_id) }
1014        separate_provide_extern
1015        feedable
1016    }
1017
1018    query coroutine_for_closure(def_id: DefId) -> DefId {
1019        desc { |_tcx| "Given a coroutine-closure def id, return the def id of the coroutine returned by it" }
1020        separate_provide_extern
1021    }
1022
1023    query coroutine_hidden_types(
1024        def_id: DefId,
1025    ) -> ty::EarlyBinder<'tcx, ty::Binder<'tcx, ty::CoroutineWitnessTypes<TyCtxt<'tcx>>>> {
1026        desc { "looking up the hidden types stored across await points in a coroutine" }
1027    }
1028
1029    /// Gets a map with the variances of every item in the local crate.
1030    ///
1031    /// <div class="warning">
1032    ///
1033    /// **Do not call this query** directly, use [`Self::variances_of`] instead.
1034    ///
1035    /// </div>
1036    query crate_variances(_: ()) -> &'tcx ty::CrateVariancesMap<'tcx> {
1037        arena_cache
1038        desc { "computing the variances for items in this crate" }
1039    }
1040
1041    /// Returns the (inferred) variances of the item given by `DefId`.
1042    ///
1043    /// The list of variances corresponds to the list of (early-bound) generic
1044    /// parameters of the item (including its parents).
1045    ///
1046    /// **Tip**: You can use `#[rustc_variance]` on an item to basically print the
1047    /// result of this query for use in UI tests or for debugging purposes.
1048    query variances_of(def_id: DefId) -> &'tcx [ty::Variance] {
1049        desc { |tcx| "computing the variances of `{}`", tcx.def_path_str(def_id) }
1050        cache_on_disk_if { def_id.is_local() }
1051        separate_provide_extern
1052        cycle_delay_bug
1053    }
1054
1055    /// Gets a map with the inferred outlives-predicates of every item in the local crate.
1056    ///
1057    /// <div class="warning">
1058    ///
1059    /// **Do not call this query** directly, use [`Self::inferred_outlives_of`] instead.
1060    ///
1061    /// </div>
1062    query inferred_outlives_crate(_: ()) -> &'tcx ty::CratePredicatesMap<'tcx> {
1063        arena_cache
1064        desc { "computing the inferred outlives-predicates for items in this crate" }
1065    }
1066
1067    /// Maps from an impl/trait or struct/variant `DefId`
1068    /// to a list of the `DefId`s of its associated items or fields.
1069    query associated_item_def_ids(key: DefId) -> &'tcx [DefId] {
1070        desc { |tcx| "collecting associated items or fields of `{}`", tcx.def_path_str(key) }
1071        cache_on_disk_if { key.is_local() }
1072        separate_provide_extern
1073    }
1074
1075    /// Maps from a trait/impl item to the trait/impl item "descriptor".
1076    query associated_item(key: DefId) -> ty::AssocItem {
1077        desc { |tcx| "computing associated item data for `{}`", tcx.def_path_str(key) }
1078        cache_on_disk_if { key.is_local() }
1079        separate_provide_extern
1080        feedable
1081    }
1082
1083    /// Collects the associated items defined on a trait or impl.
1084    query associated_items(key: DefId) -> &'tcx ty::AssocItems {
1085        arena_cache
1086        desc { |tcx| "collecting associated items of `{}`", tcx.def_path_str(key) }
1087    }
1088
1089    /// Maps from associated items on a trait to the corresponding associated
1090    /// item on the impl specified by `impl_id`.
1091    ///
1092    /// For example, with the following code
1093    ///
1094    /// ```
1095    /// struct Type {}
1096    ///                         // DefId
1097    /// trait Trait {           // trait_id
1098    ///     fn f();             // trait_f
1099    ///     fn g() {}           // trait_g
1100    /// }
1101    ///
1102    /// impl Trait for Type {   // impl_id
1103    ///     fn f() {}           // impl_f
1104    ///     fn g() {}           // impl_g
1105    /// }
1106    /// ```
1107    ///
1108    /// The map returned for `tcx.impl_item_implementor_ids(impl_id)` would be
1109    ///`{ trait_f: impl_f, trait_g: impl_g }`
1110    query impl_item_implementor_ids(impl_id: DefId) -> &'tcx DefIdMap<DefId> {
1111        arena_cache
1112        desc { |tcx| "comparing impl items against trait for `{}`", tcx.def_path_str(impl_id) }
1113    }
1114
1115    /// Given the `item_def_id` of a trait or impl, return a mapping from associated fn def id
1116    /// to its associated type items that correspond to the RPITITs in its signature.
1117    query associated_types_for_impl_traits_in_trait_or_impl(item_def_id: DefId) -> &'tcx DefIdMap<Vec<DefId>> {
1118        arena_cache
1119        desc { |tcx| "synthesizing RPITIT items for the opaque types for methods in `{}`", tcx.def_path_str(item_def_id) }
1120        separate_provide_extern
1121    }
1122
1123    /// Given an `impl_id`, return the trait it implements along with some header information.
1124    query impl_trait_header(impl_id: DefId) -> ty::ImplTraitHeader<'tcx> {
1125        desc { |tcx| "computing trait implemented by `{}`", tcx.def_path_str(impl_id) }
1126        cache_on_disk_if { impl_id.is_local() }
1127        separate_provide_extern
1128    }
1129
1130    /// Given an `impl_def_id`, return true if the self type is guaranteed to be unsized due
1131    /// to either being one of the built-in unsized types (str/slice/dyn) or to be a struct
1132    /// whose tail is one of those types.
1133    query impl_self_is_guaranteed_unsized(impl_def_id: DefId) -> bool {
1134        desc { |tcx| "computing whether `{}` has a guaranteed unsized self type", tcx.def_path_str(impl_def_id) }
1135    }
1136
1137    /// Maps a `DefId` of a type to a list of its inherent impls.
1138    /// Contains implementations of methods that are inherent to a type.
1139    /// Methods in these implementations don't need to be exported.
1140    query inherent_impls(key: DefId) -> &'tcx [DefId] {
1141        desc { |tcx| "collecting inherent impls for `{}`", tcx.def_path_str(key) }
1142        cache_on_disk_if { key.is_local() }
1143        separate_provide_extern
1144    }
1145
1146    query incoherent_impls(key: SimplifiedType) -> &'tcx [DefId] {
1147        desc { |tcx| "collecting all inherent impls for `{:?}`", key }
1148    }
1149
1150    /// Unsafety-check this `LocalDefId`.
1151    query check_transmutes(key: LocalDefId) {
1152        desc { |tcx| "check transmute calls inside `{}`", tcx.def_path_str(key) }
1153    }
1154
1155    /// Unsafety-check this `LocalDefId`.
1156    query check_unsafety(key: LocalDefId) {
1157        desc { |tcx| "unsafety-checking `{}`", tcx.def_path_str(key) }
1158    }
1159
1160    /// Checks well-formedness of tail calls (`become f()`).
1161    query check_tail_calls(key: LocalDefId) -> Result<(), rustc_errors::ErrorGuaranteed> {
1162        desc { |tcx| "tail-call-checking `{}`", tcx.def_path_str(key) }
1163        return_result_from_ensure_ok
1164    }
1165
1166    /// Returns the types assumed to be well formed while "inside" of the given item.
1167    ///
1168    /// Note that we've liberated the late bound regions of function signatures, so
1169    /// this can not be used to check whether these types are well formed.
1170    query assumed_wf_types(key: LocalDefId) -> &'tcx [(Ty<'tcx>, Span)] {
1171        desc { |tcx| "computing the implied bounds of `{}`", tcx.def_path_str(key) }
1172    }
1173
1174    /// We need to store the assumed_wf_types for an RPITIT so that impls of foreign
1175    /// traits with return-position impl trait in traits can inherit the right wf types.
1176    query assumed_wf_types_for_rpitit(key: DefId) -> &'tcx [(Ty<'tcx>, Span)] {
1177        desc { |tcx| "computing the implied bounds of `{}`", tcx.def_path_str(key) }
1178        separate_provide_extern
1179    }
1180
1181    /// Computes the signature of the function.
1182    query fn_sig(key: DefId) -> ty::EarlyBinder<'tcx, ty::PolyFnSig<'tcx>> {
1183        desc { |tcx| "computing function signature of `{}`", tcx.def_path_str(key) }
1184        cache_on_disk_if { key.is_local() }
1185        separate_provide_extern
1186        cycle_delay_bug
1187    }
1188
1189    /// Performs lint checking for the module.
1190    query lint_mod(key: LocalModDefId) {
1191        desc { |tcx| "linting {}", describe_as_module(key, tcx) }
1192    }
1193
1194    query check_unused_traits(_: ()) {
1195        desc { "checking unused trait imports in crate" }
1196    }
1197
1198    /// Checks the attributes in the module.
1199    query check_mod_attrs(key: LocalModDefId) {
1200        desc { |tcx| "checking attributes in {}", describe_as_module(key, tcx) }
1201    }
1202
1203    /// Checks for uses of unstable APIs in the module.
1204    query check_mod_unstable_api_usage(key: LocalModDefId) {
1205        desc { |tcx| "checking for unstable API usage in {}", describe_as_module(key, tcx) }
1206    }
1207
1208    query check_mod_privacy(key: LocalModDefId) {
1209        desc { |tcx| "checking privacy in {}", describe_as_module(key.to_local_def_id(), tcx) }
1210    }
1211
1212    query check_liveness(key: LocalDefId) -> &'tcx rustc_index::bit_set::DenseBitSet<abi::FieldIdx> {
1213        arena_cache
1214        desc { |tcx| "checking liveness of variables in `{}`", tcx.def_path_str(key.to_def_id()) }
1215        cache_on_disk_if(tcx) { tcx.is_typeck_child(key.to_def_id()) }
1216    }
1217
1218    /// Return the live symbols in the crate for dead code check.
1219    ///
1220    /// The second return value maps from ADTs to ignored derived traits (e.g. Debug and Clone).
1221    query live_symbols_and_ignored_derived_traits(_: ()) -> &'tcx Result<(
1222        LocalDefIdSet,
1223        LocalDefIdMap<FxIndexSet<DefId>>,
1224    ), ErrorGuaranteed> {
1225        arena_cache
1226        desc { "finding live symbols in crate" }
1227    }
1228
1229    query check_mod_deathness(key: LocalModDefId) {
1230        desc { |tcx| "checking deathness of variables in {}", describe_as_module(key, tcx) }
1231    }
1232
1233    query check_type_wf(key: ()) -> Result<(), ErrorGuaranteed> {
1234        desc { "checking that types are well-formed" }
1235        return_result_from_ensure_ok
1236    }
1237
1238    /// Caches `CoerceUnsized` kinds for impls on custom types.
1239    query coerce_unsized_info(key: DefId) -> Result<ty::adjustment::CoerceUnsizedInfo, ErrorGuaranteed> {
1240        desc { |tcx| "computing CoerceUnsized info for `{}`", tcx.def_path_str(key) }
1241        cache_on_disk_if { key.is_local() }
1242        separate_provide_extern
1243        return_result_from_ensure_ok
1244    }
1245
1246    query typeck(key: LocalDefId) -> &'tcx ty::TypeckResults<'tcx> {
1247        desc { |tcx| "type-checking `{}`", tcx.def_path_str(key) }
1248        cache_on_disk_if(tcx) { !tcx.is_typeck_child(key.to_def_id()) }
1249    }
1250
1251    query used_trait_imports(key: LocalDefId) -> &'tcx UnordSet<LocalDefId> {
1252        desc { |tcx| "finding used_trait_imports `{}`", tcx.def_path_str(key) }
1253        cache_on_disk_if { true }
1254    }
1255
1256    query coherent_trait(def_id: DefId) -> Result<(), ErrorGuaranteed> {
1257        desc { |tcx| "coherence checking all impls of trait `{}`", tcx.def_path_str(def_id) }
1258        return_result_from_ensure_ok
1259    }
1260
1261    /// Borrow-checks the given typeck root, e.g. functions, const/static items,
1262    /// and its children, e.g. closures, inline consts.
1263    query mir_borrowck(key: LocalDefId) -> Result<
1264        &'tcx FxIndexMap<LocalDefId, ty::DefinitionSiteHiddenType<'tcx>>,
1265        ErrorGuaranteed
1266    > {
1267        desc { |tcx| "borrow-checking `{}`", tcx.def_path_str(key) }
1268    }
1269
1270    /// Gets a complete map from all types to their inherent impls.
1271    ///
1272    /// <div class="warning">
1273    ///
1274    /// **Not meant to be used** directly outside of coherence.
1275    ///
1276    /// </div>
1277    query crate_inherent_impls(k: ()) -> (&'tcx CrateInherentImpls, Result<(), ErrorGuaranteed>) {
1278        desc { "finding all inherent impls defined in crate" }
1279    }
1280
1281    /// Checks all types in the crate for overlap in their inherent impls. Reports errors.
1282    ///
1283    /// <div class="warning">
1284    ///
1285    /// **Not meant to be used** directly outside of coherence.
1286    ///
1287    /// </div>
1288    query crate_inherent_impls_validity_check(_: ()) -> Result<(), ErrorGuaranteed> {
1289        desc { "check for inherent impls that should not be defined in crate" }
1290        return_result_from_ensure_ok
1291    }
1292
1293    /// Checks all types in the crate for overlap in their inherent impls. Reports errors.
1294    ///
1295    /// <div class="warning">
1296    ///
1297    /// **Not meant to be used** directly outside of coherence.
1298    ///
1299    /// </div>
1300    query crate_inherent_impls_overlap_check(_: ()) -> Result<(), ErrorGuaranteed> {
1301        desc { "check for overlap between inherent impls defined in this crate" }
1302        return_result_from_ensure_ok
1303    }
1304
1305    /// Checks whether all impls in the crate pass the overlap check, returning
1306    /// which impls fail it. If all impls are correct, the returned slice is empty.
1307    query orphan_check_impl(key: LocalDefId) -> Result<(), ErrorGuaranteed> {
1308        desc { |tcx|
1309            "checking whether impl `{}` follows the orphan rules",
1310            tcx.def_path_str(key),
1311        }
1312        return_result_from_ensure_ok
1313    }
1314
1315    /// Return the set of (transitive) callees that may result in a recursive call to `key`,
1316    /// if we were able to walk all callees.
1317    query mir_callgraph_cyclic(key: LocalDefId) -> &'tcx Option<UnordSet<LocalDefId>> {
1318        fatal_cycle
1319        arena_cache
1320        desc { |tcx|
1321            "computing (transitive) callees of `{}` that may recurse",
1322            tcx.def_path_str(key),
1323        }
1324        cache_on_disk_if { true }
1325    }
1326
1327    /// Obtain all the calls into other local functions
1328    query mir_inliner_callees(key: ty::InstanceKind<'tcx>) -> &'tcx [(DefId, GenericArgsRef<'tcx>)] {
1329        fatal_cycle
1330        desc { |tcx|
1331            "computing all local function calls in `{}`",
1332            tcx.def_path_str(key.def_id()),
1333        }
1334    }
1335
1336    /// Computes the tag (if any) for a given type and variant.
1337    ///
1338    /// `None` means that the variant doesn't need a tag (because it is niched).
1339    ///
1340    /// # Panics
1341    ///
1342    /// This query will panic for uninhabited variants and if the passed type is not an enum.
1343    query tag_for_variant(
1344        key: PseudoCanonicalInput<'tcx, (Ty<'tcx>, abi::VariantIdx)>,
1345    ) -> Option<ty::ScalarInt> {
1346        desc { "computing variant tag for enum" }
1347    }
1348
1349    /// Evaluates a constant and returns the computed allocation.
1350    ///
1351    /// <div class="warning">
1352    ///
1353    /// **Do not call this query** directly, use [`Self::eval_to_const_value_raw`] or
1354    /// [`Self::eval_to_valtree`] instead.
1355    ///
1356    /// </div>
1357    query eval_to_allocation_raw(key: ty::PseudoCanonicalInput<'tcx, GlobalId<'tcx>>)
1358        -> EvalToAllocationRawResult<'tcx> {
1359        desc { |tcx|
1360            "const-evaluating + checking `{}`",
1361            key.value.display(tcx)
1362        }
1363        cache_on_disk_if { true }
1364    }
1365
1366    /// Evaluate a static's initializer, returning the allocation of the initializer's memory.
1367    query eval_static_initializer(key: DefId) -> EvalStaticInitializerRawResult<'tcx> {
1368        desc { |tcx|
1369            "evaluating initializer of static `{}`",
1370            tcx.def_path_str(key)
1371        }
1372        cache_on_disk_if { key.is_local() }
1373        separate_provide_extern
1374        feedable
1375    }
1376
1377    /// Evaluates const items or anonymous constants[^1] into a representation
1378    /// suitable for the type system and const generics.
1379    ///
1380    /// <div class="warning">
1381    ///
1382    /// **Do not call this** directly, use one of the following wrappers:
1383    /// [`TyCtxt::const_eval_poly`], [`TyCtxt::const_eval_resolve`],
1384    /// [`TyCtxt::const_eval_instance`], or [`TyCtxt::const_eval_global_id`].
1385    ///
1386    /// </div>
1387    ///
1388    /// [^1]: Such as enum variant explicit discriminants or array lengths.
1389    query eval_to_const_value_raw(key: ty::PseudoCanonicalInput<'tcx, GlobalId<'tcx>>)
1390        -> EvalToConstValueResult<'tcx> {
1391        desc { |tcx|
1392            "simplifying constant for the type system `{}`",
1393            key.value.display(tcx)
1394        }
1395        depth_limit
1396        cache_on_disk_if { true }
1397    }
1398
1399    /// Evaluate a constant and convert it to a type level constant or
1400    /// return `None` if that is not possible.
1401    query eval_to_valtree(
1402        key: ty::PseudoCanonicalInput<'tcx, GlobalId<'tcx>>
1403    ) -> EvalToValTreeResult<'tcx> {
1404        desc { "evaluating type-level constant" }
1405    }
1406
1407    /// Converts a type-level constant value into a MIR constant value.
1408    query valtree_to_const_val(key: ty::Value<'tcx>) -> mir::ConstValue {
1409        desc { "converting type-level constant value to MIR constant value"}
1410    }
1411
1412    // FIXME get rid of this with valtrees
1413    query lit_to_const(
1414        key: LitToConstInput<'tcx>
1415    ) -> ty::Const<'tcx> {
1416        desc { "converting literal to const" }
1417    }
1418
1419    query check_match(key: LocalDefId) -> Result<(), rustc_errors::ErrorGuaranteed> {
1420        desc { |tcx| "match-checking `{}`", tcx.def_path_str(key) }
1421        return_result_from_ensure_ok
1422    }
1423
1424    /// Performs part of the privacy check and computes effective visibilities.
1425    query effective_visibilities(_: ()) -> &'tcx EffectiveVisibilities {
1426        eval_always
1427        desc { "checking effective visibilities" }
1428    }
1429    query check_private_in_public(module_def_id: LocalModDefId) {
1430        desc { |tcx|
1431            "checking for private elements in public interfaces for {}",
1432            describe_as_module(module_def_id, tcx)
1433        }
1434    }
1435
1436    query reachable_set(_: ()) -> &'tcx LocalDefIdSet {
1437        arena_cache
1438        desc { "reachability" }
1439        cache_on_disk_if { true }
1440    }
1441
1442    /// Per-body `region::ScopeTree`. The `DefId` should be the owner `DefId` for the body;
1443    /// in the case of closures, this will be redirected to the enclosing function.
1444    query region_scope_tree(def_id: DefId) -> &'tcx crate::middle::region::ScopeTree {
1445        desc { |tcx| "computing drop scopes for `{}`", tcx.def_path_str(def_id) }
1446    }
1447
1448    /// Generates a MIR body for the shim.
1449    query mir_shims(key: ty::InstanceKind<'tcx>) -> &'tcx mir::Body<'tcx> {
1450        arena_cache
1451        desc {
1452            |tcx| "generating MIR shim for `{}`, instance={:?}",
1453            tcx.def_path_str(key.def_id()),
1454            key
1455        }
1456    }
1457
1458    /// The `symbol_name` query provides the symbol name for calling a
1459    /// given instance from the local crate. In particular, it will also
1460    /// look up the correct symbol name of instances from upstream crates.
1461    query symbol_name(key: ty::Instance<'tcx>) -> ty::SymbolName<'tcx> {
1462        desc { "computing the symbol for `{}`", key }
1463        cache_on_disk_if { true }
1464    }
1465
1466    query def_kind(def_id: DefId) -> DefKind {
1467        desc { |tcx| "looking up definition kind of `{}`", tcx.def_path_str(def_id) }
1468        cache_on_disk_if { def_id.is_local() }
1469        separate_provide_extern
1470        feedable
1471    }
1472
1473    /// Gets the span for the definition.
1474    query def_span(def_id: DefId) -> Span {
1475        desc { |tcx| "looking up span for `{}`", tcx.def_path_str(def_id) }
1476        cache_on_disk_if { def_id.is_local() }
1477        separate_provide_extern
1478        feedable
1479    }
1480
1481    /// Gets the span for the identifier of the definition.
1482    query def_ident_span(def_id: DefId) -> Option<Span> {
1483        desc { |tcx| "looking up span for `{}`'s identifier", tcx.def_path_str(def_id) }
1484        cache_on_disk_if { def_id.is_local() }
1485        separate_provide_extern
1486        feedable
1487    }
1488
1489    /// Gets the span for the type of the definition.
1490    /// Panics if it is not a definition that has a single type.
1491    query ty_span(def_id: LocalDefId) -> Span {
1492        desc { |tcx| "looking up span for `{}`'s type", tcx.def_path_str(def_id) }
1493        cache_on_disk_if { true }
1494    }
1495
1496    query lookup_stability(def_id: DefId) -> Option<hir::Stability> {
1497        desc { |tcx| "looking up stability of `{}`", tcx.def_path_str(def_id) }
1498        cache_on_disk_if { def_id.is_local() }
1499        separate_provide_extern
1500    }
1501
1502    query lookup_const_stability(def_id: DefId) -> Option<hir::ConstStability> {
1503        desc { |tcx| "looking up const stability of `{}`", tcx.def_path_str(def_id) }
1504        cache_on_disk_if { def_id.is_local() }
1505        separate_provide_extern
1506    }
1507
1508    query lookup_default_body_stability(def_id: DefId) -> Option<hir::DefaultBodyStability> {
1509        desc { |tcx| "looking up default body stability of `{}`", tcx.def_path_str(def_id) }
1510        separate_provide_extern
1511    }
1512
1513    query should_inherit_track_caller(def_id: DefId) -> bool {
1514        desc { |tcx| "computing should_inherit_track_caller of `{}`", tcx.def_path_str(def_id) }
1515    }
1516
1517    query inherited_align(def_id: DefId) -> Option<Align> {
1518        desc { |tcx| "computing inherited_align of `{}`", tcx.def_path_str(def_id) }
1519    }
1520
1521    query lookup_deprecation_entry(def_id: DefId) -> Option<DeprecationEntry> {
1522        desc { |tcx| "checking whether `{}` is deprecated", tcx.def_path_str(def_id) }
1523        cache_on_disk_if { def_id.is_local() }
1524        separate_provide_extern
1525    }
1526
1527    /// Determines whether an item is annotated with `#[doc(hidden)]`.
1528    query is_doc_hidden(def_id: DefId) -> bool {
1529        desc { |tcx| "checking whether `{}` is `doc(hidden)`", tcx.def_path_str(def_id) }
1530        separate_provide_extern
1531    }
1532
1533    /// Determines whether an item is annotated with `#[doc(notable_trait)]`.
1534    query is_doc_notable_trait(def_id: DefId) -> bool {
1535        desc { |tcx| "checking whether `{}` is `doc(notable_trait)`", tcx.def_path_str(def_id) }
1536    }
1537
1538    /// Returns the attributes on the item at `def_id`.
1539    ///
1540    /// Do not use this directly, use `tcx.get_attrs` instead.
1541    query attrs_for_def(def_id: DefId) -> &'tcx [hir::Attribute] {
1542        desc { |tcx| "collecting attributes of `{}`", tcx.def_path_str(def_id) }
1543        separate_provide_extern
1544    }
1545
1546    /// Returns the `CodegenFnAttrs` for the item at `def_id`.
1547    ///
1548    /// If possible, use `tcx.codegen_instance_attrs` instead. That function takes the
1549    /// instance kind into account.
1550    ///
1551    /// For example, the `#[naked]` attribute should be applied for `InstanceKind::Item`,
1552    /// but should not be applied if the instance kind is `InstanceKind::ReifyShim`.
1553    /// Using this query would include the attribute regardless of the actual instance
1554    /// kind at the call site.
1555    query codegen_fn_attrs(def_id: DefId) -> &'tcx CodegenFnAttrs {
1556        desc { |tcx| "computing codegen attributes of `{}`", tcx.def_path_str(def_id) }
1557        arena_cache
1558        cache_on_disk_if { def_id.is_local() }
1559        separate_provide_extern
1560        feedable
1561    }
1562
1563    query asm_target_features(def_id: DefId) -> &'tcx FxIndexSet<Symbol> {
1564        desc { |tcx| "computing target features for inline asm of `{}`", tcx.def_path_str(def_id) }
1565    }
1566
1567    query fn_arg_idents(def_id: DefId) -> &'tcx [Option<rustc_span::Ident>] {
1568        desc { |tcx| "looking up function parameter identifiers for `{}`", tcx.def_path_str(def_id) }
1569        separate_provide_extern
1570    }
1571
1572    /// Gets the rendered value of the specified constant or associated constant.
1573    /// Used by rustdoc.
1574    query rendered_const(def_id: DefId) -> &'tcx String {
1575        arena_cache
1576        desc { |tcx| "rendering constant initializer of `{}`", tcx.def_path_str(def_id) }
1577        separate_provide_extern
1578    }
1579
1580    /// Gets the rendered precise capturing args for an opaque for use in rustdoc.
1581    query rendered_precise_capturing_args(def_id: DefId) -> Option<&'tcx [PreciseCapturingArgKind<Symbol, Symbol>]> {
1582        desc { |tcx| "rendering precise capturing args for `{}`", tcx.def_path_str(def_id) }
1583        separate_provide_extern
1584    }
1585
1586    query impl_parent(def_id: DefId) -> Option<DefId> {
1587        desc { |tcx| "computing specialization parent impl of `{}`", tcx.def_path_str(def_id) }
1588        separate_provide_extern
1589    }
1590
1591    query is_ctfe_mir_available(key: DefId) -> bool {
1592        desc { |tcx| "checking if item has CTFE MIR available: `{}`", tcx.def_path_str(key) }
1593        cache_on_disk_if { key.is_local() }
1594        separate_provide_extern
1595    }
1596    query is_mir_available(key: DefId) -> bool {
1597        desc { |tcx| "checking if item has MIR available: `{}`", tcx.def_path_str(key) }
1598        cache_on_disk_if { key.is_local() }
1599        separate_provide_extern
1600    }
1601
1602    query own_existential_vtable_entries(
1603        key: DefId
1604    ) -> &'tcx [DefId] {
1605        desc { |tcx| "finding all existential vtable entries for trait `{}`", tcx.def_path_str(key) }
1606    }
1607
1608    query vtable_entries(key: ty::TraitRef<'tcx>)
1609                        -> &'tcx [ty::VtblEntry<'tcx>] {
1610        desc { |tcx| "finding all vtable entries for trait `{}`", tcx.def_path_str(key.def_id) }
1611    }
1612
1613    query first_method_vtable_slot(key: ty::TraitRef<'tcx>) -> usize {
1614        desc { |tcx| "finding the slot within the vtable of `{}` for the implementation of `{}`", key.self_ty(), key.print_only_trait_name() }
1615    }
1616
1617    query supertrait_vtable_slot(key: (Ty<'tcx>, Ty<'tcx>)) -> Option<usize> {
1618        desc { |tcx| "finding the slot within vtable for trait object `{}` vtable ptr during trait upcasting coercion from `{}` vtable",
1619            key.1, key.0 }
1620    }
1621
1622    query vtable_allocation(key: (Ty<'tcx>, Option<ty::ExistentialTraitRef<'tcx>>)) -> mir::interpret::AllocId {
1623        desc { |tcx| "vtable const allocation for <{} as {}>",
1624            key.0,
1625            key.1.map(|trait_ref| format!("{trait_ref}")).unwrap_or_else(|| "_".to_owned())
1626        }
1627    }
1628
1629    query codegen_select_candidate(
1630        key: PseudoCanonicalInput<'tcx, ty::TraitRef<'tcx>>
1631    ) -> Result<&'tcx ImplSource<'tcx, ()>, CodegenObligationError> {
1632        cache_on_disk_if { true }
1633        desc { |tcx| "computing candidate for `{}`", key.value }
1634    }
1635
1636    /// Return all `impl` blocks in the current crate.
1637    query all_local_trait_impls(_: ()) -> &'tcx rustc_data_structures::fx::FxIndexMap<DefId, Vec<LocalDefId>> {
1638        desc { "finding local trait impls" }
1639    }
1640
1641    /// Return all `impl` blocks of the given trait in the current crate.
1642    query local_trait_impls(trait_id: DefId) -> &'tcx [LocalDefId] {
1643        desc { "finding local trait impls of `{}`", tcx.def_path_str(trait_id) }
1644    }
1645
1646    /// Given a trait `trait_id`, return all known `impl` blocks.
1647    query trait_impls_of(trait_id: DefId) -> &'tcx ty::trait_def::TraitImpls {
1648        arena_cache
1649        desc { |tcx| "finding trait impls of `{}`", tcx.def_path_str(trait_id) }
1650    }
1651
1652    query specialization_graph_of(trait_id: DefId) -> Result<&'tcx specialization_graph::Graph, ErrorGuaranteed> {
1653        desc { |tcx| "building specialization graph of trait `{}`", tcx.def_path_str(trait_id) }
1654        cache_on_disk_if { true }
1655        return_result_from_ensure_ok
1656    }
1657    query dyn_compatibility_violations(trait_id: DefId) -> &'tcx [DynCompatibilityViolation] {
1658        desc { |tcx| "determining dyn-compatibility of trait `{}`", tcx.def_path_str(trait_id) }
1659    }
1660    query is_dyn_compatible(trait_id: DefId) -> bool {
1661        desc { |tcx| "checking if trait `{}` is dyn-compatible", tcx.def_path_str(trait_id) }
1662    }
1663
1664    /// Gets the ParameterEnvironment for a given item; this environment
1665    /// will be in "user-facing" mode, meaning that it is suitable for
1666    /// type-checking etc, and it does not normalize specializable
1667    /// associated types.
1668    ///
1669    /// You should almost certainly not use this. If you already have an InferCtxt, then
1670    /// you should also probably have a `ParamEnv` from when it was built. If you don't,
1671    /// then you should take a `TypingEnv` to ensure that you handle opaque types correctly.
1672    query param_env(def_id: DefId) -> ty::ParamEnv<'tcx> {
1673        desc { |tcx| "computing normalized predicates of `{}`", tcx.def_path_str(def_id) }
1674        feedable
1675    }
1676
1677    /// Like `param_env`, but returns the `ParamEnv` after all opaque types have been
1678    /// replaced with their hidden type. This is used in the old trait solver
1679    /// when in `PostAnalysis` mode and should not be called directly.
1680    query typing_env_normalized_for_post_analysis(def_id: DefId) -> ty::TypingEnv<'tcx> {
1681        desc { |tcx| "computing revealed normalized predicates of `{}`", tcx.def_path_str(def_id) }
1682    }
1683
1684    /// Trait selection queries. These are best used by invoking `ty.is_copy_modulo_regions()`,
1685    /// `ty.is_copy()`, etc, since that will prune the environment where possible.
1686    query is_copy_raw(env: ty::PseudoCanonicalInput<'tcx, Ty<'tcx>>) -> bool {
1687        desc { "computing whether `{}` is `Copy`", env.value }
1688    }
1689    /// Trait selection queries. These are best used by invoking `ty.is_use_cloned_modulo_regions()`,
1690    /// `ty.is_use_cloned()`, etc, since that will prune the environment where possible.
1691    query is_use_cloned_raw(env: ty::PseudoCanonicalInput<'tcx, Ty<'tcx>>) -> bool {
1692        desc { "computing whether `{}` is `UseCloned`", env.value }
1693    }
1694    /// Query backing `Ty::is_sized`.
1695    query is_sized_raw(env: ty::PseudoCanonicalInput<'tcx, Ty<'tcx>>) -> bool {
1696        desc { "computing whether `{}` is `Sized`", env.value }
1697    }
1698    /// Query backing `Ty::is_freeze`.
1699    query is_freeze_raw(env: ty::PseudoCanonicalInput<'tcx, Ty<'tcx>>) -> bool {
1700        desc { "computing whether `{}` is freeze", env.value }
1701    }
1702    /// Query backing `Ty::is_unpin`.
1703    query is_unpin_raw(env: ty::PseudoCanonicalInput<'tcx, Ty<'tcx>>) -> bool {
1704        desc { "computing whether `{}` is `Unpin`", env.value }
1705    }
1706    /// Query backing `Ty::is_async_drop`.
1707    query is_async_drop_raw(env: ty::PseudoCanonicalInput<'tcx, Ty<'tcx>>) -> bool {
1708        desc { "computing whether `{}` is `AsyncDrop`", env.value }
1709    }
1710    /// Query backing `Ty::needs_drop`.
1711    query needs_drop_raw(env: ty::PseudoCanonicalInput<'tcx, Ty<'tcx>>) -> bool {
1712        desc { "computing whether `{}` needs drop", env.value }
1713    }
1714    /// Query backing `Ty::needs_async_drop`.
1715    query needs_async_drop_raw(env: ty::PseudoCanonicalInput<'tcx, Ty<'tcx>>) -> bool {
1716        desc { "computing whether `{}` needs async drop", env.value }
1717    }
1718    /// Query backing `Ty::has_significant_drop_raw`.
1719    query has_significant_drop_raw(env: ty::PseudoCanonicalInput<'tcx, Ty<'tcx>>) -> bool {
1720        desc { "computing whether `{}` has a significant drop", env.value }
1721    }
1722
1723    /// Query backing `Ty::is_structural_eq_shallow`.
1724    ///
1725    /// This is only correct for ADTs. Call `is_structural_eq_shallow` to handle all types
1726    /// correctly.
1727    query has_structural_eq_impl(ty: Ty<'tcx>) -> bool {
1728        desc {
1729            "computing whether `{}` implements `StructuralPartialEq`",
1730            ty
1731        }
1732    }
1733
1734    /// A list of types where the ADT requires drop if and only if any of
1735    /// those types require drop. If the ADT is known to always need drop
1736    /// then `Err(AlwaysRequiresDrop)` is returned.
1737    query adt_drop_tys(def_id: DefId) -> Result<&'tcx ty::List<Ty<'tcx>>, AlwaysRequiresDrop> {
1738        desc { |tcx| "computing when `{}` needs drop", tcx.def_path_str(def_id) }
1739        cache_on_disk_if { true }
1740    }
1741
1742    /// A list of types where the ADT requires async drop if and only if any of
1743    /// those types require async drop. If the ADT is known to always need async drop
1744    /// then `Err(AlwaysRequiresDrop)` is returned.
1745    query adt_async_drop_tys(def_id: DefId) -> Result<&'tcx ty::List<Ty<'tcx>>, AlwaysRequiresDrop> {
1746        desc { |tcx| "computing when `{}` needs async drop", tcx.def_path_str(def_id) }
1747        cache_on_disk_if { true }
1748    }
1749
1750    /// A list of types where the ADT requires drop if and only if any of those types
1751    /// has significant drop. A type marked with the attribute `rustc_insignificant_dtor`
1752    /// is considered to not be significant. A drop is significant if it is implemented
1753    /// by the user or does anything that will have any observable behavior (other than
1754    /// freeing up memory). If the ADT is known to have a significant destructor then
1755    /// `Err(AlwaysRequiresDrop)` is returned.
1756    query adt_significant_drop_tys(def_id: DefId) -> Result<&'tcx ty::List<Ty<'tcx>>, AlwaysRequiresDrop> {
1757        desc { |tcx| "computing when `{}` has a significant destructor", tcx.def_path_str(def_id) }
1758    }
1759
1760    /// Returns a list of types which (a) have a potentially significant destructor
1761    /// and (b) may be dropped as a result of dropping a value of some type `ty`
1762    /// (in the given environment).
1763    ///
1764    /// The idea of "significant" drop is somewhat informal and is used only for
1765    /// diagnostics and edition migrations. The idea is that a significant drop may have
1766    /// some visible side-effect on execution; freeing memory is NOT considered a side-effect.
1767    /// The rules are as follows:
1768    /// * Type with no explicit drop impl do not have significant drop.
1769    /// * Types with a drop impl are assumed to have significant drop unless they have a `#[rustc_insignificant_dtor]` annotation.
1770    ///
1771    /// Note that insignificant drop is a "shallow" property. A type like `Vec<LockGuard>` does not
1772    /// have significant drop but the type `LockGuard` does, and so if `ty  = Vec<LockGuard>`
1773    /// then the return value would be `&[LockGuard]`.
1774    /// *IMPORTANT*: *DO NOT* run this query before promoted MIR body is constructed,
1775    /// because this query partially depends on that query.
1776    /// Otherwise, there is a risk of query cycles.
1777    query list_significant_drop_tys(ty: ty::PseudoCanonicalInput<'tcx, Ty<'tcx>>) -> &'tcx ty::List<Ty<'tcx>> {
1778        desc { |tcx| "computing when `{}` has a significant destructor", ty.value }
1779    }
1780
1781    /// Computes the layout of a type. Note that this implicitly
1782    /// executes in `TypingMode::PostAnalysis`, and will normalize the input type.
1783    query layout_of(
1784        key: ty::PseudoCanonicalInput<'tcx, Ty<'tcx>>
1785    ) -> Result<ty::layout::TyAndLayout<'tcx>, &'tcx ty::layout::LayoutError<'tcx>> {
1786        depth_limit
1787        desc { "computing layout of `{}`", key.value }
1788        // we emit our own error during query cycle handling
1789        cycle_delay_bug
1790    }
1791
1792    /// Compute a `FnAbi` suitable for indirect calls, i.e. to `fn` pointers.
1793    ///
1794    /// NB: this doesn't handle virtual calls - those should use `fn_abi_of_instance`
1795    /// instead, where the instance is an `InstanceKind::Virtual`.
1796    query fn_abi_of_fn_ptr(
1797        key: ty::PseudoCanonicalInput<'tcx, (ty::PolyFnSig<'tcx>, &'tcx ty::List<Ty<'tcx>>)>
1798    ) -> Result<&'tcx rustc_target::callconv::FnAbi<'tcx, Ty<'tcx>>, &'tcx ty::layout::FnAbiError<'tcx>> {
1799        desc { "computing call ABI of `{}` function pointers", key.value.0 }
1800    }
1801
1802    /// Compute a `FnAbi` suitable for declaring/defining an `fn` instance, and for
1803    /// direct calls to an `fn`.
1804    ///
1805    /// NB: that includes virtual calls, which are represented by "direct calls"
1806    /// to an `InstanceKind::Virtual` instance (of `<dyn Trait as Trait>::fn`).
1807    query fn_abi_of_instance(
1808        key: ty::PseudoCanonicalInput<'tcx, (ty::Instance<'tcx>, &'tcx ty::List<Ty<'tcx>>)>
1809    ) -> Result<&'tcx rustc_target::callconv::FnAbi<'tcx, Ty<'tcx>>, &'tcx ty::layout::FnAbiError<'tcx>> {
1810        desc { "computing call ABI of `{}`", key.value.0 }
1811    }
1812
1813    query dylib_dependency_formats(_: CrateNum)
1814                                    -> &'tcx [(CrateNum, LinkagePreference)] {
1815        desc { "getting dylib dependency formats of crate" }
1816        separate_provide_extern
1817    }
1818
1819    query dependency_formats(_: ()) -> &'tcx Arc<crate::middle::dependency_format::Dependencies> {
1820        arena_cache
1821        desc { "getting the linkage format of all dependencies" }
1822    }
1823
1824    query is_compiler_builtins(_: CrateNum) -> bool {
1825        fatal_cycle
1826        desc { "checking if the crate is_compiler_builtins" }
1827        separate_provide_extern
1828    }
1829    query has_global_allocator(_: CrateNum) -> bool {
1830        // This query depends on untracked global state in CStore
1831        eval_always
1832        fatal_cycle
1833        desc { "checking if the crate has_global_allocator" }
1834        separate_provide_extern
1835    }
1836    query has_alloc_error_handler(_: CrateNum) -> bool {
1837        // This query depends on untracked global state in CStore
1838        eval_always
1839        fatal_cycle
1840        desc { "checking if the crate has_alloc_error_handler" }
1841        separate_provide_extern
1842    }
1843    query has_panic_handler(_: CrateNum) -> bool {
1844        fatal_cycle
1845        desc { "checking if the crate has_panic_handler" }
1846        separate_provide_extern
1847    }
1848    query is_profiler_runtime(_: CrateNum) -> bool {
1849        fatal_cycle
1850        desc { "checking if a crate is `#![profiler_runtime]`" }
1851        separate_provide_extern
1852    }
1853    query has_ffi_unwind_calls(key: LocalDefId) -> bool {
1854        desc { |tcx| "checking if `{}` contains FFI-unwind calls", tcx.def_path_str(key) }
1855        cache_on_disk_if { true }
1856    }
1857    query required_panic_strategy(_: CrateNum) -> Option<PanicStrategy> {
1858        fatal_cycle
1859        desc { "getting a crate's required panic strategy" }
1860        separate_provide_extern
1861    }
1862    query panic_in_drop_strategy(_: CrateNum) -> PanicStrategy {
1863        fatal_cycle
1864        desc { "getting a crate's configured panic-in-drop strategy" }
1865        separate_provide_extern
1866    }
1867    query is_no_builtins(_: CrateNum) -> bool {
1868        fatal_cycle
1869        desc { "getting whether a crate has `#![no_builtins]`" }
1870        separate_provide_extern
1871    }
1872    query symbol_mangling_version(_: CrateNum) -> SymbolManglingVersion {
1873        fatal_cycle
1874        desc { "getting a crate's symbol mangling version" }
1875        separate_provide_extern
1876    }
1877
1878    query extern_crate(def_id: CrateNum) -> Option<&'tcx ExternCrate> {
1879        eval_always
1880        desc { "getting crate's ExternCrateData" }
1881        separate_provide_extern
1882    }
1883
1884    query specialization_enabled_in(cnum: CrateNum) -> bool {
1885        desc { "checking whether the crate enabled `specialization`/`min_specialization`" }
1886        separate_provide_extern
1887    }
1888
1889    query specializes(_: (DefId, DefId)) -> bool {
1890        desc { "computing whether impls specialize one another" }
1891    }
1892    query in_scope_traits_map(_: hir::OwnerId)
1893        -> Option<&'tcx ItemLocalMap<Box<[TraitCandidate]>>> {
1894        desc { "getting traits in scope at a block" }
1895    }
1896
1897    /// Returns whether the impl or associated function has the `default` keyword.
1898    /// Note: This will ICE on inherent impl items. Consider using `AssocItem::defaultness`.
1899    query defaultness(def_id: DefId) -> hir::Defaultness {
1900        desc { |tcx| "looking up whether `{}` has `default`", tcx.def_path_str(def_id) }
1901        separate_provide_extern
1902        feedable
1903    }
1904
1905    /// Returns whether the field corresponding to the `DefId` has a default field value.
1906    query default_field(def_id: DefId) -> Option<DefId> {
1907        desc { |tcx| "looking up the `const` corresponding to the default for `{}`", tcx.def_path_str(def_id) }
1908        separate_provide_extern
1909    }
1910
1911    query check_well_formed(key: LocalDefId) -> Result<(), ErrorGuaranteed> {
1912        desc { |tcx| "checking that `{}` is well-formed", tcx.def_path_str(key) }
1913        return_result_from_ensure_ok
1914    }
1915
1916    query enforce_impl_non_lifetime_params_are_constrained(key: LocalDefId) -> Result<(), ErrorGuaranteed> {
1917        desc { |tcx| "checking that `{}`'s generics are constrained by the impl header", tcx.def_path_str(key) }
1918        return_result_from_ensure_ok
1919    }
1920
1921    // The `DefId`s of all non-generic functions and statics in the given crate
1922    // that can be reached from outside the crate.
1923    //
1924    // We expect this items to be available for being linked to.
1925    //
1926    // This query can also be called for `LOCAL_CRATE`. In this case it will
1927    // compute which items will be reachable to other crates, taking into account
1928    // the kind of crate that is currently compiled. Crates with only a
1929    // C interface have fewer reachable things.
1930    //
1931    // Does not include external symbols that don't have a corresponding DefId,
1932    // like the compiler-generated `main` function and so on.
1933    query reachable_non_generics(_: CrateNum)
1934        -> &'tcx DefIdMap<SymbolExportInfo> {
1935        arena_cache
1936        desc { "looking up the exported symbols of a crate" }
1937        separate_provide_extern
1938    }
1939    query is_reachable_non_generic(def_id: DefId) -> bool {
1940        desc { |tcx| "checking whether `{}` is an exported symbol", tcx.def_path_str(def_id) }
1941        cache_on_disk_if { def_id.is_local() }
1942        separate_provide_extern
1943    }
1944    query is_unreachable_local_definition(def_id: LocalDefId) -> bool {
1945        desc { |tcx|
1946            "checking whether `{}` is reachable from outside the crate",
1947            tcx.def_path_str(def_id),
1948        }
1949    }
1950
1951    /// The entire set of monomorphizations the local crate can safely
1952    /// link to because they are exported from upstream crates. Do
1953    /// not depend on this directly, as its value changes anytime
1954    /// a monomorphization gets added or removed in any upstream
1955    /// crate. Instead use the narrower `upstream_monomorphizations_for`,
1956    /// `upstream_drop_glue_for`, `upstream_async_drop_glue_for`, or,
1957    /// even better, `Instance::upstream_monomorphization()`.
1958    query upstream_monomorphizations(_: ()) -> &'tcx DefIdMap<UnordMap<GenericArgsRef<'tcx>, CrateNum>> {
1959        arena_cache
1960        desc { "collecting available upstream monomorphizations" }
1961    }
1962
1963    /// Returns the set of upstream monomorphizations available for the
1964    /// generic function identified by the given `def_id`. The query makes
1965    /// sure to make a stable selection if the same monomorphization is
1966    /// available in multiple upstream crates.
1967    ///
1968    /// You likely want to call `Instance::upstream_monomorphization()`
1969    /// instead of invoking this query directly.
1970    query upstream_monomorphizations_for(def_id: DefId)
1971        -> Option<&'tcx UnordMap<GenericArgsRef<'tcx>, CrateNum>>
1972    {
1973        desc { |tcx|
1974            "collecting available upstream monomorphizations for `{}`",
1975            tcx.def_path_str(def_id),
1976        }
1977        separate_provide_extern
1978    }
1979
1980    /// Returns the upstream crate that exports drop-glue for the given
1981    /// type (`args` is expected to be a single-item list containing the
1982    /// type one wants drop-glue for).
1983    ///
1984    /// This is a subset of `upstream_monomorphizations_for` in order to
1985    /// increase dep-tracking granularity. Otherwise adding or removing any
1986    /// type with drop-glue in any upstream crate would invalidate all
1987    /// functions calling drop-glue of an upstream type.
1988    ///
1989    /// You likely want to call `Instance::upstream_monomorphization()`
1990    /// instead of invoking this query directly.
1991    ///
1992    /// NOTE: This query could easily be extended to also support other
1993    ///       common functions that have are large set of monomorphizations
1994    ///       (like `Clone::clone` for example).
1995    query upstream_drop_glue_for(args: GenericArgsRef<'tcx>) -> Option<CrateNum> {
1996        desc { "available upstream drop-glue for `{:?}`", args }
1997    }
1998
1999    /// Returns the upstream crate that exports async-drop-glue for
2000    /// the given type (`args` is expected to be a single-item list
2001    /// containing the type one wants async-drop-glue for).
2002    ///
2003    /// This is a subset of `upstream_monomorphizations_for` in order
2004    /// to increase dep-tracking granularity. Otherwise adding or
2005    /// removing any type with async-drop-glue in any upstream crate
2006    /// would invalidate all functions calling async-drop-glue of an
2007    /// upstream type.
2008    ///
2009    /// You likely want to call `Instance::upstream_monomorphization()`
2010    /// instead of invoking this query directly.
2011    ///
2012    /// NOTE: This query could easily be extended to also support other
2013    ///       common functions that have are large set of monomorphizations
2014    ///       (like `Clone::clone` for example).
2015    query upstream_async_drop_glue_for(args: GenericArgsRef<'tcx>) -> Option<CrateNum> {
2016        desc { "available upstream async-drop-glue for `{:?}`", args }
2017    }
2018
2019    /// Returns a list of all `extern` blocks of a crate.
2020    query foreign_modules(_: CrateNum) -> &'tcx FxIndexMap<DefId, ForeignModule> {
2021        arena_cache
2022        desc { "looking up the foreign modules of a linked crate" }
2023        separate_provide_extern
2024    }
2025
2026    /// Lint against `extern fn` declarations having incompatible types.
2027    query clashing_extern_declarations(_: ()) {
2028        desc { "checking `extern fn` declarations are compatible" }
2029    }
2030
2031    /// Identifies the entry-point (e.g., the `main` function) for a given
2032    /// crate, returning `None` if there is no entry point (such as for library crates).
2033    query entry_fn(_: ()) -> Option<(DefId, EntryFnType)> {
2034        desc { "looking up the entry function of a crate" }
2035    }
2036
2037    /// Finds the `rustc_proc_macro_decls` item of a crate.
2038    query proc_macro_decls_static(_: ()) -> Option<LocalDefId> {
2039        desc { "looking up the proc macro declarations for a crate" }
2040    }
2041
2042    // The macro which defines `rustc_metadata::provide_extern` depends on this query's name.
2043    // Changing the name should cause a compiler error, but in case that changes, be aware.
2044    //
2045    // The hash should not be calculated before the `analysis` pass is complete, specifically
2046    // until `tcx.untracked().definitions.freeze()` has been called, otherwise if incremental
2047    // compilation is enabled calculating this hash can freeze this structure too early in
2048    // compilation and cause subsequent crashes when attempting to write to `definitions`
2049    query crate_hash(_: CrateNum) -> Svh {
2050        eval_always
2051        desc { "looking up the hash a crate" }
2052        separate_provide_extern
2053    }
2054
2055    /// Gets the hash for the host proc macro. Used to support -Z dual-proc-macro.
2056    query crate_host_hash(_: CrateNum) -> Option<Svh> {
2057        eval_always
2058        desc { "looking up the hash of a host version of a crate" }
2059        separate_provide_extern
2060    }
2061
2062    /// Gets the extra data to put in each output filename for a crate.
2063    /// For example, compiling the `foo` crate with `extra-filename=-a` creates a `libfoo-b.rlib` file.
2064    query extra_filename(_: CrateNum) -> &'tcx String {
2065        arena_cache
2066        eval_always
2067        desc { "looking up the extra filename for a crate" }
2068        separate_provide_extern
2069    }
2070
2071    /// Gets the paths where the crate came from in the file system.
2072    query crate_extern_paths(_: CrateNum) -> &'tcx Vec<PathBuf> {
2073        arena_cache
2074        eval_always
2075        desc { "looking up the paths for extern crates" }
2076        separate_provide_extern
2077    }
2078
2079    /// Given a crate and a trait, look up all impls of that trait in the crate.
2080    /// Return `(impl_id, self_ty)`.
2081    query implementations_of_trait(_: (CrateNum, DefId)) -> &'tcx [(DefId, Option<SimplifiedType>)] {
2082        desc { "looking up implementations of a trait in a crate" }
2083        separate_provide_extern
2084    }
2085
2086    /// Collects all incoherent impls for the given crate and type.
2087    ///
2088    /// Do not call this directly, but instead use the `incoherent_impls` query.
2089    /// This query is only used to get the data necessary for that query.
2090    query crate_incoherent_impls(key: (CrateNum, SimplifiedType)) -> &'tcx [DefId] {
2091        desc { |tcx| "collecting all impls for a type in a crate" }
2092        separate_provide_extern
2093    }
2094
2095    /// Get the corresponding native library from the `native_libraries` query
2096    query native_library(def_id: DefId) -> Option<&'tcx NativeLib> {
2097        desc { |tcx| "getting the native library for `{}`", tcx.def_path_str(def_id) }
2098    }
2099
2100    query inherit_sig_for_delegation_item(def_id: LocalDefId) -> &'tcx [Ty<'tcx>] {
2101        desc { "inheriting delegation signature" }
2102    }
2103
2104    /// Does lifetime resolution on items. Importantly, we can't resolve
2105    /// lifetimes directly on things like trait methods, because of trait params.
2106    /// See `rustc_resolve::late::lifetimes` for details.
2107    query resolve_bound_vars(owner_id: hir::OwnerId) -> &'tcx ResolveBoundVars {
2108        arena_cache
2109        desc { |tcx| "resolving lifetimes for `{}`", tcx.def_path_str(owner_id) }
2110    }
2111    query named_variable_map(owner_id: hir::OwnerId) -> &'tcx SortedMap<ItemLocalId, ResolvedArg> {
2112        desc { |tcx| "looking up a named region inside `{}`", tcx.def_path_str(owner_id) }
2113    }
2114    query is_late_bound_map(owner_id: hir::OwnerId) -> Option<&'tcx FxIndexSet<ItemLocalId>> {
2115        desc { |tcx| "testing if a region is late bound inside `{}`", tcx.def_path_str(owner_id) }
2116    }
2117    /// Returns the *default lifetime* to be used if a trait object type were to be passed for
2118    /// the type parameter given by `DefId`.
2119    ///
2120    /// **Tip**: You can use `#[rustc_object_lifetime_default]` on an item to basically
2121    /// print the result of this query for use in UI tests or for debugging purposes.
2122    ///
2123    /// # Examples
2124    ///
2125    /// - For `T` in `struct Foo<'a, T: 'a>(&'a T);`, this would be `Param('a)`
2126    /// - For `T` in `struct Bar<'a, T>(&'a T);`, this would be `Empty`
2127    ///
2128    /// # Panics
2129    ///
2130    /// This query will panic if the given definition is not a type parameter.
2131    query object_lifetime_default(def_id: DefId) -> ObjectLifetimeDefault {
2132        desc { "looking up lifetime defaults for type parameter `{}`", tcx.def_path_str(def_id) }
2133        separate_provide_extern
2134    }
2135    query late_bound_vars_map(owner_id: hir::OwnerId)
2136        -> &'tcx SortedMap<ItemLocalId, Vec<ty::BoundVariableKind>> {
2137        desc { |tcx| "looking up late bound vars inside `{}`", tcx.def_path_str(owner_id) }
2138    }
2139    /// For an opaque type, return the list of (captured lifetime, inner generic param).
2140    /// ```ignore (illustrative)
2141    /// fn foo<'a: 'a, 'b, T>(&'b u8) -> impl Into<Self> + 'b { ... }
2142    /// ```
2143    ///
2144    /// We would return `[('a, '_a), ('b, '_b)]`, with `'a` early-bound and `'b` late-bound.
2145    ///
2146    /// After hir_ty_lowering, we get:
2147    /// ```ignore (pseudo-code)
2148    /// opaque foo::<'a>::opaque<'_a, '_b>: Into<Foo<'_a>> + '_b;
2149    ///                          ^^^^^^^^ inner generic params
2150    /// fn foo<'a>: for<'b> fn(&'b u8) -> foo::<'a>::opaque::<'a, 'b>
2151    ///                                                       ^^^^^^ captured lifetimes
2152    /// ```
2153    query opaque_captured_lifetimes(def_id: LocalDefId) -> &'tcx [(ResolvedArg, LocalDefId)] {
2154        desc { |tcx| "listing captured lifetimes for opaque `{}`", tcx.def_path_str(def_id) }
2155    }
2156
2157    /// Computes the visibility of the provided `def_id`.
2158    ///
2159    /// If the item from the `def_id` doesn't have a visibility, it will panic. For example
2160    /// a generic type parameter will panic if you call this method on it:
2161    ///
2162    /// ```
2163    /// use std::fmt::Debug;
2164    ///
2165    /// pub trait Foo<T: Debug> {}
2166    /// ```
2167    ///
2168    /// In here, if you call `visibility` on `T`, it'll panic.
2169    query visibility(def_id: DefId) -> ty::Visibility<DefId> {
2170        desc { |tcx| "computing visibility of `{}`", tcx.def_path_str(def_id) }
2171        separate_provide_extern
2172        feedable
2173    }
2174
2175    query inhabited_predicate_adt(key: DefId) -> ty::inhabitedness::InhabitedPredicate<'tcx> {
2176        desc { "computing the uninhabited predicate of `{:?}`", key }
2177    }
2178
2179    /// Do not call this query directly: invoke `Ty::inhabited_predicate` instead.
2180    query inhabited_predicate_type(key: Ty<'tcx>) -> ty::inhabitedness::InhabitedPredicate<'tcx> {
2181        desc { "computing the uninhabited predicate of `{}`", key }
2182    }
2183
2184    query dep_kind(_: CrateNum) -> CrateDepKind {
2185        eval_always
2186        desc { "fetching what a dependency looks like" }
2187        separate_provide_extern
2188    }
2189
2190    /// Gets the name of the crate.
2191    query crate_name(_: CrateNum) -> Symbol {
2192        feedable
2193        desc { "fetching what a crate is named" }
2194        separate_provide_extern
2195    }
2196    query module_children(def_id: DefId) -> &'tcx [ModChild] {
2197        desc { |tcx| "collecting child items of module `{}`", tcx.def_path_str(def_id) }
2198        separate_provide_extern
2199    }
2200
2201    /// Gets the number of definitions in a foreign crate.
2202    ///
2203    /// This allows external tools to iterate over all definitions in a foreign crate.
2204    ///
2205    /// This should never be used for the local crate, instead use `iter_local_def_id`.
2206    query num_extern_def_ids(_: CrateNum) -> usize {
2207        desc { "fetching the number of definitions in a crate" }
2208        separate_provide_extern
2209    }
2210
2211    query lib_features(_: CrateNum) -> &'tcx LibFeatures {
2212        desc { "calculating the lib features defined in a crate" }
2213        separate_provide_extern
2214        arena_cache
2215    }
2216    /// Mapping from feature name to feature name based on the `implied_by` field of `#[unstable]`
2217    /// attributes. If a `#[unstable(feature = "implier", implied_by = "impliee")]` attribute
2218    /// exists, then this map will have a `impliee -> implier` entry.
2219    ///
2220    /// This mapping is necessary unless both the `#[stable]` and `#[unstable]` attributes should
2221    /// specify their implications (both `implies` and `implied_by`). If only one of the two
2222    /// attributes do (as in the current implementation, `implied_by` in `#[unstable]`), then this
2223    /// mapping is necessary for diagnostics. When a "unnecessary feature attribute" error is
2224    /// reported, only the `#[stable]` attribute information is available, so the map is necessary
2225    /// to know that the feature implies another feature. If it were reversed, and the `#[stable]`
2226    /// attribute had an `implies` meta item, then a map would be necessary when avoiding a "use of
2227    /// unstable feature" error for a feature that was implied.
2228    query stability_implications(_: CrateNum) -> &'tcx UnordMap<Symbol, Symbol> {
2229        arena_cache
2230        desc { "calculating the implications between `#[unstable]` features defined in a crate" }
2231        separate_provide_extern
2232    }
2233    /// Whether the function is an intrinsic
2234    query intrinsic_raw(def_id: DefId) -> Option<rustc_middle::ty::IntrinsicDef> {
2235        desc { |tcx| "fetch intrinsic name if `{}` is an intrinsic", tcx.def_path_str(def_id) }
2236        separate_provide_extern
2237    }
2238    /// Returns the lang items defined in another crate by loading it from metadata.
2239    query get_lang_items(_: ()) -> &'tcx LanguageItems {
2240        arena_cache
2241        eval_always
2242        desc { "calculating the lang items map" }
2243    }
2244
2245    /// Returns all diagnostic items defined in all crates.
2246    query all_diagnostic_items(_: ()) -> &'tcx rustc_hir::diagnostic_items::DiagnosticItems {
2247        arena_cache
2248        eval_always
2249        desc { "calculating the diagnostic items map" }
2250    }
2251
2252    /// Returns the lang items defined in another crate by loading it from metadata.
2253    query defined_lang_items(_: CrateNum) -> &'tcx [(DefId, LangItem)] {
2254        desc { "calculating the lang items defined in a crate" }
2255        separate_provide_extern
2256    }
2257
2258    /// Returns the diagnostic items defined in a crate.
2259    query diagnostic_items(_: CrateNum) -> &'tcx rustc_hir::diagnostic_items::DiagnosticItems {
2260        arena_cache
2261        desc { "calculating the diagnostic items map in a crate" }
2262        separate_provide_extern
2263    }
2264
2265    query missing_lang_items(_: CrateNum) -> &'tcx [LangItem] {
2266        desc { "calculating the missing lang items in a crate" }
2267        separate_provide_extern
2268    }
2269
2270    /// The visible parent map is a map from every item to a visible parent.
2271    /// It prefers the shortest visible path to an item.
2272    /// Used for diagnostics, for example path trimming.
2273    /// The parents are modules, enums or traits.
2274    query visible_parent_map(_: ()) -> &'tcx DefIdMap<DefId> {
2275        arena_cache
2276        desc { "calculating the visible parent map" }
2277    }
2278    /// Collects the "trimmed", shortest accessible paths to all items for diagnostics.
2279    /// See the [provider docs](`rustc_middle::ty::print::trimmed_def_paths`) for more info.
2280    query trimmed_def_paths(_: ()) -> &'tcx DefIdMap<Symbol> {
2281        arena_cache
2282        desc { "calculating trimmed def paths" }
2283    }
2284    query missing_extern_crate_item(_: CrateNum) -> bool {
2285        eval_always
2286        desc { "seeing if we're missing an `extern crate` item for this crate" }
2287        separate_provide_extern
2288    }
2289    query used_crate_source(_: CrateNum) -> &'tcx Arc<CrateSource> {
2290        arena_cache
2291        eval_always
2292        desc { "looking at the source for a crate" }
2293        separate_provide_extern
2294    }
2295
2296    /// Returns the debugger visualizers defined for this crate.
2297    /// NOTE: This query has to be marked `eval_always` because it reads data
2298    ///       directly from disk that is not tracked anywhere else. I.e. it
2299    ///       represents a genuine input to the query system.
2300    query debugger_visualizers(_: CrateNum) -> &'tcx Vec<DebuggerVisualizerFile> {
2301        arena_cache
2302        desc { "looking up the debugger visualizers for this crate" }
2303        separate_provide_extern
2304        eval_always
2305    }
2306
2307    query postorder_cnums(_: ()) -> &'tcx [CrateNum] {
2308        eval_always
2309        desc { "generating a postorder list of CrateNums" }
2310    }
2311    /// Returns whether or not the crate with CrateNum 'cnum'
2312    /// is marked as a private dependency
2313    query is_private_dep(c: CrateNum) -> bool {
2314        eval_always
2315        desc { "checking whether crate `{}` is a private dependency", c }
2316        separate_provide_extern
2317    }
2318    query allocator_kind(_: ()) -> Option<AllocatorKind> {
2319        eval_always
2320        desc { "getting the allocator kind for the current crate" }
2321    }
2322    query alloc_error_handler_kind(_: ()) -> Option<AllocatorKind> {
2323        eval_always
2324        desc { "alloc error handler kind for the current crate" }
2325    }
2326
2327    query upvars_mentioned(def_id: DefId) -> Option<&'tcx FxIndexMap<hir::HirId, hir::Upvar>> {
2328        desc { |tcx| "collecting upvars mentioned in `{}`", tcx.def_path_str(def_id) }
2329    }
2330
2331    /// All available crates in the graph, including those that should not be user-facing
2332    /// (such as private crates).
2333    query crates(_: ()) -> &'tcx [CrateNum] {
2334        eval_always
2335        desc { "fetching all foreign CrateNum instances" }
2336    }
2337    // Crates that are loaded non-speculatively (not for diagnostics or doc links).
2338    // FIXME: This is currently only used for collecting lang items, but should be used instead of
2339    // `crates` in most other cases too.
2340    query used_crates(_: ()) -> &'tcx [CrateNum] {
2341        eval_always
2342        desc { "fetching `CrateNum`s for all crates loaded non-speculatively" }
2343    }
2344
2345    /// A list of all traits in a crate, used by rustdoc and error reporting.
2346    query traits(_: CrateNum) -> &'tcx [DefId] {
2347        desc { "fetching all traits in a crate" }
2348        separate_provide_extern
2349    }
2350
2351    query trait_impls_in_crate(_: CrateNum) -> &'tcx [DefId] {
2352        desc { "fetching all trait impls in a crate" }
2353        separate_provide_extern
2354    }
2355
2356    query stable_order_of_exportable_impls(_: CrateNum) -> &'tcx FxIndexMap<DefId, usize> {
2357        desc { "fetching the stable impl's order" }
2358        separate_provide_extern
2359    }
2360
2361    query exportable_items(_: CrateNum) -> &'tcx [DefId] {
2362        desc { "fetching all exportable items in a crate" }
2363        separate_provide_extern
2364    }
2365
2366    /// The list of non-generic symbols exported from the given crate.
2367    ///
2368    /// This is separate from exported_generic_symbols to avoid having
2369    /// to deserialize all non-generic symbols too for upstream crates
2370    /// in the upstream_monomorphizations query.
2371    ///
2372    /// - All names contained in `exported_non_generic_symbols(cnum)` are
2373    ///   guaranteed to correspond to a publicly visible symbol in `cnum`
2374    ///   machine code.
2375    /// - The `exported_non_generic_symbols` and `exported_generic_symbols`
2376    ///   sets of different crates do not intersect.
2377    query exported_non_generic_symbols(cnum: CrateNum) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportInfo)] {
2378        desc { "collecting exported non-generic symbols for crate `{}`", cnum}
2379        cache_on_disk_if { *cnum == LOCAL_CRATE }
2380        separate_provide_extern
2381    }
2382
2383    /// The list of generic symbols exported from the given crate.
2384    ///
2385    /// - All names contained in `exported_generic_symbols(cnum)` are
2386    ///   guaranteed to correspond to a publicly visible symbol in `cnum`
2387    ///   machine code.
2388    /// - The `exported_non_generic_symbols` and `exported_generic_symbols`
2389    ///   sets of different crates do not intersect.
2390    query exported_generic_symbols(cnum: CrateNum) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportInfo)] {
2391        desc { "collecting exported generic symbols for crate `{}`", cnum}
2392        cache_on_disk_if { *cnum == LOCAL_CRATE }
2393        separate_provide_extern
2394    }
2395
2396    query collect_and_partition_mono_items(_: ()) -> MonoItemPartitions<'tcx> {
2397        eval_always
2398        desc { "collect_and_partition_mono_items" }
2399    }
2400
2401    query is_codegened_item(def_id: DefId) -> bool {
2402        desc { |tcx| "determining whether `{}` needs codegen", tcx.def_path_str(def_id) }
2403    }
2404
2405    query codegen_unit(sym: Symbol) -> &'tcx CodegenUnit<'tcx> {
2406        desc { "getting codegen unit `{sym}`" }
2407    }
2408
2409    query backend_optimization_level(_: ()) -> OptLevel {
2410        desc { "optimization level used by backend" }
2411    }
2412
2413    /// Return the filenames where output artefacts shall be stored.
2414    ///
2415    /// This query returns an `&Arc` because codegen backends need the value even after the `TyCtxt`
2416    /// has been destroyed.
2417    query output_filenames(_: ()) -> &'tcx Arc<OutputFilenames> {
2418        feedable
2419        desc { "getting output filenames" }
2420        arena_cache
2421    }
2422
2423    /// <div class="warning">
2424    ///
2425    /// Do not call this query directly: Invoke `normalize` instead.
2426    ///
2427    /// </div>
2428    query normalize_canonicalized_projection(
2429        goal: CanonicalAliasGoal<'tcx>
2430    ) -> Result<
2431        &'tcx Canonical<'tcx, canonical::QueryResponse<'tcx, NormalizationResult<'tcx>>>,
2432        NoSolution,
2433    > {
2434        desc { "normalizing `{}`", goal.canonical.value.value }
2435    }
2436
2437    /// <div class="warning">
2438    ///
2439    /// Do not call this query directly: Invoke `normalize` instead.
2440    ///
2441    /// </div>
2442    query normalize_canonicalized_free_alias(
2443        goal: CanonicalAliasGoal<'tcx>
2444    ) -> Result<
2445        &'tcx Canonical<'tcx, canonical::QueryResponse<'tcx, NormalizationResult<'tcx>>>,
2446        NoSolution,
2447    > {
2448        desc { "normalizing `{}`", goal.canonical.value.value }
2449    }
2450
2451    /// <div class="warning">
2452    ///
2453    /// Do not call this query directly: Invoke `normalize` instead.
2454    ///
2455    /// </div>
2456    query normalize_canonicalized_inherent_projection(
2457        goal: CanonicalAliasGoal<'tcx>
2458    ) -> Result<
2459        &'tcx Canonical<'tcx, canonical::QueryResponse<'tcx, NormalizationResult<'tcx>>>,
2460        NoSolution,
2461    > {
2462        desc { "normalizing `{}`", goal.canonical.value.value }
2463    }
2464
2465    /// Do not call this query directly: invoke `try_normalize_erasing_regions` instead.
2466    query try_normalize_generic_arg_after_erasing_regions(
2467        goal: PseudoCanonicalInput<'tcx, GenericArg<'tcx>>
2468    ) -> Result<GenericArg<'tcx>, NoSolution> {
2469        desc { "normalizing `{}`", goal.value }
2470    }
2471
2472    query implied_outlives_bounds(
2473        key: (CanonicalImpliedOutlivesBoundsGoal<'tcx>, bool)
2474    ) -> Result<
2475        &'tcx Canonical<'tcx, canonical::QueryResponse<'tcx, Vec<OutlivesBound<'tcx>>>>,
2476        NoSolution,
2477    > {
2478        desc { "computing implied outlives bounds for `{}` (hack disabled = {:?})", key.0.canonical.value.value.ty, key.1 }
2479    }
2480
2481    /// Do not call this query directly:
2482    /// invoke `DropckOutlives::new(dropped_ty)).fully_perform(typeck.infcx)` instead.
2483    query dropck_outlives(
2484        goal: CanonicalDropckOutlivesGoal<'tcx>
2485    ) -> Result<
2486        &'tcx Canonical<'tcx, canonical::QueryResponse<'tcx, DropckOutlivesResult<'tcx>>>,
2487        NoSolution,
2488    > {
2489        desc { "computing dropck types for `{}`", goal.canonical.value.value.dropped_ty }
2490    }
2491
2492    /// Do not call this query directly: invoke `infcx.predicate_may_hold()` or
2493    /// `infcx.predicate_must_hold()` instead.
2494    query evaluate_obligation(
2495        goal: CanonicalPredicateGoal<'tcx>
2496    ) -> Result<EvaluationResult, OverflowError> {
2497        desc { "evaluating trait selection obligation `{}`", goal.canonical.value.value }
2498    }
2499
2500    /// Do not call this query directly: part of the `Eq` type-op
2501    query type_op_ascribe_user_type(
2502        goal: CanonicalTypeOpAscribeUserTypeGoal<'tcx>
2503    ) -> Result<
2504        &'tcx Canonical<'tcx, canonical::QueryResponse<'tcx, ()>>,
2505        NoSolution,
2506    > {
2507        desc { "evaluating `type_op_ascribe_user_type` `{:?}`", goal.canonical.value.value }
2508    }
2509
2510    /// Do not call this query directly: part of the `ProvePredicate` type-op
2511    query type_op_prove_predicate(
2512        goal: CanonicalTypeOpProvePredicateGoal<'tcx>
2513    ) -> Result<
2514        &'tcx Canonical<'tcx, canonical::QueryResponse<'tcx, ()>>,
2515        NoSolution,
2516    > {
2517        desc { "evaluating `type_op_prove_predicate` `{:?}`", goal.canonical.value.value }
2518    }
2519
2520    /// Do not call this query directly: part of the `Normalize` type-op
2521    query type_op_normalize_ty(
2522        goal: CanonicalTypeOpNormalizeGoal<'tcx, Ty<'tcx>>
2523    ) -> Result<
2524        &'tcx Canonical<'tcx, canonical::QueryResponse<'tcx, Ty<'tcx>>>,
2525        NoSolution,
2526    > {
2527        desc { "normalizing `{}`", goal.canonical.value.value.value }
2528    }
2529
2530    /// Do not call this query directly: part of the `Normalize` type-op
2531    query type_op_normalize_clause(
2532        goal: CanonicalTypeOpNormalizeGoal<'tcx, ty::Clause<'tcx>>
2533    ) -> Result<
2534        &'tcx Canonical<'tcx, canonical::QueryResponse<'tcx, ty::Clause<'tcx>>>,
2535        NoSolution,
2536    > {
2537        desc { "normalizing `{:?}`", goal.canonical.value.value.value }
2538    }
2539
2540    /// Do not call this query directly: part of the `Normalize` type-op
2541    query type_op_normalize_poly_fn_sig(
2542        goal: CanonicalTypeOpNormalizeGoal<'tcx, ty::PolyFnSig<'tcx>>
2543    ) -> Result<
2544        &'tcx Canonical<'tcx, canonical::QueryResponse<'tcx, ty::PolyFnSig<'tcx>>>,
2545        NoSolution,
2546    > {
2547        desc { "normalizing `{:?}`", goal.canonical.value.value.value }
2548    }
2549
2550    /// Do not call this query directly: part of the `Normalize` type-op
2551    query type_op_normalize_fn_sig(
2552        goal: CanonicalTypeOpNormalizeGoal<'tcx, ty::FnSig<'tcx>>
2553    ) -> Result<
2554        &'tcx Canonical<'tcx, canonical::QueryResponse<'tcx, ty::FnSig<'tcx>>>,
2555        NoSolution,
2556    > {
2557        desc { "normalizing `{:?}`", goal.canonical.value.value.value }
2558    }
2559
2560    query instantiate_and_check_impossible_predicates(key: (DefId, GenericArgsRef<'tcx>)) -> bool {
2561        desc { |tcx|
2562            "checking impossible instantiated predicates: `{}`",
2563            tcx.def_path_str(key.0)
2564        }
2565    }
2566
2567    query is_impossible_associated_item(key: (DefId, DefId)) -> bool {
2568        desc { |tcx|
2569            "checking if `{}` is impossible to reference within `{}`",
2570            tcx.def_path_str(key.1),
2571            tcx.def_path_str(key.0),
2572        }
2573    }
2574
2575    query method_autoderef_steps(
2576        goal: CanonicalMethodAutoderefStepsGoal<'tcx>
2577    ) -> MethodAutoderefStepsResult<'tcx> {
2578        desc { "computing autoderef types for `{}`", goal.canonical.value.value.self_ty }
2579    }
2580
2581    /// Used by `-Znext-solver` to compute proof trees.
2582    query evaluate_root_goal_for_proof_tree_raw(
2583        goal: solve::CanonicalInput<'tcx>,
2584    ) -> (solve::QueryResult<'tcx>, &'tcx solve::inspect::Probe<TyCtxt<'tcx>>) {
2585        no_hash
2586        desc { "computing proof tree for `{}`", goal.canonical.value.goal.predicate }
2587    }
2588
2589    /// Returns the Rust target features for the current target. These are not always the same as LLVM target features!
2590    query rust_target_features(_: CrateNum) -> &'tcx UnordMap<String, rustc_target::target_features::Stability> {
2591        arena_cache
2592        eval_always
2593        desc { "looking up Rust target features" }
2594    }
2595
2596    query implied_target_features(feature: Symbol) -> &'tcx Vec<Symbol> {
2597        arena_cache
2598        eval_always
2599        desc { "looking up implied target features" }
2600    }
2601
2602    query features_query(_: ()) -> &'tcx rustc_feature::Features {
2603        feedable
2604        desc { "looking up enabled feature gates" }
2605    }
2606
2607    query crate_for_resolver((): ()) -> &'tcx Steal<(rustc_ast::Crate, rustc_ast::AttrVec)> {
2608        feedable
2609        no_hash
2610        desc { "the ast before macro expansion and name resolution" }
2611    }
2612
2613    /// Attempt to resolve the given `DefId` to an `Instance`, for the
2614    /// given generics args (`GenericArgsRef`), returning one of:
2615    ///  * `Ok(Some(instance))` on success
2616    ///  * `Ok(None)` when the `GenericArgsRef` are still too generic,
2617    ///    and therefore don't allow finding the final `Instance`
2618    ///  * `Err(ErrorGuaranteed)` when the `Instance` resolution process
2619    ///    couldn't complete due to errors elsewhere - this is distinct
2620    ///    from `Ok(None)` to avoid misleading diagnostics when an error
2621    ///    has already been/will be emitted, for the original cause.
2622    query resolve_instance_raw(
2623        key: ty::PseudoCanonicalInput<'tcx, (DefId, GenericArgsRef<'tcx>)>
2624    ) -> Result<Option<ty::Instance<'tcx>>, ErrorGuaranteed> {
2625        desc { "resolving instance `{}`", ty::Instance::new_raw(key.value.0, key.value.1) }
2626    }
2627
2628    query reveal_opaque_types_in_bounds(key: ty::Clauses<'tcx>) -> ty::Clauses<'tcx> {
2629        desc { "revealing opaque types in `{:?}`", key }
2630    }
2631
2632    query limits(key: ()) -> Limits {
2633        desc { "looking up limits" }
2634    }
2635
2636    /// Performs an HIR-based well-formed check on the item with the given `HirId`. If
2637    /// we get an `Unimplemented` error that matches the provided `Predicate`, return
2638    /// the cause of the newly created obligation.
2639    ///
2640    /// This is only used by error-reporting code to get a better cause (in particular, a better
2641    /// span) for an *existing* error. Therefore, it is best-effort, and may never handle
2642    /// all of the cases that the normal `ty::Ty`-based wfcheck does. This is fine,
2643    /// because the `ty::Ty`-based wfcheck is always run.
2644    query diagnostic_hir_wf_check(
2645        key: (ty::Predicate<'tcx>, WellFormedLoc)
2646    ) -> Option<&'tcx ObligationCause<'tcx>> {
2647        arena_cache
2648        eval_always
2649        no_hash
2650        desc { "performing HIR wf-checking for predicate `{:?}` at item `{:?}`", key.0, key.1 }
2651    }
2652
2653    /// The list of backend features computed from CLI flags (`-Ctarget-cpu`, `-Ctarget-feature`,
2654    /// `--target` and similar).
2655    query global_backend_features(_: ()) -> &'tcx Vec<String> {
2656        arena_cache
2657        eval_always
2658        desc { "computing the backend features for CLI flags" }
2659    }
2660
2661    query check_validity_requirement(key: (ValidityRequirement, ty::PseudoCanonicalInput<'tcx, Ty<'tcx>>)) -> Result<bool, &'tcx ty::layout::LayoutError<'tcx>> {
2662        desc { "checking validity requirement for `{}`: {}", key.1.value, key.0 }
2663    }
2664
2665    /// This takes the def-id of an associated item from a impl of a trait,
2666    /// and checks its validity against the trait item it corresponds to.
2667    ///
2668    /// Any other def id will ICE.
2669    query compare_impl_item(key: LocalDefId) -> Result<(), ErrorGuaranteed> {
2670        desc { |tcx| "checking assoc item `{}` is compatible with trait definition", tcx.def_path_str(key) }
2671        return_result_from_ensure_ok
2672    }
2673
2674    query deduced_param_attrs(def_id: DefId) -> &'tcx [DeducedParamAttrs] {
2675        desc { |tcx| "deducing parameter attributes for {}", tcx.def_path_str(def_id) }
2676        separate_provide_extern
2677    }
2678
2679    query doc_link_resolutions(def_id: DefId) -> &'tcx DocLinkResMap {
2680        eval_always
2681        desc { "resolutions for documentation links for a module" }
2682        separate_provide_extern
2683    }
2684
2685    query doc_link_traits_in_scope(def_id: DefId) -> &'tcx [DefId] {
2686        eval_always
2687        desc { "traits in scope for documentation links for a module" }
2688        separate_provide_extern
2689    }
2690
2691    /// Get all item paths that were stripped by a `#[cfg]` in a particular crate.
2692    /// Should not be called for the local crate before the resolver outputs are created, as it
2693    /// is only fed there.
2694    query stripped_cfg_items(cnum: CrateNum) -> &'tcx [StrippedCfgItem] {
2695        desc { "getting cfg-ed out item names" }
2696        separate_provide_extern
2697    }
2698
2699    query generics_require_sized_self(def_id: DefId) -> bool {
2700        desc { "check whether the item has a `where Self: Sized` bound" }
2701    }
2702
2703    query cross_crate_inlinable(def_id: DefId) -> bool {
2704        desc { "whether the item should be made inlinable across crates" }
2705        separate_provide_extern
2706    }
2707
2708    /// Perform monomorphization-time checking on this item.
2709    /// This is used for lints/errors that can only be checked once the instance is fully
2710    /// monomorphized.
2711    query check_mono_item(key: ty::Instance<'tcx>) {
2712        desc { "monomorphization-time checking" }
2713    }
2714
2715    /// Builds the set of functions that should be skipped for the move-size check.
2716    query skip_move_check_fns(_: ()) -> &'tcx FxIndexSet<DefId> {
2717        arena_cache
2718        desc { "functions to skip for move-size check" }
2719    }
2720
2721    query items_of_instance(key: (ty::Instance<'tcx>, CollectionMode)) -> Result<(&'tcx [Spanned<MonoItem<'tcx>>], &'tcx [Spanned<MonoItem<'tcx>>]), NormalizationErrorInMono> {
2722        desc { "collecting items used by `{}`", key.0 }
2723        cache_on_disk_if { true }
2724    }
2725
2726    query size_estimate(key: ty::Instance<'tcx>) -> usize {
2727        desc { "estimating codegen size of `{}`", key }
2728        cache_on_disk_if { true }
2729    }
2730
2731    query anon_const_kind(def_id: DefId) -> ty::AnonConstKind {
2732        desc { |tcx| "looking up anon const kind of `{}`", tcx.def_path_str(def_id) }
2733        separate_provide_extern
2734    }
2735
2736    query trivial_const(def_id: DefId) -> Option<(mir::ConstValue, Ty<'tcx>)> {
2737        desc { |tcx| "checking if `{}` is a trivial const", tcx.def_path_str(def_id) }
2738        cache_on_disk_if { def_id.is_local() }
2739        separate_provide_extern
2740    }
2741
2742    /// Checks for the nearest `#[sanitize(xyz = "off")]` or
2743    /// `#[sanitize(xyz = "on")]` on this def and any enclosing defs, up to the
2744    /// crate root.
2745    ///
2746    /// Returns the sanitizer settings for this def.
2747    query sanitizer_settings_for(key: LocalDefId) -> SanitizerFnAttrs {
2748        desc { |tcx| "checking what set of sanitizers are enabled on `{}`", tcx.def_path_str(key) }
2749        feedable
2750    }
2751
2752    query check_externally_implementable_items(_: ()) {
2753        desc { "check externally implementable items" }
2754    }
2755
2756    /// Returns a list of all `externally implementable items` crate.
2757    query externally_implementable_items(cnum: CrateNum) -> &'tcx FxIndexMap<DefId, (EiiDecl, FxIndexMap<DefId, EiiImpl>)> {
2758        arena_cache
2759        desc { "looking up the externally implementable items of a crate" }
2760        cache_on_disk_if { *cnum == LOCAL_CRATE }
2761        separate_provide_extern
2762    }
2763}
2764
2765rustc_with_all_queries! { define_callbacks! }
2766rustc_feedable_queries! { define_feedable! }
2767
2768fn describe_as_module(def_id: impl Into<LocalDefId>, tcx: TyCtxt<'_>) -> String {
2769    let def_id = def_id.into();
2770    if def_id.is_top_level_module() {
2771        "top-level module".to_string()
2772    } else {
2773        format!("module `{}`", tcx.def_path_str(def_id))
2774    }
2775}