rustc_middle/ty/
instance.rs

1use std::assert_matches::assert_matches;
2use std::fmt;
3
4use rustc_data_structures::fx::FxHashMap;
5use rustc_errors::ErrorGuaranteed;
6use rustc_hir as hir;
7use rustc_hir::def::{CtorKind, DefKind, Namespace};
8use rustc_hir::def_id::{CrateNum, DefId};
9use rustc_hir::lang_items::LangItem;
10use rustc_index::bit_set::FiniteBitSet;
11use rustc_macros::{Decodable, Encodable, HashStable, Lift, TyDecodable, TyEncodable};
12use rustc_span::def_id::LOCAL_CRATE;
13use rustc_span::{DUMMY_SP, Span, Symbol};
14use tracing::{debug, instrument};
15
16use crate::error;
17use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags;
18use crate::ty::normalize_erasing_regions::NormalizationError;
19use crate::ty::print::{FmtPrinter, Print};
20use crate::ty::{
21    self, EarlyBinder, GenericArgs, GenericArgsRef, Ty, TyCtxt, TypeFoldable, TypeSuperVisitable,
22    TypeVisitable, TypeVisitableExt, TypeVisitor,
23};
24
25/// An `InstanceKind` along with the args that are needed to substitute the instance.
26///
27/// Monomorphization happens on-the-fly and no monomorphized MIR is ever created. Instead, this type
28/// simply couples a potentially generic `InstanceKind` with some args, and codegen and const eval
29/// will do all required instantiations as they run.
30///
31/// Note: the `Lift` impl is currently not used by rustc, but is used by
32/// rustc_codegen_cranelift when the `jit` feature is enabled.
33#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
34#[derive(HashStable, Lift, TypeFoldable, TypeVisitable)]
35pub struct Instance<'tcx> {
36    pub def: InstanceKind<'tcx>,
37    pub args: GenericArgsRef<'tcx>,
38}
39
40/// Describes why a `ReifyShim` was created. This is needed to distinguish a ReifyShim created to
41/// adjust for things like `#[track_caller]` in a vtable from a `ReifyShim` created to produce a
42/// function pointer from a vtable entry.
43/// Currently, this is only used when KCFI is enabled, as only KCFI needs to treat those two
44/// `ReifyShim`s differently.
45#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
46#[derive(TyEncodable, TyDecodable, HashStable)]
47pub enum ReifyReason {
48    /// The `ReifyShim` was created to produce a function pointer. This happens when:
49    /// * A vtable entry is directly converted to a function call (e.g. creating a fn ptr from a
50    ///   method on a `dyn` object).
51    /// * A function with `#[track_caller]` is converted to a function pointer
52    /// * If KCFI is enabled, creating a function pointer from a method on a dyn-compatible trait.
53    /// This includes the case of converting `::call`-like methods on closure-likes to function
54    /// pointers.
55    FnPtr,
56    /// This `ReifyShim` was created to populate a vtable. Currently, this happens when a
57    /// `#[track_caller]` mismatch occurs between the implementation of a method and the method.
58    /// This includes the case of `::call`-like methods in closure-likes' vtables.
59    Vtable,
60}
61
62#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
63#[derive(TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable, Lift)]
64pub enum InstanceKind<'tcx> {
65    /// A user-defined callable item.
66    ///
67    /// This includes:
68    /// - `fn` items
69    /// - closures
70    /// - coroutines
71    Item(DefId),
72
73    /// An intrinsic `fn` item (with`#[rustc_intrinsic]`).
74    ///
75    /// Alongside `Virtual`, this is the only `InstanceKind` that does not have its own callable MIR.
76    /// Instead, codegen and const eval "magically" evaluate calls to intrinsics purely in the
77    /// caller.
78    Intrinsic(DefId),
79
80    /// `<T as Trait>::method` where `method` receives unsizeable `self: Self` (part of the
81    /// `unsized_fn_params` feature).
82    ///
83    /// The generated shim will take `Self` via `*mut Self` - conceptually this is `&owned Self` -
84    /// and dereference the argument to call the original function.
85    VTableShim(DefId),
86
87    /// `fn()` pointer where the function itself cannot be turned into a pointer.
88    ///
89    /// One example is `<dyn Trait as Trait>::fn`, where the shim contains
90    /// a virtual call, which codegen supports only via a direct call to the
91    /// `<dyn Trait as Trait>::fn` instance (an `InstanceKind::Virtual`).
92    ///
93    /// Another example is functions annotated with `#[track_caller]`, which
94    /// must have their implicit caller location argument populated for a call.
95    /// Because this is a required part of the function's ABI but can't be tracked
96    /// as a property of the function pointer, we use a single "caller location"
97    /// (the definition of the function itself).
98    ///
99    /// The second field encodes *why* this shim was created. This allows distinguishing between
100    /// a `ReifyShim` that appears in a vtable vs one that appears as a function pointer.
101    ///
102    /// This field will only be populated if we are compiling in a mode that needs these shims
103    /// to be separable, currently only when KCFI is enabled.
104    ReifyShim(DefId, Option<ReifyReason>),
105
106    /// `<fn() as FnTrait>::call_*` (generated `FnTrait` implementation for `fn()` pointers).
107    ///
108    /// `DefId` is `FnTrait::call_*`.
109    FnPtrShim(DefId, Ty<'tcx>),
110
111    /// Dynamic dispatch to `<dyn Trait as Trait>::fn`.
112    ///
113    /// This `InstanceKind` may have a callable MIR as the default implementation.
114    /// Calls to `Virtual` instances must be codegen'd as virtual calls through the vtable.
115    /// *This means we might not know exactly what is being called.*
116    ///
117    /// If this is reified to a `fn` pointer, a `ReifyShim` is used (see `ReifyShim` above for more
118    /// details on that).
119    Virtual(DefId, usize),
120
121    /// `<[FnMut/Fn closure] as FnOnce>::call_once`.
122    ///
123    /// The `DefId` is the ID of the `call_once` method in `FnOnce`.
124    ///
125    /// This generates a body that will just borrow the (owned) self type,
126    /// and dispatch to the `FnMut::call_mut` instance for the closure.
127    ClosureOnceShim { call_once: DefId, track_caller: bool },
128
129    /// `<[FnMut/Fn coroutine-closure] as FnOnce>::call_once`
130    ///
131    /// The body generated here differs significantly from the `ClosureOnceShim`,
132    /// since we need to generate a distinct coroutine type that will move the
133    /// closure's upvars *out* of the closure.
134    ConstructCoroutineInClosureShim {
135        coroutine_closure_def_id: DefId,
136        // Whether the generated MIR body takes the coroutine by-ref. This is
137        // because the signature of `<{async fn} as FnMut>::call_mut` is:
138        // `fn(&mut self, args: A) -> <Self as FnOnce>::Output`, that is to say
139        // that it returns the `FnOnce`-flavored coroutine but takes the closure
140        // by mut ref (and similarly for `Fn::call`).
141        receiver_by_ref: bool,
142    },
143
144    /// Compiler-generated accessor for thread locals which returns a reference to the thread local
145    /// the `DefId` defines. This is used to export thread locals from dylibs on platforms lacking
146    /// native support.
147    ThreadLocalShim(DefId),
148
149    /// Proxy shim for async drop of future (def_id, proxy_cor_ty, impl_cor_ty)
150    FutureDropPollShim(DefId, Ty<'tcx>, Ty<'tcx>),
151
152    /// `core::ptr::drop_in_place::<T>`.
153    ///
154    /// The `DefId` is for `core::ptr::drop_in_place`.
155    /// The `Option<Ty<'tcx>>` is either `Some(T)`, or `None` for empty drop
156    /// glue.
157    DropGlue(DefId, Option<Ty<'tcx>>),
158
159    /// Compiler-generated `<T as Clone>::clone` implementation.
160    ///
161    /// For all types that automatically implement `Copy`, a trivial `Clone` impl is provided too.
162    /// Additionally, arrays, tuples, and closures get a `Clone` shim even if they aren't `Copy`.
163    ///
164    /// The `DefId` is for `Clone::clone`, the `Ty` is the type `T` with the builtin `Clone` impl.
165    CloneShim(DefId, Ty<'tcx>),
166
167    /// Compiler-generated `<T as FnPtr>::addr` implementation.
168    ///
169    /// Automatically generated for all potentially higher-ranked `fn(I) -> R` types.
170    ///
171    /// The `DefId` is for `FnPtr::addr`, the `Ty` is the type `T`.
172    FnPtrAddrShim(DefId, Ty<'tcx>),
173
174    /// `core::future::async_drop::async_drop_in_place::<'_, T>`.
175    ///
176    /// The `DefId` is for `core::future::async_drop::async_drop_in_place`, the `Ty`
177    /// is the type `T`.
178    AsyncDropGlueCtorShim(DefId, Ty<'tcx>),
179
180    /// `core::future::async_drop::async_drop_in_place::<'_, T>::{closure}`.
181    ///
182    /// async_drop_in_place poll function implementation (for generated coroutine).
183    /// `Ty` here is `async_drop_in_place<T>::{closure}` coroutine type, not just `T`
184    AsyncDropGlue(DefId, Ty<'tcx>),
185}
186
187impl<'tcx> Instance<'tcx> {
188    /// Returns the `Ty` corresponding to this `Instance`, with generic instantiations applied and
189    /// lifetimes erased, allowing a `ParamEnv` to be specified for use during normalization.
190    pub fn ty(&self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> Ty<'tcx> {
191        let ty = tcx.type_of(self.def.def_id());
192        tcx.instantiate_and_normalize_erasing_regions(self.args, typing_env, ty)
193    }
194
195    /// Finds a crate that contains a monomorphization of this instance that
196    /// can be linked to from the local crate. A return value of `None` means
197    /// no upstream crate provides such an exported monomorphization.
198    ///
199    /// This method already takes into account the global `-Zshare-generics`
200    /// setting, always returning `None` if `share-generics` is off.
201    pub fn upstream_monomorphization(&self, tcx: TyCtxt<'tcx>) -> Option<CrateNum> {
202        // If this is an item that is defined in the local crate, no upstream
203        // crate can know about it/provide a monomorphization.
204        if self.def_id().is_local() {
205            return None;
206        }
207
208        // If we are not in share generics mode, we don't link to upstream
209        // monomorphizations but always instantiate our own internal versions
210        // instead.
211        if !tcx.sess.opts.share_generics()
212            // However, if the def_id is marked inline(never), then it's fine to just reuse the
213            // upstream monomorphization.
214            && tcx.codegen_fn_attrs(self.def_id()).inline != rustc_hir::attrs::InlineAttr::Never
215        {
216            return None;
217        }
218
219        // If this a non-generic instance, it cannot be a shared monomorphization.
220        self.args.non_erasable_generics().next()?;
221
222        // compiler_builtins cannot use upstream monomorphizations.
223        if tcx.is_compiler_builtins(LOCAL_CRATE) {
224            return None;
225        }
226
227        match self.def {
228            InstanceKind::Item(def) => tcx
229                .upstream_monomorphizations_for(def)
230                .and_then(|monos| monos.get(&self.args).cloned()),
231            InstanceKind::DropGlue(_, Some(_)) => tcx.upstream_drop_glue_for(self.args),
232            InstanceKind::AsyncDropGlue(_, _) => None,
233            InstanceKind::FutureDropPollShim(_, _, _) => None,
234            InstanceKind::AsyncDropGlueCtorShim(_, _) => {
235                tcx.upstream_async_drop_glue_for(self.args)
236            }
237            _ => None,
238        }
239    }
240}
241
242impl<'tcx> InstanceKind<'tcx> {
243    #[inline]
244    pub fn def_id(self) -> DefId {
245        match self {
246            InstanceKind::Item(def_id)
247            | InstanceKind::VTableShim(def_id)
248            | InstanceKind::ReifyShim(def_id, _)
249            | InstanceKind::FnPtrShim(def_id, _)
250            | InstanceKind::Virtual(def_id, _)
251            | InstanceKind::Intrinsic(def_id)
252            | InstanceKind::ThreadLocalShim(def_id)
253            | InstanceKind::ClosureOnceShim { call_once: def_id, track_caller: _ }
254            | ty::InstanceKind::ConstructCoroutineInClosureShim {
255                coroutine_closure_def_id: def_id,
256                receiver_by_ref: _,
257            }
258            | InstanceKind::DropGlue(def_id, _)
259            | InstanceKind::CloneShim(def_id, _)
260            | InstanceKind::FnPtrAddrShim(def_id, _)
261            | InstanceKind::FutureDropPollShim(def_id, _, _)
262            | InstanceKind::AsyncDropGlue(def_id, _)
263            | InstanceKind::AsyncDropGlueCtorShim(def_id, _) => def_id,
264        }
265    }
266
267    /// Returns the `DefId` of instances which might not require codegen locally.
268    pub fn def_id_if_not_guaranteed_local_codegen(self) -> Option<DefId> {
269        match self {
270            ty::InstanceKind::Item(def) => Some(def),
271            ty::InstanceKind::DropGlue(def_id, Some(_))
272            | InstanceKind::AsyncDropGlueCtorShim(def_id, _)
273            | InstanceKind::AsyncDropGlue(def_id, _)
274            | InstanceKind::FutureDropPollShim(def_id, ..)
275            | InstanceKind::ThreadLocalShim(def_id) => Some(def_id),
276            InstanceKind::VTableShim(..)
277            | InstanceKind::ReifyShim(..)
278            | InstanceKind::FnPtrShim(..)
279            | InstanceKind::Virtual(..)
280            | InstanceKind::Intrinsic(..)
281            | InstanceKind::ClosureOnceShim { .. }
282            | ty::InstanceKind::ConstructCoroutineInClosureShim { .. }
283            | InstanceKind::DropGlue(..)
284            | InstanceKind::CloneShim(..)
285            | InstanceKind::FnPtrAddrShim(..) => None,
286        }
287    }
288
289    #[inline]
290    pub fn get_attrs(
291        &self,
292        tcx: TyCtxt<'tcx>,
293        attr: Symbol,
294    ) -> impl Iterator<Item = &'tcx hir::Attribute> {
295        tcx.get_attrs(self.def_id(), attr)
296    }
297
298    /// Returns `true` if the LLVM version of this instance is unconditionally
299    /// marked with `inline`. This implies that a copy of this instance is
300    /// generated in every codegen unit.
301    /// Note that this is only a hint. See the documentation for
302    /// `generates_cgu_internal_copy` for more information.
303    pub fn requires_inline(&self, tcx: TyCtxt<'tcx>) -> bool {
304        use rustc_hir::definitions::DefPathData;
305        let def_id = match *self {
306            ty::InstanceKind::Item(def) => def,
307            ty::InstanceKind::DropGlue(_, Some(_)) => return false,
308            ty::InstanceKind::AsyncDropGlueCtorShim(_, ty) => return ty.is_coroutine(),
309            ty::InstanceKind::FutureDropPollShim(_, _, _) => return false,
310            ty::InstanceKind::AsyncDropGlue(_, _) => return false,
311            ty::InstanceKind::ThreadLocalShim(_) => return false,
312            _ => return true,
313        };
314        matches!(
315            tcx.def_key(def_id).disambiguated_data.data,
316            DefPathData::Ctor | DefPathData::Closure
317        )
318    }
319
320    pub fn requires_caller_location(&self, tcx: TyCtxt<'_>) -> bool {
321        match *self {
322            InstanceKind::Item(def_id) | InstanceKind::Virtual(def_id, _) => {
323                tcx.body_codegen_attrs(def_id).flags.contains(CodegenFnAttrFlags::TRACK_CALLER)
324            }
325            InstanceKind::ClosureOnceShim { call_once: _, track_caller } => track_caller,
326            _ => false,
327        }
328    }
329
330    /// Returns `true` when the MIR body associated with this instance should be monomorphized
331    /// by its users (e.g. codegen or miri) by instantiating the `args` from `Instance` (see
332    /// `Instance::args_for_mir_body`).
333    ///
334    /// Otherwise, returns `false` only for some kinds of shims where the construction of the MIR
335    /// body should perform necessary instantiations.
336    pub fn has_polymorphic_mir_body(&self) -> bool {
337        match *self {
338            InstanceKind::CloneShim(..)
339            | InstanceKind::ThreadLocalShim(..)
340            | InstanceKind::FnPtrAddrShim(..)
341            | InstanceKind::FnPtrShim(..)
342            | InstanceKind::DropGlue(_, Some(_))
343            | InstanceKind::FutureDropPollShim(..)
344            | InstanceKind::AsyncDropGlue(_, _) => false,
345            InstanceKind::AsyncDropGlueCtorShim(_, _) => false,
346            InstanceKind::ClosureOnceShim { .. }
347            | InstanceKind::ConstructCoroutineInClosureShim { .. }
348            | InstanceKind::DropGlue(..)
349            | InstanceKind::Item(_)
350            | InstanceKind::Intrinsic(..)
351            | InstanceKind::ReifyShim(..)
352            | InstanceKind::Virtual(..)
353            | InstanceKind::VTableShim(..) => true,
354        }
355    }
356}
357
358fn type_length<'tcx>(item: impl TypeVisitable<TyCtxt<'tcx>>) -> usize {
359    struct Visitor<'tcx> {
360        type_length: usize,
361        cache: FxHashMap<Ty<'tcx>, usize>,
362    }
363    impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for Visitor<'tcx> {
364        fn visit_ty(&mut self, t: Ty<'tcx>) {
365            if let Some(&value) = self.cache.get(&t) {
366                self.type_length += value;
367                return;
368            }
369
370            let prev = self.type_length;
371            self.type_length += 1;
372            t.super_visit_with(self);
373
374            // We don't try to use the cache if the type is fairly small.
375            if self.type_length > 16 {
376                self.cache.insert(t, self.type_length - prev);
377            }
378        }
379
380        fn visit_const(&mut self, ct: ty::Const<'tcx>) {
381            self.type_length += 1;
382            ct.super_visit_with(self);
383        }
384    }
385    let mut visitor = Visitor { type_length: 0, cache: Default::default() };
386    item.visit_with(&mut visitor);
387
388    visitor.type_length
389}
390
391impl<'tcx> fmt::Display for Instance<'tcx> {
392    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
393        ty::tls::with(|tcx| {
394            let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
395            let instance = tcx.lift(*self).expect("could not lift for printing");
396            instance.print(&mut p)?;
397            let s = p.into_buffer();
398            f.write_str(&s)
399        })
400    }
401}
402
403// async_drop_in_place<T>::coroutine.poll, when T is a standard coroutine,
404// should be resolved to this coroutine's future_drop_poll (through FutureDropPollShim proxy).
405// async_drop_in_place<async_drop_in_place<T>::coroutine>::coroutine.poll,
406// when T is a standard coroutine, should be resolved to this coroutine's future_drop_poll.
407// async_drop_in_place<async_drop_in_place<T>::coroutine>::coroutine.poll,
408// when T is not a coroutine, should be resolved to the innermost
409// async_drop_in_place<T>::coroutine's poll function (through FutureDropPollShim proxy)
410fn resolve_async_drop_poll<'tcx>(mut cor_ty: Ty<'tcx>) -> Instance<'tcx> {
411    let first_cor = cor_ty;
412    let ty::Coroutine(poll_def_id, proxy_args) = first_cor.kind() else {
413        bug!();
414    };
415    let poll_def_id = *poll_def_id;
416    let mut child_ty = cor_ty;
417    loop {
418        if let ty::Coroutine(child_def, child_args) = child_ty.kind() {
419            cor_ty = child_ty;
420            if *child_def == poll_def_id {
421                child_ty = child_args.first().unwrap().expect_ty();
422                continue;
423            } else {
424                return Instance {
425                    def: ty::InstanceKind::FutureDropPollShim(poll_def_id, first_cor, cor_ty),
426                    args: proxy_args,
427                };
428            }
429        } else {
430            let ty::Coroutine(_, child_args) = cor_ty.kind() else {
431                bug!();
432            };
433            if first_cor != cor_ty {
434                return Instance {
435                    def: ty::InstanceKind::FutureDropPollShim(poll_def_id, first_cor, cor_ty),
436                    args: proxy_args,
437                };
438            } else {
439                return Instance {
440                    def: ty::InstanceKind::AsyncDropGlue(poll_def_id, cor_ty),
441                    args: child_args,
442                };
443            }
444        }
445    }
446}
447
448impl<'tcx> Instance<'tcx> {
449    /// Creates a new [`InstanceKind::Item`] from the `def_id` and `args`.
450    ///
451    /// Note that this item corresponds to the body of `def_id` directly, which
452    /// likely does not make sense for trait items which need to be resolved to an
453    /// implementation, and which may not even have a body themselves. Usages of
454    /// this function should probably use [`Instance::expect_resolve`], or if run
455    /// in a polymorphic environment or within a lint (that may encounter ambiguity)
456    /// [`Instance::try_resolve`] instead.
457    pub fn new_raw(def_id: DefId, args: GenericArgsRef<'tcx>) -> Instance<'tcx> {
458        assert!(
459            !args.has_escaping_bound_vars(),
460            "args of instance {def_id:?} has escaping bound vars: {args:?}"
461        );
462        Instance { def: InstanceKind::Item(def_id), args }
463    }
464
465    pub fn mono(tcx: TyCtxt<'tcx>, def_id: DefId) -> Instance<'tcx> {
466        let args = GenericArgs::for_item(tcx, def_id, |param, _| match param.kind {
467            ty::GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
468            ty::GenericParamDefKind::Type { .. } => {
469                bug!("Instance::mono: {:?} has type parameters", def_id)
470            }
471            ty::GenericParamDefKind::Const { .. } => {
472                bug!("Instance::mono: {:?} has const parameters", def_id)
473            }
474        });
475
476        Instance::new_raw(def_id, args)
477    }
478
479    #[inline]
480    pub fn def_id(&self) -> DefId {
481        self.def.def_id()
482    }
483
484    /// Resolves a `(def_id, args)` pair to an (optional) instance -- most commonly,
485    /// this is used to find the precise code that will run for a trait method invocation,
486    /// if known. This should only be used for functions and consts. If you want to
487    /// resolve an associated type, use [`TyCtxt::try_normalize_erasing_regions`].
488    ///
489    /// Returns `Ok(None)` if we cannot resolve `Instance` to a specific instance.
490    /// For example, in a context like this,
491    ///
492    /// ```ignore (illustrative)
493    /// fn foo<T: Debug>(t: T) { ... }
494    /// ```
495    ///
496    /// trying to resolve `Debug::fmt` applied to `T` will yield `Ok(None)`, because we do not
497    /// know what code ought to run. This setting is also affected by the current `TypingMode`
498    /// of the environment.
499    ///
500    /// Presuming that coherence and type-check have succeeded, if this method is invoked
501    /// in a monomorphic context (i.e., like during codegen), then it is guaranteed to return
502    /// `Ok(Some(instance))`, **except** for when the instance's inputs hit the type size limit,
503    /// in which case it may bail out and return `Ok(None)`.
504    ///
505    /// Returns `Err(ErrorGuaranteed)` when the `Instance` resolution process
506    /// couldn't complete due to errors elsewhere - this is distinct
507    /// from `Ok(None)` to avoid misleading diagnostics when an error
508    /// has already been/will be emitted, for the original cause
509    #[instrument(level = "debug", skip(tcx), ret)]
510    pub fn try_resolve(
511        tcx: TyCtxt<'tcx>,
512        typing_env: ty::TypingEnv<'tcx>,
513        def_id: DefId,
514        args: GenericArgsRef<'tcx>,
515    ) -> Result<Option<Instance<'tcx>>, ErrorGuaranteed> {
516        assert_matches!(
517            tcx.def_kind(def_id),
518            DefKind::Fn
519                | DefKind::AssocFn
520                | DefKind::Const
521                | DefKind::AssocConst
522                | DefKind::AnonConst
523                | DefKind::InlineConst
524                | DefKind::Static { .. }
525                | DefKind::Ctor(_, CtorKind::Fn)
526                | DefKind::Closure
527                | DefKind::SyntheticCoroutineBody,
528            "`Instance::try_resolve` should only be used to resolve instances of \
529            functions, statics, and consts; to resolve associated types, use \
530            `try_normalize_erasing_regions`."
531        );
532
533        // Rust code can easily create exponentially-long types using only a
534        // polynomial recursion depth. Even with the default recursion
535        // depth, you can easily get cases that take >2^60 steps to run,
536        // which means that rustc basically hangs.
537        //
538        // Bail out in these cases to avoid that bad user experience.
539        if tcx.sess.opts.unstable_opts.enforce_type_length_limit
540            && !tcx.type_length_limit().value_within_limit(type_length(args))
541        {
542            return Ok(None);
543        }
544
545        // All regions in the result of this query are erased, so it's
546        // fine to erase all of the input regions.
547        tcx.resolve_instance_raw(tcx.erase_regions(typing_env.as_query_input((def_id, args))))
548    }
549
550    pub fn expect_resolve(
551        tcx: TyCtxt<'tcx>,
552        typing_env: ty::TypingEnv<'tcx>,
553        def_id: DefId,
554        args: GenericArgsRef<'tcx>,
555        span: Span,
556    ) -> Instance<'tcx> {
557        // We compute the span lazily, to avoid unnecessary query calls.
558        // If `span` is a DUMMY_SP, and the def id is local, then use the
559        // def span of the def id.
560        let span_or_local_def_span =
561            || if span.is_dummy() && def_id.is_local() { tcx.def_span(def_id) } else { span };
562
563        match ty::Instance::try_resolve(tcx, typing_env, def_id, args) {
564            Ok(Some(instance)) => instance,
565            Ok(None) => {
566                let type_length = type_length(args);
567                if !tcx.type_length_limit().value_within_limit(type_length) {
568                    tcx.dcx().emit_fatal(error::TypeLengthLimit {
569                        // We don't use `def_span(def_id)` so that diagnostics point
570                        // to the crate root during mono instead of to foreign items.
571                        // This is arguably better.
572                        span: span_or_local_def_span(),
573                        instance: Instance::new_raw(def_id, args),
574                        type_length,
575                    });
576                } else {
577                    span_bug!(
578                        span_or_local_def_span(),
579                        "failed to resolve instance for {}",
580                        tcx.def_path_str_with_args(def_id, args)
581                    )
582                }
583            }
584            instance => span_bug!(
585                span_or_local_def_span(),
586                "failed to resolve instance for {}: {instance:#?}",
587                tcx.def_path_str_with_args(def_id, args)
588            ),
589        }
590    }
591
592    pub fn resolve_for_fn_ptr(
593        tcx: TyCtxt<'tcx>,
594        typing_env: ty::TypingEnv<'tcx>,
595        def_id: DefId,
596        args: GenericArgsRef<'tcx>,
597    ) -> Option<Instance<'tcx>> {
598        debug!("resolve(def_id={:?}, args={:?})", def_id, args);
599        // Use either `resolve_closure` or `resolve_for_vtable`
600        assert!(!tcx.is_closure_like(def_id), "Called `resolve_for_fn_ptr` on closure: {def_id:?}");
601        let reason = tcx.sess.is_sanitizer_kcfi_enabled().then_some(ReifyReason::FnPtr);
602        Instance::try_resolve(tcx, typing_env, def_id, args).ok().flatten().map(|mut resolved| {
603            match resolved.def {
604                InstanceKind::Item(def) if resolved.def.requires_caller_location(tcx) => {
605                    debug!(" => fn pointer created for function with #[track_caller]");
606                    resolved.def = InstanceKind::ReifyShim(def, reason);
607                }
608                InstanceKind::Virtual(def_id, _) => {
609                    debug!(" => fn pointer created for virtual call");
610                    resolved.def = InstanceKind::ReifyShim(def_id, reason);
611                }
612                // Reify `Trait::method` implementations if KCFI is enabled
613                // FIXME(maurer) only reify it if it is a vtable-safe function
614                _ if tcx.sess.is_sanitizer_kcfi_enabled()
615                    && tcx
616                        .opt_associated_item(def_id)
617                        .and_then(|assoc| assoc.trait_item_def_id)
618                        .is_some() =>
619                {
620                    // If this function could also go in a vtable, we need to `ReifyShim` it with
621                    // KCFI because it can only attach one type per function.
622                    resolved.def = InstanceKind::ReifyShim(resolved.def_id(), reason)
623                }
624                // Reify `::call`-like method implementations if KCFI is enabled
625                _ if tcx.sess.is_sanitizer_kcfi_enabled()
626                    && tcx.is_closure_like(resolved.def_id()) =>
627                {
628                    // Reroute through a reify via the *unresolved* instance. The resolved one can't
629                    // be directly reified because it's closure-like. The reify can handle the
630                    // unresolved instance.
631                    resolved = Instance { def: InstanceKind::ReifyShim(def_id, reason), args }
632                }
633                _ => {}
634            }
635
636            resolved
637        })
638    }
639
640    pub fn expect_resolve_for_vtable(
641        tcx: TyCtxt<'tcx>,
642        typing_env: ty::TypingEnv<'tcx>,
643        def_id: DefId,
644        args: GenericArgsRef<'tcx>,
645        span: Span,
646    ) -> Instance<'tcx> {
647        debug!("resolve_for_vtable(def_id={:?}, args={:?})", def_id, args);
648        let fn_sig = tcx.fn_sig(def_id).instantiate_identity();
649        let is_vtable_shim = !fn_sig.inputs().skip_binder().is_empty()
650            && fn_sig.input(0).skip_binder().is_param(0)
651            && tcx.generics_of(def_id).has_self;
652
653        if is_vtable_shim {
654            debug!(" => associated item with unsizeable self: Self");
655            return Instance { def: InstanceKind::VTableShim(def_id), args };
656        }
657
658        let mut resolved = Instance::expect_resolve(tcx, typing_env, def_id, args, span);
659
660        let reason = tcx.sess.is_sanitizer_kcfi_enabled().then_some(ReifyReason::Vtable);
661        match resolved.def {
662            InstanceKind::Item(def) => {
663                // We need to generate a shim when we cannot guarantee that
664                // the caller of a trait object method will be aware of
665                // `#[track_caller]` - this ensures that the caller
666                // and callee ABI will always match.
667                //
668                // The shim is generated when all of these conditions are met:
669                //
670                // 1) The underlying method expects a caller location parameter
671                // in the ABI
672                let needs_track_caller_shim = resolved.def.requires_caller_location(tcx)
673                    // 2) The caller location parameter comes from having `#[track_caller]`
674                    // on the implementation, and *not* on the trait method.
675                    && !tcx.should_inherit_track_caller(def)
676                    // If the method implementation comes from the trait definition itself
677                    // (e.g. `trait Foo { #[track_caller] my_fn() { /* impl */ } }`),
678                    // then we don't need to generate a shim. This check is needed because
679                    // `should_inherit_track_caller` returns `false` if our method
680                    // implementation comes from the trait block, and not an impl block
681                    && !matches!(
682                        tcx.opt_associated_item(def),
683                        Some(ty::AssocItem {
684                            container: ty::AssocItemContainer::Trait,
685                            ..
686                        })
687                    );
688                if needs_track_caller_shim {
689                    if tcx.is_closure_like(def) {
690                        debug!(
691                            " => vtable fn pointer created for closure with #[track_caller]: {:?} for method {:?} {:?}",
692                            def, def_id, args
693                        );
694
695                        // Create a shim for the `FnOnce/FnMut/Fn` method we are calling
696                        // - unlike functions, invoking a closure always goes through a
697                        // trait.
698                        resolved = Instance { def: InstanceKind::ReifyShim(def_id, reason), args };
699                    } else {
700                        debug!(
701                            " => vtable fn pointer created for function with #[track_caller]: {:?}",
702                            def
703                        );
704                        resolved.def = InstanceKind::ReifyShim(def, reason);
705                    }
706                }
707            }
708            InstanceKind::Virtual(def_id, _) => {
709                debug!(" => vtable fn pointer created for virtual call");
710                resolved.def = InstanceKind::ReifyShim(def_id, reason)
711            }
712            _ => {}
713        }
714
715        resolved
716    }
717
718    pub fn resolve_closure(
719        tcx: TyCtxt<'tcx>,
720        def_id: DefId,
721        args: ty::GenericArgsRef<'tcx>,
722        requested_kind: ty::ClosureKind,
723    ) -> Instance<'tcx> {
724        let actual_kind = args.as_closure().kind();
725
726        match needs_fn_once_adapter_shim(actual_kind, requested_kind) {
727            Ok(true) => Instance::fn_once_adapter_instance(tcx, def_id, args),
728            _ => Instance::new_raw(def_id, args),
729        }
730    }
731
732    pub fn resolve_drop_in_place(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> ty::Instance<'tcx> {
733        let def_id = tcx.require_lang_item(LangItem::DropInPlace, DUMMY_SP);
734        let args = tcx.mk_args(&[ty.into()]);
735        Instance::expect_resolve(
736            tcx,
737            ty::TypingEnv::fully_monomorphized(),
738            def_id,
739            args,
740            ty.ty_adt_def().and_then(|adt| tcx.hir_span_if_local(adt.did())).unwrap_or(DUMMY_SP),
741        )
742    }
743
744    pub fn resolve_async_drop_in_place(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> ty::Instance<'tcx> {
745        let def_id = tcx.require_lang_item(LangItem::AsyncDropInPlace, DUMMY_SP);
746        let args = tcx.mk_args(&[ty.into()]);
747        Instance::expect_resolve(
748            tcx,
749            ty::TypingEnv::fully_monomorphized(),
750            def_id,
751            args,
752            ty.ty_adt_def().and_then(|adt| tcx.hir_span_if_local(adt.did())).unwrap_or(DUMMY_SP),
753        )
754    }
755
756    pub fn resolve_async_drop_in_place_poll(
757        tcx: TyCtxt<'tcx>,
758        def_id: DefId,
759        ty: Ty<'tcx>,
760    ) -> ty::Instance<'tcx> {
761        let args = tcx.mk_args(&[ty.into()]);
762        Instance::expect_resolve(tcx, ty::TypingEnv::fully_monomorphized(), def_id, args, DUMMY_SP)
763    }
764
765    #[instrument(level = "debug", skip(tcx), ret)]
766    pub fn fn_once_adapter_instance(
767        tcx: TyCtxt<'tcx>,
768        closure_did: DefId,
769        args: ty::GenericArgsRef<'tcx>,
770    ) -> Instance<'tcx> {
771        let fn_once = tcx.require_lang_item(LangItem::FnOnce, DUMMY_SP);
772        let call_once = tcx
773            .associated_items(fn_once)
774            .in_definition_order()
775            .find(|it| it.is_fn())
776            .unwrap()
777            .def_id;
778        let track_caller =
779            tcx.codegen_fn_attrs(closure_did).flags.contains(CodegenFnAttrFlags::TRACK_CALLER);
780        let def = ty::InstanceKind::ClosureOnceShim { call_once, track_caller };
781
782        let self_ty = Ty::new_closure(tcx, closure_did, args);
783
784        let tupled_inputs_ty = args.as_closure().sig().map_bound(|sig| sig.inputs()[0]);
785        let tupled_inputs_ty = tcx.instantiate_bound_regions_with_erased(tupled_inputs_ty);
786        let args = tcx.mk_args_trait(self_ty, [tupled_inputs_ty.into()]);
787
788        debug!(?self_ty, args=?tupled_inputs_ty.tuple_fields());
789        Instance { def, args }
790    }
791
792    pub fn try_resolve_item_for_coroutine(
793        tcx: TyCtxt<'tcx>,
794        trait_item_id: DefId,
795        trait_id: DefId,
796        rcvr_args: ty::GenericArgsRef<'tcx>,
797    ) -> Option<Instance<'tcx>> {
798        let ty::Coroutine(coroutine_def_id, args) = *rcvr_args.type_at(0).kind() else {
799            return None;
800        };
801        let coroutine_kind = tcx.coroutine_kind(coroutine_def_id).unwrap();
802
803        let coroutine_callable_item = if tcx.is_lang_item(trait_id, LangItem::Future) {
804            assert_matches!(
805                coroutine_kind,
806                hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)
807            );
808            hir::LangItem::FuturePoll
809        } else if tcx.is_lang_item(trait_id, LangItem::Iterator) {
810            assert_matches!(
811                coroutine_kind,
812                hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _)
813            );
814            hir::LangItem::IteratorNext
815        } else if tcx.is_lang_item(trait_id, LangItem::AsyncIterator) {
816            assert_matches!(
817                coroutine_kind,
818                hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _)
819            );
820            hir::LangItem::AsyncIteratorPollNext
821        } else if tcx.is_lang_item(trait_id, LangItem::Coroutine) {
822            assert_matches!(coroutine_kind, hir::CoroutineKind::Coroutine(_));
823            hir::LangItem::CoroutineResume
824        } else {
825            return None;
826        };
827
828        if tcx.is_lang_item(trait_item_id, coroutine_callable_item) {
829            if tcx.is_async_drop_in_place_coroutine(coroutine_def_id) {
830                return Some(resolve_async_drop_poll(rcvr_args.type_at(0)));
831            }
832            let ty::Coroutine(_, id_args) = *tcx.type_of(coroutine_def_id).skip_binder().kind()
833            else {
834                bug!()
835            };
836
837            // If the closure's kind ty disagrees with the identity closure's kind ty,
838            // then this must be a coroutine generated by one of the `ConstructCoroutineInClosureShim`s.
839            if args.as_coroutine().kind_ty() == id_args.as_coroutine().kind_ty() {
840                Some(Instance { def: ty::InstanceKind::Item(coroutine_def_id), args })
841            } else {
842                Some(Instance {
843                    def: ty::InstanceKind::Item(
844                        tcx.coroutine_by_move_body_def_id(coroutine_def_id),
845                    ),
846                    args,
847                })
848            }
849        } else {
850            // All other methods should be defaulted methods of the built-in trait.
851            // This is important for `Iterator`'s combinators, but also useful for
852            // adding future default methods to `Future`, for instance.
853            debug_assert!(tcx.defaultness(trait_item_id).has_value());
854            Some(Instance::new_raw(trait_item_id, rcvr_args))
855        }
856    }
857
858    /// Depending on the kind of `InstanceKind`, the MIR body associated with an
859    /// instance is expressed in terms of the generic parameters of `self.def_id()`, and in other
860    /// cases the MIR body is expressed in terms of the types found in the generic parameter array.
861    /// In the former case, we want to instantiate those generic types and replace them with the
862    /// values from the args when monomorphizing the function body. But in the latter case, we
863    /// don't want to do that instantiation, since it has already been done effectively.
864    ///
865    /// This function returns `Some(args)` in the former case and `None` otherwise -- i.e., if
866    /// this function returns `None`, then the MIR body does not require instantiation during
867    /// codegen.
868    fn args_for_mir_body(&self) -> Option<GenericArgsRef<'tcx>> {
869        self.def.has_polymorphic_mir_body().then_some(self.args)
870    }
871
872    pub fn instantiate_mir<T>(&self, tcx: TyCtxt<'tcx>, v: EarlyBinder<'tcx, &T>) -> T
873    where
874        T: TypeFoldable<TyCtxt<'tcx>> + Copy,
875    {
876        let v = v.map_bound(|v| *v);
877        if let Some(args) = self.args_for_mir_body() {
878            v.instantiate(tcx, args)
879        } else {
880            v.instantiate_identity()
881        }
882    }
883
884    #[inline(always)]
885    // Keep me in sync with try_instantiate_mir_and_normalize_erasing_regions
886    pub fn instantiate_mir_and_normalize_erasing_regions<T>(
887        &self,
888        tcx: TyCtxt<'tcx>,
889        typing_env: ty::TypingEnv<'tcx>,
890        v: EarlyBinder<'tcx, T>,
891    ) -> T
892    where
893        T: TypeFoldable<TyCtxt<'tcx>>,
894    {
895        if let Some(args) = self.args_for_mir_body() {
896            tcx.instantiate_and_normalize_erasing_regions(args, typing_env, v)
897        } else {
898            tcx.normalize_erasing_regions(typing_env, v.instantiate_identity())
899        }
900    }
901
902    #[inline(always)]
903    // Keep me in sync with instantiate_mir_and_normalize_erasing_regions
904    pub fn try_instantiate_mir_and_normalize_erasing_regions<T>(
905        &self,
906        tcx: TyCtxt<'tcx>,
907        typing_env: ty::TypingEnv<'tcx>,
908        v: EarlyBinder<'tcx, T>,
909    ) -> Result<T, NormalizationError<'tcx>>
910    where
911        T: TypeFoldable<TyCtxt<'tcx>>,
912    {
913        if let Some(args) = self.args_for_mir_body() {
914            tcx.try_instantiate_and_normalize_erasing_regions(args, typing_env, v)
915        } else {
916            // We're using `instantiate_identity` as e.g.
917            // `FnPtrShim` is separately generated for every
918            // instantiation of the `FnDef`, so the MIR body
919            // is already instantiated. Any generic parameters it
920            // contains are generic parameters from the caller.
921            tcx.try_normalize_erasing_regions(typing_env, v.instantiate_identity())
922        }
923    }
924}
925
926fn needs_fn_once_adapter_shim(
927    actual_closure_kind: ty::ClosureKind,
928    trait_closure_kind: ty::ClosureKind,
929) -> Result<bool, ()> {
930    match (actual_closure_kind, trait_closure_kind) {
931        (ty::ClosureKind::Fn, ty::ClosureKind::Fn)
932        | (ty::ClosureKind::FnMut, ty::ClosureKind::FnMut)
933        | (ty::ClosureKind::FnOnce, ty::ClosureKind::FnOnce) => {
934            // No adapter needed.
935            Ok(false)
936        }
937        (ty::ClosureKind::Fn, ty::ClosureKind::FnMut) => {
938            // The closure fn is a `fn(&self, ...)`, but we want a `fn(&mut self, ...)`.
939            // At codegen time, these are basically the same, so we can just return the closure.
940            Ok(false)
941        }
942        (ty::ClosureKind::Fn | ty::ClosureKind::FnMut, ty::ClosureKind::FnOnce) => {
943            // The closure fn is a `fn(&self, ...)` or `fn(&mut self, ...)`, but
944            // we want a `fn(self, ...)`. We can produce this by doing something like:
945            //
946            //     fn call_once(self, ...) { Fn::call(&self, ...) }
947            //     fn call_once(mut self, ...) { FnMut::call_mut(&mut self, ...) }
948            //
949            // These are both the same at codegen time.
950            Ok(true)
951        }
952        (ty::ClosureKind::FnMut | ty::ClosureKind::FnOnce, _) => Err(()),
953    }
954}
955
956// Set bits represent unused generic parameters.
957// An empty set indicates that all parameters are used.
958#[derive(Debug, Copy, Clone, Eq, PartialEq, Decodable, Encodable, HashStable)]
959pub struct UnusedGenericParams(FiniteBitSet<u32>);
960
961impl Default for UnusedGenericParams {
962    fn default() -> Self {
963        UnusedGenericParams::new_all_used()
964    }
965}
966
967impl UnusedGenericParams {
968    pub fn new_all_unused(amount: u32) -> Self {
969        let mut bitset = FiniteBitSet::new_empty();
970        bitset.set_range(0..amount);
971        Self(bitset)
972    }
973
974    pub fn new_all_used() -> Self {
975        Self(FiniteBitSet::new_empty())
976    }
977
978    pub fn mark_used(&mut self, idx: u32) {
979        self.0.clear(idx);
980    }
981
982    pub fn is_unused(&self, idx: u32) -> bool {
983        self.0.contains(idx).unwrap_or(false)
984    }
985
986    pub fn is_used(&self, idx: u32) -> bool {
987        !self.is_unused(idx)
988    }
989
990    pub fn all_used(&self) -> bool {
991        self.0.is_empty()
992    }
993
994    pub fn bits(&self) -> u32 {
995        self.0.0
996    }
997
998    pub fn from_bits(bits: u32) -> UnusedGenericParams {
999        UnusedGenericParams(FiniteBitSet(bits))
1000    }
1001}