rustc_middle/ty/
instance.rs

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