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