]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/instance.rs
Rollup merge of #60315 - pietroalbini:fix-tools-version, r=Mark-Simulacrum
[rust.git] / src / librustc / ty / instance.rs
1 use crate::hir::Unsafety;
2 use crate::hir::def::Namespace;
3 use crate::hir::def_id::DefId;
4 use crate::ty::{self, Ty, PolyFnSig, TypeFoldable, SubstsRef, TyCtxt};
5 use crate::ty::print::{FmtPrinter, Printer};
6 use crate::traits;
7 use rustc_target::spec::abi::Abi;
8 use rustc_macros::HashStable;
9
10 use std::fmt;
11 use std::iter;
12
13 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable, HashStable)]
14 pub struct Instance<'tcx> {
15     pub def: InstanceDef<'tcx>,
16     pub substs: SubstsRef<'tcx>,
17 }
18
19 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable, HashStable)]
20 pub enum InstanceDef<'tcx> {
21     Item(DefId),
22     Intrinsic(DefId),
23
24     /// `<T as Trait>::method` where `method` receives unsizeable `self: Self`.
25     VtableShim(DefId),
26
27     /// `<fn() as FnTrait>::call_*`
28     /// `DefId` is `FnTrait::call_*`
29     FnPtrShim(DefId, Ty<'tcx>),
30
31     /// `<Trait as Trait>::fn`
32     Virtual(DefId, usize),
33
34     /// `<[mut closure] as FnOnce>::call_once`
35     ClosureOnceShim { call_once: DefId },
36
37     /// `drop_in_place::<T>; None` for empty drop glue.
38     DropGlue(DefId, Option<Ty<'tcx>>),
39
40     ///`<T as Clone>::clone` shim.
41     CloneShim(DefId, Ty<'tcx>),
42 }
43
44 impl<'a, 'tcx> Instance<'tcx> {
45     pub fn ty(&self,
46               tcx: TyCtxt<'a, 'tcx, 'tcx>)
47               -> Ty<'tcx>
48     {
49         let ty = tcx.type_of(self.def.def_id());
50         tcx.subst_and_normalize_erasing_regions(
51             self.substs,
52             ty::ParamEnv::reveal_all(),
53             &ty,
54         )
55     }
56
57     fn fn_sig_noadjust(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> PolyFnSig<'tcx> {
58         let ty = self.ty(tcx);
59         match ty.sty {
60             ty::FnDef(..) |
61             // Shims currently have type FnPtr. Not sure this should remain.
62             ty::FnPtr(_) => ty.fn_sig(tcx),
63             ty::Closure(def_id, substs) => {
64                 let sig = substs.closure_sig(def_id, tcx);
65
66                 let env_ty = tcx.closure_env_ty(def_id, substs).unwrap();
67                 sig.map_bound(|sig| tcx.mk_fn_sig(
68                     iter::once(*env_ty.skip_binder()).chain(sig.inputs().iter().cloned()),
69                     sig.output(),
70                     sig.c_variadic,
71                     sig.unsafety,
72                     sig.abi
73                 ))
74             }
75             ty::Generator(def_id, substs, _) => {
76                 let sig = substs.poly_sig(def_id, tcx);
77
78                 let env_region = ty::ReLateBound(ty::INNERMOST, ty::BrEnv);
79                 let env_ty = tcx.mk_mut_ref(tcx.mk_region(env_region), ty);
80
81                 let pin_did = tcx.lang_items().pin_type().unwrap();
82                 let pin_adt_ref = tcx.adt_def(pin_did);
83                 let pin_substs = tcx.intern_substs(&[env_ty.into()]);
84                 let env_ty = tcx.mk_adt(pin_adt_ref, pin_substs);
85
86                 sig.map_bound(|sig| {
87                     let state_did = tcx.lang_items().gen_state().unwrap();
88                     let state_adt_ref = tcx.adt_def(state_did);
89                     let state_substs = tcx.intern_substs(&[
90                         sig.yield_ty.into(),
91                         sig.return_ty.into(),
92                     ]);
93                     let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
94
95                     tcx.mk_fn_sig(iter::once(env_ty),
96                         ret_ty,
97                         false,
98                         Unsafety::Normal,
99                         Abi::Rust
100                     )
101                 })
102             }
103             _ => bug!("unexpected type {:?} in Instance::fn_sig_noadjust", ty)
104         }
105     }
106
107     pub fn fn_sig(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> ty::PolyFnSig<'tcx> {
108         let mut fn_sig = self.fn_sig_noadjust(tcx);
109         if let InstanceDef::VtableShim(..) = self.def {
110             // Modify fn(self, ...) to fn(self: *mut Self, ...)
111             fn_sig = fn_sig.map_bound(|mut fn_sig| {
112                 let mut inputs_and_output = fn_sig.inputs_and_output.to_vec();
113                 inputs_and_output[0] = tcx.mk_mut_ptr(inputs_and_output[0]);
114                 fn_sig.inputs_and_output = tcx.intern_type_list(&inputs_and_output);
115                 fn_sig
116             });
117         }
118         fn_sig
119     }
120 }
121
122 impl<'tcx> InstanceDef<'tcx> {
123     #[inline]
124     pub fn def_id(&self) -> DefId {
125         match *self {
126             InstanceDef::Item(def_id) |
127             InstanceDef::VtableShim(def_id) |
128             InstanceDef::FnPtrShim(def_id, _) |
129             InstanceDef::Virtual(def_id, _) |
130             InstanceDef::Intrinsic(def_id, ) |
131             InstanceDef::ClosureOnceShim { call_once: def_id } |
132             InstanceDef::DropGlue(def_id, _) |
133             InstanceDef::CloneShim(def_id, _) => def_id
134         }
135     }
136
137     #[inline]
138     pub fn attrs<'a>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> ty::Attributes<'tcx> {
139         tcx.get_attrs(self.def_id())
140     }
141
142     pub fn is_inline<'a>(
143         &self,
144         tcx: TyCtxt<'a, 'tcx, 'tcx>
145     ) -> bool {
146         use crate::hir::map::DefPathData;
147         let def_id = match *self {
148             ty::InstanceDef::Item(def_id) => def_id,
149             ty::InstanceDef::DropGlue(_, Some(_)) => return false,
150             _ => return true
151         };
152         match tcx.def_key(def_id).disambiguated_data.data {
153             DefPathData::Ctor | DefPathData::ClosureExpr => true,
154             _ => false
155         }
156     }
157
158     pub fn requires_local<'a>(
159         &self,
160         tcx: TyCtxt<'a, 'tcx, 'tcx>
161     ) -> bool {
162         if self.is_inline(tcx) {
163             return true
164         }
165         if let ty::InstanceDef::DropGlue(..) = *self {
166             // Drop glue wants to be instantiated at every codegen
167             // unit, but without an #[inline] hint. We should make this
168             // available to normal end-users.
169             return true
170         }
171         tcx.codegen_fn_attrs(self.def_id()).requests_inline()
172     }
173 }
174
175 impl<'tcx> fmt::Display for Instance<'tcx> {
176     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177         ty::tls::with(|tcx| {
178             let substs = tcx.lift(&self.substs).expect("could not lift for printing");
179             FmtPrinter::new(tcx, &mut *f, Namespace::ValueNS)
180                 .print_def_path(self.def_id(), substs)?;
181             Ok(())
182         })?;
183
184         match self.def {
185             InstanceDef::Item(_) => Ok(()),
186             InstanceDef::VtableShim(_) => {
187                 write!(f, " - shim(vtable)")
188             }
189             InstanceDef::Intrinsic(_) => {
190                 write!(f, " - intrinsic")
191             }
192             InstanceDef::Virtual(_, num) => {
193                 write!(f, " - shim(#{})", num)
194             }
195             InstanceDef::FnPtrShim(_, ty) => {
196                 write!(f, " - shim({:?})", ty)
197             }
198             InstanceDef::ClosureOnceShim { .. } => {
199                 write!(f, " - shim")
200             }
201             InstanceDef::DropGlue(_, ty) => {
202                 write!(f, " - shim({:?})", ty)
203             }
204             InstanceDef::CloneShim(_, ty) => {
205                 write!(f, " - shim({:?})", ty)
206             }
207         }
208     }
209 }
210
211 impl<'a, 'b, 'tcx> Instance<'tcx> {
212     pub fn new(def_id: DefId, substs: SubstsRef<'tcx>)
213                -> Instance<'tcx> {
214         assert!(!substs.has_escaping_bound_vars(),
215                 "substs of instance {:?} not normalized for codegen: {:?}",
216                 def_id, substs);
217         Instance { def: InstanceDef::Item(def_id), substs: substs }
218     }
219
220     pub fn mono(tcx: TyCtxt<'a, 'tcx, 'b>, def_id: DefId) -> Instance<'tcx> {
221         Instance::new(def_id, tcx.global_tcx().empty_substs_for_def_id(def_id))
222     }
223
224     #[inline]
225     pub fn def_id(&self) -> DefId {
226         self.def.def_id()
227     }
228
229     /// Resolves a `(def_id, substs)` pair to an (optional) instance -- most commonly,
230     /// this is used to find the precise code that will run for a trait method invocation,
231     /// if known.
232     ///
233     /// Returns `None` if we cannot resolve `Instance` to a specific instance.
234     /// For example, in a context like this,
235     ///
236     /// ```
237     /// fn foo<T: Debug>(t: T) { ... }
238     /// ```
239     ///
240     /// trying to resolve `Debug::fmt` applied to `T` will yield `None`, because we do not
241     /// know what code ought to run. (Note that this setting is also affected by the
242     /// `RevealMode` in the parameter environment.)
243     ///
244     /// Presuming that coherence and type-check have succeeded, if this method is invoked
245     /// in a monomorphic context (i.e., like during codegen), then it is guaranteed to return
246     /// `Some`.
247     pub fn resolve(tcx: TyCtxt<'a, 'tcx, 'tcx>,
248                    param_env: ty::ParamEnv<'tcx>,
249                    def_id: DefId,
250                    substs: SubstsRef<'tcx>) -> Option<Instance<'tcx>> {
251         debug!("resolve(def_id={:?}, substs={:?})", def_id, substs);
252         let result = if let Some(trait_def_id) = tcx.trait_of_item(def_id) {
253             debug!(" => associated item, attempting to find impl in param_env {:#?}", param_env);
254             let item = tcx.associated_item(def_id);
255             resolve_associated_item(tcx, &item, param_env, trait_def_id, substs)
256         } else {
257             let ty = tcx.type_of(def_id);
258             let item_type = tcx.subst_and_normalize_erasing_regions(
259                 substs,
260                 param_env,
261                 &ty,
262             );
263
264             let def = match item_type.sty {
265                 ty::FnDef(..) if {
266                     let f = item_type.fn_sig(tcx);
267                     f.abi() == Abi::RustIntrinsic ||
268                         f.abi() == Abi::PlatformIntrinsic
269                 } =>
270                 {
271                     debug!(" => intrinsic");
272                     ty::InstanceDef::Intrinsic(def_id)
273                 }
274                 _ => {
275                     if Some(def_id) == tcx.lang_items().drop_in_place_fn() {
276                         let ty = substs.type_at(0);
277                         if ty.needs_drop(tcx, ty::ParamEnv::reveal_all()) {
278                             debug!(" => nontrivial drop glue");
279                             ty::InstanceDef::DropGlue(def_id, Some(ty))
280                         } else {
281                             debug!(" => trivial drop glue");
282                             ty::InstanceDef::DropGlue(def_id, None)
283                         }
284                     } else {
285                         debug!(" => free item");
286                         ty::InstanceDef::Item(def_id)
287                     }
288                 }
289             };
290             Some(Instance {
291                 def: def,
292                 substs: substs
293             })
294         };
295         debug!("resolve(def_id={:?}, substs={:?}) = {:?}", def_id, substs, result);
296         result
297     }
298
299     pub fn resolve_for_vtable(tcx: TyCtxt<'a, 'tcx, 'tcx>,
300                               param_env: ty::ParamEnv<'tcx>,
301                               def_id: DefId,
302                               substs: SubstsRef<'tcx>) -> Option<Instance<'tcx>> {
303         debug!("resolve(def_id={:?}, substs={:?})", def_id, substs);
304         let fn_sig = tcx.fn_sig(def_id);
305         let is_vtable_shim =
306             fn_sig.inputs().skip_binder().len() > 0 && fn_sig.input(0).skip_binder().is_self();
307         if is_vtable_shim {
308             debug!(" => associated item with unsizeable self: Self");
309             Some(Instance {
310                 def: InstanceDef::VtableShim(def_id),
311                 substs,
312             })
313         } else {
314             Instance::resolve(tcx, param_env, def_id, substs)
315         }
316     }
317
318     pub fn resolve_closure(
319         tcx: TyCtxt<'a, 'tcx, 'tcx>,
320         def_id: DefId,
321         substs: ty::ClosureSubsts<'tcx>,
322         requested_kind: ty::ClosureKind)
323         -> Instance<'tcx>
324     {
325         let actual_kind = substs.closure_kind(def_id, tcx);
326
327         match needs_fn_once_adapter_shim(actual_kind, requested_kind) {
328             Ok(true) => fn_once_adapter_instance(tcx, def_id, substs),
329             _ => Instance::new(def_id, substs.substs)
330         }
331     }
332
333     pub fn is_vtable_shim(&self) -> bool {
334         if let InstanceDef::VtableShim(..) = self.def {
335             true
336         } else {
337             false
338         }
339     }
340 }
341
342 fn resolve_associated_item<'a, 'tcx>(
343     tcx: TyCtxt<'a, 'tcx, 'tcx>,
344     trait_item: &ty::AssociatedItem,
345     param_env: ty::ParamEnv<'tcx>,
346     trait_id: DefId,
347     rcvr_substs: SubstsRef<'tcx>,
348 ) -> Option<Instance<'tcx>> {
349     let def_id = trait_item.def_id;
350     debug!("resolve_associated_item(trait_item={:?}, \
351             param_env={:?}, \
352             trait_id={:?}, \
353             rcvr_substs={:?})",
354             def_id, param_env, trait_id, rcvr_substs);
355
356     let trait_ref = ty::TraitRef::from_method(tcx, trait_id, rcvr_substs);
357     let vtbl = tcx.codegen_fulfill_obligation((param_env, ty::Binder::bind(trait_ref)));
358
359     // Now that we know which impl is being used, we can dispatch to
360     // the actual function:
361     match vtbl {
362         traits::VtableImpl(impl_data) => {
363             let (def_id, substs) = traits::find_associated_item(
364                 tcx, param_env, trait_item, rcvr_substs, &impl_data);
365             let substs = tcx.erase_regions(&substs);
366             Some(ty::Instance::new(def_id, substs))
367         }
368         traits::VtableGenerator(generator_data) => {
369             Some(Instance {
370                 def: ty::InstanceDef::Item(generator_data.generator_def_id),
371                 substs: generator_data.substs.substs
372             })
373         }
374         traits::VtableClosure(closure_data) => {
375             let trait_closure_kind = tcx.lang_items().fn_trait_kind(trait_id).unwrap();
376             Some(Instance::resolve_closure(tcx, closure_data.closure_def_id, closure_data.substs,
377                                            trait_closure_kind))
378         }
379         traits::VtableFnPointer(ref data) => {
380             Some(Instance {
381                 def: ty::InstanceDef::FnPtrShim(trait_item.def_id, data.fn_ty),
382                 substs: rcvr_substs
383             })
384         }
385         traits::VtableObject(ref data) => {
386             let index = tcx.get_vtable_index_of_object_method(data, def_id);
387             Some(Instance {
388                 def: ty::InstanceDef::Virtual(def_id, index),
389                 substs: rcvr_substs
390             })
391         }
392         traits::VtableBuiltin(..) => {
393             if tcx.lang_items().clone_trait().is_some() {
394                 Some(Instance {
395                     def: ty::InstanceDef::CloneShim(def_id, trait_ref.self_ty()),
396                     substs: rcvr_substs
397                 })
398             } else {
399                 None
400             }
401         }
402         traits::VtableAutoImpl(..) |
403         traits::VtableParam(..) |
404         traits::VtableTraitAlias(..) => None
405     }
406 }
407
408 fn needs_fn_once_adapter_shim<'a, 'tcx>(actual_closure_kind: ty::ClosureKind,
409                                         trait_closure_kind: ty::ClosureKind)
410     -> Result<bool, ()>
411 {
412     match (actual_closure_kind, trait_closure_kind) {
413         (ty::ClosureKind::Fn, ty::ClosureKind::Fn) |
414             (ty::ClosureKind::FnMut, ty::ClosureKind::FnMut) |
415             (ty::ClosureKind::FnOnce, ty::ClosureKind::FnOnce) => {
416                 // No adapter needed.
417                 Ok(false)
418             }
419         (ty::ClosureKind::Fn, ty::ClosureKind::FnMut) => {
420             // The closure fn `llfn` is a `fn(&self, ...)`.  We want a
421             // `fn(&mut self, ...)`. In fact, at codegen time, these are
422             // basically the same thing, so we can just return llfn.
423             Ok(false)
424         }
425         (ty::ClosureKind::Fn, ty::ClosureKind::FnOnce) |
426             (ty::ClosureKind::FnMut, ty::ClosureKind::FnOnce) => {
427                 // The closure fn `llfn` is a `fn(&self, ...)` or `fn(&mut
428                 // self, ...)`.  We want a `fn(self, ...)`. We can produce
429                 // this by doing something like:
430                 //
431                 //     fn call_once(self, ...) { call_mut(&self, ...) }
432                 //     fn call_once(mut self, ...) { call_mut(&mut self, ...) }
433                 //
434                 // These are both the same at codegen time.
435                 Ok(true)
436         }
437         (ty::ClosureKind::FnMut, _) |
438         (ty::ClosureKind::FnOnce, _) => Err(())
439     }
440 }
441
442 fn fn_once_adapter_instance<'a, 'tcx>(
443     tcx: TyCtxt<'a, 'tcx, 'tcx>,
444     closure_did: DefId,
445     substs: ty::ClosureSubsts<'tcx>)
446     -> Instance<'tcx>
447 {
448     debug!("fn_once_adapter_shim({:?}, {:?})",
449            closure_did,
450            substs);
451     let fn_once = tcx.lang_items().fn_once_trait().unwrap();
452     let call_once = tcx.associated_items(fn_once)
453         .find(|it| it.kind == ty::AssociatedKind::Method)
454         .unwrap().def_id;
455     let def = ty::InstanceDef::ClosureOnceShim { call_once };
456
457     let self_ty = tcx.mk_closure(closure_did, substs);
458
459     let sig = substs.closure_sig(closure_did, tcx);
460     let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
461     assert_eq!(sig.inputs().len(), 1);
462     let substs = tcx.mk_substs_trait(self_ty, &[sig.inputs()[0].into()]);
463
464     debug!("fn_once_adapter_shim: self_ty={:?} sig={:?}", self_ty, sig);
465     Instance { def, substs }
466 }