• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags;
2 use crate::ty::print::{FmtPrinter, Printer};
3 use crate::ty::{self, Ty, TyCtxt, TypeFoldable, TypeSuperFoldable};
4 use crate::ty::{EarlyBinder, InternalSubsts, SubstsRef, TypeVisitableExt};
5 use rustc_errors::ErrorGuaranteed;
6 use rustc_hir::def::Namespace;
7 use rustc_hir::def_id::{CrateNum, DefId};
8 use rustc_hir::lang_items::LangItem;
9 use rustc_index::bit_set::FiniteBitSet;
10 use rustc_macros::HashStable;
11 use rustc_middle::ty::normalize_erasing_regions::NormalizationError;
12 use rustc_span::Symbol;
13 
14 use std::fmt;
15 
16 /// A monomorphized `InstanceDef`.
17 ///
18 /// Monomorphization happens on-the-fly and no monomorphized MIR is ever created. Instead, this type
19 /// simply couples a potentially generic `InstanceDef` with some substs, and codegen and const eval
20 /// will do all required substitution as they run.
21 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
22 #[derive(HashStable, Lift, TypeFoldable, TypeVisitable)]
23 pub struct Instance<'tcx> {
24     pub def: InstanceDef<'tcx>,
25     pub substs: SubstsRef<'tcx>,
26 }
27 
28 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
29 #[derive(TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable, Lift)]
30 pub enum InstanceDef<'tcx> {
31     /// A user-defined callable item.
32     ///
33     /// This includes:
34     /// - `fn` items
35     /// - closures
36     /// - generators
37     Item(DefId),
38 
39     /// An intrinsic `fn` item (with `"rust-intrinsic"` or `"platform-intrinsic"` ABI).
40     ///
41     /// Alongside `Virtual`, this is the only `InstanceDef` that does not have its own callable MIR.
42     /// Instead, codegen and const eval "magically" evaluate calls to intrinsics purely in the
43     /// caller.
44     Intrinsic(DefId),
45 
46     /// `<T as Trait>::method` where `method` receives unsizeable `self: Self` (part of the
47     /// `unsized_locals` feature).
48     ///
49     /// The generated shim will take `Self` via `*mut Self` - conceptually this is `&owned Self` -
50     /// and dereference the argument to call the original function.
51     VTableShim(DefId),
52 
53     /// `fn()` pointer where the function itself cannot be turned into a pointer.
54     ///
55     /// One example is `<dyn Trait as Trait>::fn`, where the shim contains
56     /// a virtual call, which codegen supports only via a direct call to the
57     /// `<dyn Trait as Trait>::fn` instance (an `InstanceDef::Virtual`).
58     ///
59     /// Another example is functions annotated with `#[track_caller]`, which
60     /// must have their implicit caller location argument populated for a call.
61     /// Because this is a required part of the function's ABI but can't be tracked
62     /// as a property of the function pointer, we use a single "caller location"
63     /// (the definition of the function itself).
64     ReifyShim(DefId),
65 
66     /// `<fn() as FnTrait>::call_*` (generated `FnTrait` implementation for `fn()` pointers).
67     ///
68     /// `DefId` is `FnTrait::call_*`.
69     FnPtrShim(DefId, Ty<'tcx>),
70 
71     /// Dynamic dispatch to `<dyn Trait as Trait>::fn`.
72     ///
73     /// This `InstanceDef` does not have callable MIR. Calls to `Virtual` instances must be
74     /// codegen'd as virtual calls through the vtable.
75     ///
76     /// If this is reified to a `fn` pointer, a `ReifyShim` is used (see `ReifyShim` above for more
77     /// details on that).
78     Virtual(DefId, usize),
79 
80     /// `<[FnMut closure] as FnOnce>::call_once`.
81     ///
82     /// The `DefId` is the ID of the `call_once` method in `FnOnce`.
83     ClosureOnceShim { call_once: DefId, track_caller: bool },
84 
85     /// Compiler-generated accessor for thread locals which returns a reference to the thread local
86     /// the `DefId` defines. This is used to export thread locals from dylibs on platforms lacking
87     /// native support.
88     ThreadLocalShim(DefId),
89 
90     /// `core::ptr::drop_in_place::<T>`.
91     ///
92     /// The `DefId` is for `core::ptr::drop_in_place`.
93     /// The `Option<Ty<'tcx>>` is either `Some(T)`, or `None` for empty drop
94     /// glue.
95     DropGlue(DefId, Option<Ty<'tcx>>),
96 
97     /// Compiler-generated `<T as Clone>::clone` implementation.
98     ///
99     /// For all types that automatically implement `Copy`, a trivial `Clone` impl is provided too.
100     /// Additionally, arrays, tuples, and closures get a `Clone` shim even if they aren't `Copy`.
101     ///
102     /// The `DefId` is for `Clone::clone`, the `Ty` is the type `T` with the builtin `Clone` impl.
103     CloneShim(DefId, Ty<'tcx>),
104 
105     /// Compiler-generated `<T as FnPtr>::addr` implementation.
106     ///
107     /// Automatically generated for all potentially higher-ranked `fn(I) -> R` types.
108     ///
109     /// The `DefId` is for `FnPtr::addr`, the `Ty` is the type `T`.
110     FnPtrAddrShim(DefId, Ty<'tcx>),
111 }
112 
113 impl<'tcx> Instance<'tcx> {
114     /// Returns the `Ty` corresponding to this `Instance`, with generic substitutions applied and
115     /// lifetimes erased, allowing a `ParamEnv` to be specified for use during normalization.
ty(&self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> Ty<'tcx>116     pub fn ty(&self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> Ty<'tcx> {
117         let ty = tcx.type_of(self.def.def_id());
118         tcx.subst_and_normalize_erasing_regions(self.substs, param_env, ty)
119     }
120 
121     /// Finds a crate that contains a monomorphization of this instance that
122     /// can be linked to from the local crate. A return value of `None` means
123     /// no upstream crate provides such an exported monomorphization.
124     ///
125     /// This method already takes into account the global `-Zshare-generics`
126     /// setting, always returning `None` if `share-generics` is off.
upstream_monomorphization(&self, tcx: TyCtxt<'tcx>) -> Option<CrateNum>127     pub fn upstream_monomorphization(&self, tcx: TyCtxt<'tcx>) -> Option<CrateNum> {
128         // If we are not in share generics mode, we don't link to upstream
129         // monomorphizations but always instantiate our own internal versions
130         // instead.
131         if !tcx.sess.opts.share_generics() {
132             return None;
133         }
134 
135         // If this is an item that is defined in the local crate, no upstream
136         // crate can know about it/provide a monomorphization.
137         if self.def_id().is_local() {
138             return None;
139         }
140 
141         // If this a non-generic instance, it cannot be a shared monomorphization.
142         self.substs.non_erasable_generics().next()?;
143 
144         match self.def {
145             InstanceDef::Item(def) => tcx
146                 .upstream_monomorphizations_for(def)
147                 .and_then(|monos| monos.get(&self.substs).cloned()),
148             InstanceDef::DropGlue(_, Some(_)) => tcx.upstream_drop_glue_for(self.substs),
149             _ => None,
150         }
151     }
152 }
153 
154 impl<'tcx> InstanceDef<'tcx> {
155     #[inline]
def_id(self) -> DefId156     pub fn def_id(self) -> DefId {
157         match self {
158             InstanceDef::Item(def_id)
159             | InstanceDef::VTableShim(def_id)
160             | InstanceDef::ReifyShim(def_id)
161             | InstanceDef::FnPtrShim(def_id, _)
162             | InstanceDef::Virtual(def_id, _)
163             | InstanceDef::Intrinsic(def_id)
164             | InstanceDef::ThreadLocalShim(def_id)
165             | InstanceDef::ClosureOnceShim { call_once: def_id, track_caller: _ }
166             | InstanceDef::DropGlue(def_id, _)
167             | InstanceDef::CloneShim(def_id, _)
168             | InstanceDef::FnPtrAddrShim(def_id, _) => def_id,
169         }
170     }
171 
172     /// Returns the `DefId` of instances which might not require codegen locally.
def_id_if_not_guaranteed_local_codegen(self) -> Option<DefId>173     pub fn def_id_if_not_guaranteed_local_codegen(self) -> Option<DefId> {
174         match self {
175             ty::InstanceDef::Item(def) => Some(def),
176             ty::InstanceDef::DropGlue(def_id, Some(_)) | InstanceDef::ThreadLocalShim(def_id) => {
177                 Some(def_id)
178             }
179             InstanceDef::VTableShim(..)
180             | InstanceDef::ReifyShim(..)
181             | InstanceDef::FnPtrShim(..)
182             | InstanceDef::Virtual(..)
183             | InstanceDef::Intrinsic(..)
184             | InstanceDef::ClosureOnceShim { .. }
185             | InstanceDef::DropGlue(..)
186             | InstanceDef::CloneShim(..)
187             | InstanceDef::FnPtrAddrShim(..) => None,
188         }
189     }
190 
191     #[inline]
get_attrs( &self, tcx: TyCtxt<'tcx>, attr: Symbol, ) -> impl Iterator<Item = &'tcx rustc_ast::Attribute>192     pub fn get_attrs(
193         &self,
194         tcx: TyCtxt<'tcx>,
195         attr: Symbol,
196     ) -> impl Iterator<Item = &'tcx rustc_ast::Attribute> {
197         tcx.get_attrs(self.def_id(), attr)
198     }
199 
200     /// Returns `true` if the LLVM version of this instance is unconditionally
201     /// marked with `inline`. This implies that a copy of this instance is
202     /// generated in every codegen unit.
203     /// Note that this is only a hint. See the documentation for
204     /// `generates_cgu_internal_copy` for more information.
requires_inline(&self, tcx: TyCtxt<'tcx>) -> bool205     pub fn requires_inline(&self, tcx: TyCtxt<'tcx>) -> bool {
206         use rustc_hir::definitions::DefPathData;
207         let def_id = match *self {
208             ty::InstanceDef::Item(def) => def,
209             ty::InstanceDef::DropGlue(_, Some(_)) => return false,
210             ty::InstanceDef::ThreadLocalShim(_) => return false,
211             _ => return true,
212         };
213         matches!(
214             tcx.def_key(def_id).disambiguated_data.data,
215             DefPathData::Ctor | DefPathData::ClosureExpr
216         )
217     }
218 
219     /// Returns `true` if the machine code for this instance is instantiated in
220     /// each codegen unit that references it.
221     /// Note that this is only a hint! The compiler can globally decide to *not*
222     /// do this in order to speed up compilation. CGU-internal copies are
223     /// only exist to enable inlining. If inlining is not performed (e.g. at
224     /// `-Copt-level=0`) then the time for generating them is wasted and it's
225     /// better to create a single copy with external linkage.
generates_cgu_internal_copy(&self, tcx: TyCtxt<'tcx>) -> bool226     pub fn generates_cgu_internal_copy(&self, tcx: TyCtxt<'tcx>) -> bool {
227         if self.requires_inline(tcx) {
228             return true;
229         }
230         if let ty::InstanceDef::DropGlue(.., Some(ty)) = *self {
231             // Drop glue generally wants to be instantiated at every codegen
232             // unit, but without an #[inline] hint. We should make this
233             // available to normal end-users.
234             if tcx.sess.opts.incremental.is_none() {
235                 return true;
236             }
237             // When compiling with incremental, we can generate a *lot* of
238             // codegen units. Including drop glue into all of them has a
239             // considerable compile time cost.
240             //
241             // We include enums without destructors to allow, say, optimizing
242             // drops of `Option::None` before LTO. We also respect the intent of
243             // `#[inline]` on `Drop::drop` implementations.
244             return ty.ty_adt_def().map_or(true, |adt_def| {
245                 adt_def.destructor(tcx).map_or_else(
246                     || adt_def.is_enum(),
247                     |dtor| tcx.codegen_fn_attrs(dtor.did).requests_inline(),
248                 )
249             });
250         }
251         if let ty::InstanceDef::ThreadLocalShim(..) = *self {
252             return false;
253         }
254         tcx.codegen_fn_attrs(self.def_id()).requests_inline()
255     }
256 
requires_caller_location(&self, tcx: TyCtxt<'_>) -> bool257     pub fn requires_caller_location(&self, tcx: TyCtxt<'_>) -> bool {
258         match *self {
259             InstanceDef::Item(def_id) | InstanceDef::Virtual(def_id, _) => {
260                 tcx.body_codegen_attrs(def_id).flags.contains(CodegenFnAttrFlags::TRACK_CALLER)
261             }
262             InstanceDef::ClosureOnceShim { call_once: _, track_caller } => track_caller,
263             _ => false,
264         }
265     }
266 
267     /// Returns `true` when the MIR body associated with this instance should be monomorphized
268     /// by its users (e.g. codegen or miri) by substituting the `substs` from `Instance` (see
269     /// `Instance::substs_for_mir_body`).
270     ///
271     /// Otherwise, returns `false` only for some kinds of shims where the construction of the MIR
272     /// body should perform necessary substitutions.
has_polymorphic_mir_body(&self) -> bool273     pub fn has_polymorphic_mir_body(&self) -> bool {
274         match *self {
275             InstanceDef::CloneShim(..)
276             | InstanceDef::ThreadLocalShim(..)
277             | InstanceDef::FnPtrAddrShim(..)
278             | InstanceDef::FnPtrShim(..)
279             | InstanceDef::DropGlue(_, Some(_)) => false,
280             InstanceDef::ClosureOnceShim { .. }
281             | InstanceDef::DropGlue(..)
282             | InstanceDef::Item(_)
283             | InstanceDef::Intrinsic(..)
284             | InstanceDef::ReifyShim(..)
285             | InstanceDef::Virtual(..)
286             | InstanceDef::VTableShim(..) => true,
287         }
288     }
289 }
290 
fmt_instance( f: &mut fmt::Formatter<'_>, instance: &Instance<'_>, type_length: rustc_session::Limit, ) -> fmt::Result291 fn fmt_instance(
292     f: &mut fmt::Formatter<'_>,
293     instance: &Instance<'_>,
294     type_length: rustc_session::Limit,
295 ) -> fmt::Result {
296     ty::tls::with(|tcx| {
297         let substs = tcx.lift(instance.substs).expect("could not lift for printing");
298 
299         let s = FmtPrinter::new_with_limit(tcx, Namespace::ValueNS, type_length)
300             .print_def_path(instance.def_id(), substs)?
301             .into_buffer();
302         f.write_str(&s)
303     })?;
304 
305     match instance.def {
306         InstanceDef::Item(_) => Ok(()),
307         InstanceDef::VTableShim(_) => write!(f, " - shim(vtable)"),
308         InstanceDef::ReifyShim(_) => write!(f, " - shim(reify)"),
309         InstanceDef::ThreadLocalShim(_) => write!(f, " - shim(tls)"),
310         InstanceDef::Intrinsic(_) => write!(f, " - intrinsic"),
311         InstanceDef::Virtual(_, num) => write!(f, " - virtual#{}", num),
312         InstanceDef::FnPtrShim(_, ty) => write!(f, " - shim({})", ty),
313         InstanceDef::ClosureOnceShim { .. } => write!(f, " - shim"),
314         InstanceDef::DropGlue(_, None) => write!(f, " - shim(None)"),
315         InstanceDef::DropGlue(_, Some(ty)) => write!(f, " - shim(Some({}))", ty),
316         InstanceDef::CloneShim(_, ty) => write!(f, " - shim({})", ty),
317         InstanceDef::FnPtrAddrShim(_, ty) => write!(f, " - shim({})", ty),
318     }
319 }
320 
321 pub struct ShortInstance<'a, 'tcx>(pub &'a Instance<'tcx>, pub usize);
322 
323 impl<'a, 'tcx> fmt::Display for ShortInstance<'a, 'tcx> {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result324     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
325         fmt_instance(f, self.0, rustc_session::Limit(self.1))
326     }
327 }
328 
329 impl<'tcx> fmt::Display for Instance<'tcx> {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result330     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
331         ty::tls::with(|tcx| fmt_instance(f, self, tcx.type_length_limit()))
332     }
333 }
334 
335 impl<'tcx> Instance<'tcx> {
new(def_id: DefId, substs: SubstsRef<'tcx>) -> Instance<'tcx>336     pub fn new(def_id: DefId, substs: SubstsRef<'tcx>) -> Instance<'tcx> {
337         assert!(
338             !substs.has_escaping_bound_vars(),
339             "substs of instance {:?} not normalized for codegen: {:?}",
340             def_id,
341             substs
342         );
343         Instance { def: InstanceDef::Item(def_id), substs }
344     }
345 
mono(tcx: TyCtxt<'tcx>, def_id: DefId) -> Instance<'tcx>346     pub fn mono(tcx: TyCtxt<'tcx>, def_id: DefId) -> Instance<'tcx> {
347         let substs = InternalSubsts::for_item(tcx, def_id, |param, _| match param.kind {
348             ty::GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
349             ty::GenericParamDefKind::Type { .. } => {
350                 bug!("Instance::mono: {:?} has type parameters", def_id)
351             }
352             ty::GenericParamDefKind::Const { .. } => {
353                 bug!("Instance::mono: {:?} has const parameters", def_id)
354             }
355         });
356 
357         Instance::new(def_id, substs)
358     }
359 
360     #[inline]
def_id(&self) -> DefId361     pub fn def_id(&self) -> DefId {
362         self.def.def_id()
363     }
364 
365     /// Resolves a `(def_id, substs)` pair to an (optional) instance -- most commonly,
366     /// this is used to find the precise code that will run for a trait method invocation,
367     /// if known.
368     ///
369     /// Returns `Ok(None)` if we cannot resolve `Instance` to a specific instance.
370     /// For example, in a context like this,
371     ///
372     /// ```ignore (illustrative)
373     /// fn foo<T: Debug>(t: T) { ... }
374     /// ```
375     ///
376     /// trying to resolve `Debug::fmt` applied to `T` will yield `Ok(None)`, because we do not
377     /// know what code ought to run. (Note that this setting is also affected by the
378     /// `RevealMode` in the parameter environment.)
379     ///
380     /// Presuming that coherence and type-check have succeeded, if this method is invoked
381     /// in a monomorphic context (i.e., like during codegen), then it is guaranteed to return
382     /// `Ok(Some(instance))`.
383     ///
384     /// Returns `Err(ErrorGuaranteed)` when the `Instance` resolution process
385     /// couldn't complete due to errors elsewhere - this is distinct
386     /// from `Ok(None)` to avoid misleading diagnostics when an error
387     /// has already been/will be emitted, for the original cause
388     #[instrument(level = "debug", skip(tcx), ret)]
resolve( tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, def_id: DefId, substs: SubstsRef<'tcx>, ) -> Result<Option<Instance<'tcx>>, ErrorGuaranteed>389     pub fn resolve(
390         tcx: TyCtxt<'tcx>,
391         param_env: ty::ParamEnv<'tcx>,
392         def_id: DefId,
393         substs: SubstsRef<'tcx>,
394     ) -> Result<Option<Instance<'tcx>>, ErrorGuaranteed> {
395         // All regions in the result of this query are erased, so it's
396         // fine to erase all of the input regions.
397 
398         // HACK(eddyb) erase regions in `substs` first, so that `param_env.and(...)`
399         // below is more likely to ignore the bounds in scope (e.g. if the only
400         // generic parameters mentioned by `substs` were lifetime ones).
401         let substs = tcx.erase_regions(substs);
402         tcx.resolve_instance(tcx.erase_regions(param_env.and((def_id, substs))))
403     }
404 
expect_resolve( tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, def_id: DefId, substs: SubstsRef<'tcx>, ) -> Instance<'tcx>405     pub fn expect_resolve(
406         tcx: TyCtxt<'tcx>,
407         param_env: ty::ParamEnv<'tcx>,
408         def_id: DefId,
409         substs: SubstsRef<'tcx>,
410     ) -> Instance<'tcx> {
411         match ty::Instance::resolve(tcx, param_env, def_id, substs) {
412             Ok(Some(instance)) => instance,
413             instance => bug!(
414                 "failed to resolve instance for {}: {instance:#?}",
415                 tcx.def_path_str_with_substs(def_id, substs)
416             ),
417         }
418     }
419 
resolve_for_fn_ptr( tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, def_id: DefId, substs: SubstsRef<'tcx>, ) -> Option<Instance<'tcx>>420     pub fn resolve_for_fn_ptr(
421         tcx: TyCtxt<'tcx>,
422         param_env: ty::ParamEnv<'tcx>,
423         def_id: DefId,
424         substs: SubstsRef<'tcx>,
425     ) -> Option<Instance<'tcx>> {
426         debug!("resolve(def_id={:?}, substs={:?})", def_id, substs);
427         // Use either `resolve_closure` or `resolve_for_vtable`
428         assert!(!tcx.is_closure(def_id), "Called `resolve_for_fn_ptr` on closure: {:?}", def_id);
429         Instance::resolve(tcx, param_env, def_id, substs).ok().flatten().map(|mut resolved| {
430             match resolved.def {
431                 InstanceDef::Item(def) if resolved.def.requires_caller_location(tcx) => {
432                     debug!(" => fn pointer created for function with #[track_caller]");
433                     resolved.def = InstanceDef::ReifyShim(def);
434                 }
435                 InstanceDef::Virtual(def_id, _) => {
436                     debug!(" => fn pointer created for virtual call");
437                     resolved.def = InstanceDef::ReifyShim(def_id);
438                 }
439                 _ => {}
440             }
441 
442             resolved
443         })
444     }
445 
resolve_for_vtable( tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, def_id: DefId, substs: SubstsRef<'tcx>, ) -> Option<Instance<'tcx>>446     pub fn resolve_for_vtable(
447         tcx: TyCtxt<'tcx>,
448         param_env: ty::ParamEnv<'tcx>,
449         def_id: DefId,
450         substs: SubstsRef<'tcx>,
451     ) -> Option<Instance<'tcx>> {
452         debug!("resolve_for_vtable(def_id={:?}, substs={:?})", def_id, substs);
453         let fn_sig = tcx.fn_sig(def_id).subst_identity();
454         let is_vtable_shim = !fn_sig.inputs().skip_binder().is_empty()
455             && fn_sig.input(0).skip_binder().is_param(0)
456             && tcx.generics_of(def_id).has_self;
457         if is_vtable_shim {
458             debug!(" => associated item with unsizeable self: Self");
459             Some(Instance { def: InstanceDef::VTableShim(def_id), substs })
460         } else {
461             Instance::resolve(tcx, param_env, def_id, substs).ok().flatten().map(|mut resolved| {
462                 match resolved.def {
463                     InstanceDef::Item(def) => {
464                         // We need to generate a shim when we cannot guarantee that
465                         // the caller of a trait object method will be aware of
466                         // `#[track_caller]` - this ensures that the caller
467                         // and callee ABI will always match.
468                         //
469                         // The shim is generated when all of these conditions are met:
470                         //
471                         // 1) The underlying method expects a caller location parameter
472                         // in the ABI
473                         if resolved.def.requires_caller_location(tcx)
474                             // 2) The caller location parameter comes from having `#[track_caller]`
475                             // on the implementation, and *not* on the trait method.
476                             && !tcx.should_inherit_track_caller(def)
477                             // If the method implementation comes from the trait definition itself
478                             // (e.g. `trait Foo { #[track_caller] my_fn() { /* impl */ } }`),
479                             // then we don't need to generate a shim. This check is needed because
480                             // `should_inherit_track_caller` returns `false` if our method
481                             // implementation comes from the trait block, and not an impl block
482                             && !matches!(
483                                 tcx.opt_associated_item(def),
484                                 Some(ty::AssocItem {
485                                     container: ty::AssocItemContainer::TraitContainer,
486                                     ..
487                                 })
488                             )
489                         {
490                             if tcx.is_closure(def) {
491                                 debug!(" => vtable fn pointer created for closure with #[track_caller]: {:?} for method {:?} {:?}",
492                                        def, def_id, substs);
493 
494                                 // Create a shim for the `FnOnce/FnMut/Fn` method we are calling
495                                 // - unlike functions, invoking a closure always goes through a
496                                 // trait.
497                                 resolved = Instance { def: InstanceDef::ReifyShim(def_id), substs };
498                             } else {
499                                 debug!(
500                                     " => vtable fn pointer created for function with #[track_caller]: {:?}", def
501                                 );
502                                 resolved.def = InstanceDef::ReifyShim(def);
503                             }
504                         }
505                     }
506                     InstanceDef::Virtual(def_id, _) => {
507                         debug!(" => vtable fn pointer created for virtual call");
508                         resolved.def = InstanceDef::ReifyShim(def_id);
509                     }
510                     _ => {}
511                 }
512 
513                 resolved
514             })
515         }
516     }
517 
resolve_closure( tcx: TyCtxt<'tcx>, def_id: DefId, substs: ty::SubstsRef<'tcx>, requested_kind: ty::ClosureKind, ) -> Option<Instance<'tcx>>518     pub fn resolve_closure(
519         tcx: TyCtxt<'tcx>,
520         def_id: DefId,
521         substs: ty::SubstsRef<'tcx>,
522         requested_kind: ty::ClosureKind,
523     ) -> Option<Instance<'tcx>> {
524         let actual_kind = substs.as_closure().kind();
525 
526         match needs_fn_once_adapter_shim(actual_kind, requested_kind) {
527             Ok(true) => Instance::fn_once_adapter_instance(tcx, def_id, substs),
528             _ => Some(Instance::new(def_id, substs)),
529         }
530     }
531 
resolve_drop_in_place(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> ty::Instance<'tcx>532     pub fn resolve_drop_in_place(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> ty::Instance<'tcx> {
533         let def_id = tcx.require_lang_item(LangItem::DropInPlace, None);
534         let substs = tcx.mk_substs(&[ty.into()]);
535         Instance::expect_resolve(tcx, ty::ParamEnv::reveal_all(), def_id, substs)
536     }
537 
538     #[instrument(level = "debug", skip(tcx), ret)]
fn_once_adapter_instance( tcx: TyCtxt<'tcx>, closure_did: DefId, substs: ty::SubstsRef<'tcx>, ) -> Option<Instance<'tcx>>539     pub fn fn_once_adapter_instance(
540         tcx: TyCtxt<'tcx>,
541         closure_did: DefId,
542         substs: ty::SubstsRef<'tcx>,
543     ) -> Option<Instance<'tcx>> {
544         let fn_once = tcx.require_lang_item(LangItem::FnOnce, None);
545         let call_once = tcx
546             .associated_items(fn_once)
547             .in_definition_order()
548             .find(|it| it.kind == ty::AssocKind::Fn)
549             .unwrap()
550             .def_id;
551         let track_caller =
552             tcx.codegen_fn_attrs(closure_did).flags.contains(CodegenFnAttrFlags::TRACK_CALLER);
553         let def = ty::InstanceDef::ClosureOnceShim { call_once, track_caller };
554 
555         let self_ty = Ty::new_closure(tcx, closure_did, substs);
556 
557         let sig = substs.as_closure().sig();
558         let sig =
559             tcx.try_normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), sig).ok()?;
560         assert_eq!(sig.inputs().len(), 1);
561         let substs = tcx.mk_substs_trait(self_ty, [sig.inputs()[0].into()]);
562 
563         debug!(?self_ty, ?sig);
564         Some(Instance { def, substs })
565     }
566 
567     /// Depending on the kind of `InstanceDef`, the MIR body associated with an
568     /// instance is expressed in terms of the generic parameters of `self.def_id()`, and in other
569     /// cases the MIR body is expressed in terms of the types found in the substitution array.
570     /// In the former case, we want to substitute those generic types and replace them with the
571     /// values from the substs when monomorphizing the function body. But in the latter case, we
572     /// don't want to do that substitution, since it has already been done effectively.
573     ///
574     /// This function returns `Some(substs)` in the former case and `None` otherwise -- i.e., if
575     /// this function returns `None`, then the MIR body does not require substitution during
576     /// codegen.
substs_for_mir_body(&self) -> Option<SubstsRef<'tcx>>577     fn substs_for_mir_body(&self) -> Option<SubstsRef<'tcx>> {
578         self.def.has_polymorphic_mir_body().then_some(self.substs)
579     }
580 
subst_mir<T>(&self, tcx: TyCtxt<'tcx>, v: EarlyBinder<&T>) -> T where T: TypeFoldable<TyCtxt<'tcx>> + Copy,581     pub fn subst_mir<T>(&self, tcx: TyCtxt<'tcx>, v: EarlyBinder<&T>) -> T
582     where
583         T: TypeFoldable<TyCtxt<'tcx>> + Copy,
584     {
585         let v = v.map_bound(|v| *v);
586         if let Some(substs) = self.substs_for_mir_body() {
587             v.subst(tcx, substs)
588         } else {
589             v.subst_identity()
590         }
591     }
592 
593     #[inline(always)]
subst_mir_and_normalize_erasing_regions<T>( &self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, v: EarlyBinder<T>, ) -> T where T: TypeFoldable<TyCtxt<'tcx>> + Clone,594     pub fn subst_mir_and_normalize_erasing_regions<T>(
595         &self,
596         tcx: TyCtxt<'tcx>,
597         param_env: ty::ParamEnv<'tcx>,
598         v: EarlyBinder<T>,
599     ) -> T
600     where
601         T: TypeFoldable<TyCtxt<'tcx>> + Clone,
602     {
603         if let Some(substs) = self.substs_for_mir_body() {
604             tcx.subst_and_normalize_erasing_regions(substs, param_env, v)
605         } else {
606             tcx.normalize_erasing_regions(param_env, v.skip_binder())
607         }
608     }
609 
610     #[inline(always)]
try_subst_mir_and_normalize_erasing_regions<T>( &self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, v: EarlyBinder<T>, ) -> Result<T, NormalizationError<'tcx>> where T: TypeFoldable<TyCtxt<'tcx>> + Clone,611     pub fn try_subst_mir_and_normalize_erasing_regions<T>(
612         &self,
613         tcx: TyCtxt<'tcx>,
614         param_env: ty::ParamEnv<'tcx>,
615         v: EarlyBinder<T>,
616     ) -> Result<T, NormalizationError<'tcx>>
617     where
618         T: TypeFoldable<TyCtxt<'tcx>> + Clone,
619     {
620         if let Some(substs) = self.substs_for_mir_body() {
621             tcx.try_subst_and_normalize_erasing_regions(substs, param_env, v)
622         } else {
623             tcx.try_normalize_erasing_regions(param_env, v.skip_binder())
624         }
625     }
626 
627     /// Returns a new `Instance` where generic parameters in `instance.substs` are replaced by
628     /// identity parameters if they are determined to be unused in `instance.def`.
polymorphize(self, tcx: TyCtxt<'tcx>) -> Self629     pub fn polymorphize(self, tcx: TyCtxt<'tcx>) -> Self {
630         debug!("polymorphize: running polymorphization analysis");
631         if !tcx.sess.opts.unstable_opts.polymorphize {
632             return self;
633         }
634 
635         let polymorphized_substs = polymorphize(tcx, self.def, self.substs);
636         debug!("polymorphize: self={:?} polymorphized_substs={:?}", self, polymorphized_substs);
637         Self { def: self.def, substs: polymorphized_substs }
638     }
639 }
640 
polymorphize<'tcx>( tcx: TyCtxt<'tcx>, instance: ty::InstanceDef<'tcx>, substs: SubstsRef<'tcx>, ) -> SubstsRef<'tcx>641 fn polymorphize<'tcx>(
642     tcx: TyCtxt<'tcx>,
643     instance: ty::InstanceDef<'tcx>,
644     substs: SubstsRef<'tcx>,
645 ) -> SubstsRef<'tcx> {
646     debug!("polymorphize({:?}, {:?})", instance, substs);
647     let unused = tcx.unused_generic_params(instance);
648     debug!("polymorphize: unused={:?}", unused);
649 
650     // If this is a closure or generator then we need to handle the case where another closure
651     // from the function is captured as an upvar and hasn't been polymorphized. In this case,
652     // the unpolymorphized upvar closure would result in a polymorphized closure producing
653     // multiple mono items (and eventually symbol clashes).
654     let def_id = instance.def_id();
655     let upvars_ty = if tcx.is_closure(def_id) {
656         Some(substs.as_closure().tupled_upvars_ty())
657     } else if tcx.type_of(def_id).skip_binder().is_generator() {
658         Some(substs.as_generator().tupled_upvars_ty())
659     } else {
660         None
661     };
662     let has_upvars = upvars_ty.is_some_and(|ty| !ty.tuple_fields().is_empty());
663     debug!("polymorphize: upvars_ty={:?} has_upvars={:?}", upvars_ty, has_upvars);
664 
665     struct PolymorphizationFolder<'tcx> {
666         tcx: TyCtxt<'tcx>,
667     }
668 
669     impl<'tcx> ty::TypeFolder<TyCtxt<'tcx>> for PolymorphizationFolder<'tcx> {
670         fn interner(&self) -> TyCtxt<'tcx> {
671             self.tcx
672         }
673 
674         fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
675             debug!("fold_ty: ty={:?}", ty);
676             match *ty.kind() {
677                 ty::Closure(def_id, substs) => {
678                     let polymorphized_substs =
679                         polymorphize(self.tcx, ty::InstanceDef::Item(def_id), substs);
680                     if substs == polymorphized_substs {
681                         ty
682                     } else {
683                         Ty::new_closure(self.tcx, def_id, polymorphized_substs)
684                     }
685                 }
686                 ty::Generator(def_id, substs, movability) => {
687                     let polymorphized_substs =
688                         polymorphize(self.tcx, ty::InstanceDef::Item(def_id), substs);
689                     if substs == polymorphized_substs {
690                         ty
691                     } else {
692                         Ty::new_generator(self.tcx, def_id, polymorphized_substs, movability)
693                     }
694                 }
695                 _ => ty.super_fold_with(self),
696             }
697         }
698     }
699 
700     InternalSubsts::for_item(tcx, def_id, |param, _| {
701         let is_unused = unused.is_unused(param.index);
702         debug!("polymorphize: param={:?} is_unused={:?}", param, is_unused);
703         match param.kind {
704             // Upvar case: If parameter is a type parameter..
705             ty::GenericParamDefKind::Type { .. } if
706                 // ..and has upvars..
707                 has_upvars &&
708                 // ..and this param has the same type as the tupled upvars..
709                 upvars_ty == Some(substs[param.index as usize].expect_ty()) => {
710                     // ..then double-check that polymorphization marked it used..
711                     debug_assert!(!is_unused);
712                     // ..and polymorphize any closures/generators captured as upvars.
713                     let upvars_ty = upvars_ty.unwrap();
714                     let polymorphized_upvars_ty = upvars_ty.fold_with(
715                         &mut PolymorphizationFolder { tcx });
716                     debug!("polymorphize: polymorphized_upvars_ty={:?}", polymorphized_upvars_ty);
717                     ty::GenericArg::from(polymorphized_upvars_ty)
718                 },
719 
720             // Simple case: If parameter is a const or type parameter..
721             ty::GenericParamDefKind::Const { .. } | ty::GenericParamDefKind::Type { .. } if
722                 // ..and is within range and unused..
723                 unused.is_unused(param.index) =>
724                     // ..then use the identity for this parameter.
725                     tcx.mk_param_from_def(param),
726 
727             // Otherwise, use the parameter as before.
728             _ => substs[param.index as usize],
729         }
730     })
731 }
732 
needs_fn_once_adapter_shim( actual_closure_kind: ty::ClosureKind, trait_closure_kind: ty::ClosureKind, ) -> Result<bool, ()>733 fn needs_fn_once_adapter_shim(
734     actual_closure_kind: ty::ClosureKind,
735     trait_closure_kind: ty::ClosureKind,
736 ) -> Result<bool, ()> {
737     match (actual_closure_kind, trait_closure_kind) {
738         (ty::ClosureKind::Fn, ty::ClosureKind::Fn)
739         | (ty::ClosureKind::FnMut, ty::ClosureKind::FnMut)
740         | (ty::ClosureKind::FnOnce, ty::ClosureKind::FnOnce) => {
741             // No adapter needed.
742             Ok(false)
743         }
744         (ty::ClosureKind::Fn, ty::ClosureKind::FnMut) => {
745             // The closure fn `llfn` is a `fn(&self, ...)`. We want a
746             // `fn(&mut self, ...)`. In fact, at codegen time, these are
747             // basically the same thing, so we can just return llfn.
748             Ok(false)
749         }
750         (ty::ClosureKind::Fn | ty::ClosureKind::FnMut, ty::ClosureKind::FnOnce) => {
751             // The closure fn `llfn` is a `fn(&self, ...)` or `fn(&mut
752             // self, ...)`. We want a `fn(self, ...)`. We can produce
753             // this by doing something like:
754             //
755             //     fn call_once(self, ...) { call_mut(&self, ...) }
756             //     fn call_once(mut self, ...) { call_mut(&mut self, ...) }
757             //
758             // These are both the same at codegen time.
759             Ok(true)
760         }
761         (ty::ClosureKind::FnMut | ty::ClosureKind::FnOnce, _) => Err(()),
762     }
763 }
764 
765 // Set bits represent unused generic parameters.
766 // An empty set indicates that all parameters are used.
767 #[derive(Debug, Copy, Clone, Eq, PartialEq, Decodable, Encodable, HashStable)]
768 pub struct UnusedGenericParams(FiniteBitSet<u32>);
769 
770 impl Default for UnusedGenericParams {
default() -> Self771     fn default() -> Self {
772         UnusedGenericParams::new_all_used()
773     }
774 }
775 
776 impl UnusedGenericParams {
new_all_unused(amount: u32) -> Self777     pub fn new_all_unused(amount: u32) -> Self {
778         let mut bitset = FiniteBitSet::new_empty();
779         bitset.set_range(0..amount);
780         Self(bitset)
781     }
782 
new_all_used() -> Self783     pub fn new_all_used() -> Self {
784         Self(FiniteBitSet::new_empty())
785     }
786 
mark_used(&mut self, idx: u32)787     pub fn mark_used(&mut self, idx: u32) {
788         self.0.clear(idx);
789     }
790 
is_unused(&self, idx: u32) -> bool791     pub fn is_unused(&self, idx: u32) -> bool {
792         self.0.contains(idx).unwrap_or(false)
793     }
794 
is_used(&self, idx: u32) -> bool795     pub fn is_used(&self, idx: u32) -> bool {
796         !self.is_unused(idx)
797     }
798 
all_used(&self) -> bool799     pub fn all_used(&self) -> bool {
800         self.0.is_empty()
801     }
802 
bits(&self) -> u32803     pub fn bits(&self) -> u32 {
804         self.0.0
805     }
806 
from_bits(bits: u32) -> UnusedGenericParams807     pub fn from_bits(bits: u32) -> UnusedGenericParams {
808         UnusedGenericParams(FiniteBitSet(bits))
809     }
810 }
811