1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use arena
::TypedArena
;
14 use llvm
::{ValueRef, get_params}
;
15 use metadata
::csearch
;
16 use middle
::subst
::{Subst, Substs}
;
17 use middle
::subst
::VecPerParamSpace
;
30 use trans
::debuginfo
::DebugLoc
;
32 use trans
::expr
::SaveIn
;
36 use trans
::monomorphize
;
37 use trans
::type_
::Type
;
38 use trans
::type_of
::*;
39 use middle
::ty
::{self, Ty, HasTypeFlags}
;
40 use middle
::ty
::MethodCall
;
42 use syntax
::{ast, attr, visit}
;
43 use syntax
::codemap
::DUMMY_SP
;
46 // drop_glue pointer, size, align.
47 const VTABLE_OFFSET
: usize = 3;
49 /// The main "translation" pass for methods. Generates code
50 /// for non-monomorphized methods only. Other methods will
51 /// be generated once they are invoked with specific type parameters,
52 /// see `trans::base::lval_static_fn()` or `trans::base::monomorphic_fn()`.
53 pub fn trans_impl(ccx
: &CrateContext
,
55 impl_items
: &[P
<ast
::ImplItem
>],
56 generics
: &ast
::Generics
,
58 let _icx
= push_ctxt("meth::trans_impl");
61 debug
!("trans_impl(name={}, id={})", name
, id
);
63 let mut v
= TransItemVisitor { ccx: ccx }
;
65 // Both here and below with generic methods, be sure to recurse and look for
66 // items that we need to translate.
67 if !generics
.ty_params
.is_empty() {
68 for impl_item
in impl_items
{
69 match impl_item
.node
{
70 ast
::MethodImplItem(..) => {
71 visit
::walk_impl_item(&mut v
, impl_item
);
78 for impl_item
in impl_items
{
79 match impl_item
.node
{
80 ast
::MethodImplItem(ref sig
, ref body
) => {
81 if sig
.generics
.ty_params
.is_empty() {
82 let trans_everywhere
= attr
::requests_inline(&impl_item
.attrs
);
83 for (ref ccx
, is_origin
) in ccx
.maybe_iter(trans_everywhere
) {
84 let llfn
= get_item_val(ccx
, impl_item
.id
);
85 let empty_substs
= tcx
.mk_substs(Substs
::trans_empty());
86 trans_fn(ccx
, &sig
.decl
, body
, llfn
,
87 empty_substs
, impl_item
.id
, &[]);
91 if is_origin { OriginalTranslation }
else { InlinedCopy }
);
94 visit
::walk_impl_item(&mut v
, impl_item
);
101 pub fn trans_method_callee
<'blk
, 'tcx
>(bcx
: Block
<'blk
, 'tcx
>,
102 method_call
: MethodCall
,
103 self_expr
: Option
<&ast
::Expr
>,
104 arg_cleanup_scope
: cleanup
::ScopeId
)
105 -> Callee
<'blk
, 'tcx
> {
106 let _icx
= push_ctxt("meth::trans_method_callee");
108 let method
= bcx
.tcx().tables
.borrow().method_map
[&method_call
];
110 match bcx
.tcx().impl_or_trait_item(method
.def_id
).container() {
111 ty
::ImplContainer(_
) => {
112 debug
!("trans_method_callee: static, {:?}", method
.def_id
);
113 let datum
= callee
::trans_fn_ref(bcx
.ccx(),
115 MethodCallKey(method_call
),
116 bcx
.fcx
.param_substs
);
124 ty
::TraitContainer(trait_def_id
) => {
125 let trait_substs
= method
.substs
.clone().method_to_trait();
126 let trait_substs
= bcx
.tcx().mk_substs(trait_substs
);
127 let trait_ref
= ty
::TraitRef
::new(trait_def_id
, trait_substs
);
129 let trait_ref
= ty
::Binder(bcx
.monomorphize(&trait_ref
));
130 let span
= bcx
.tcx().map
.span(method_call
.expr_id
);
131 debug
!("method_call={:?} trait_ref={:?} trait_ref id={:?} substs={:?}",
136 let origin
= fulfill_obligation(bcx
.ccx(),
139 debug
!("origin = {:?}", origin
);
140 trans_monomorphized_callee(bcx
,
152 pub fn trans_static_method_callee
<'a
, 'tcx
>(ccx
: &CrateContext
<'a
, 'tcx
>,
153 method_id
: ast
::DefId
,
154 trait_id
: ast
::DefId
,
155 expr_id
: ast
::NodeId
,
156 param_substs
: &'tcx subst
::Substs
<'tcx
>)
157 -> Datum
<'tcx
, Rvalue
>
159 let _icx
= push_ctxt("meth::trans_static_method_callee");
162 debug
!("trans_static_method_callee(method_id={:?}, trait_id={}, \
165 tcx
.item_path_str(trait_id
),
168 let mname
= if method_id
.krate
== ast
::LOCAL_CRATE
{
169 match tcx
.map
.get(method_id
.node
) {
170 ast_map
::NodeTraitItem(trait_item
) => trait_item
.ident
.name
,
171 _
=> panic
!("callee is not a trait method")
174 csearch
::get_item_path(tcx
, method_id
).last().unwrap().name()
176 debug
!("trans_static_method_callee: method_id={:?}, expr_id={}, \
177 name={}", method_id
, expr_id
, mname
);
179 // Find the substitutions for the fn itself. This includes
180 // type parameters that belong to the trait but also some that
181 // belong to the method:
182 let rcvr_substs
= node_id_substs(ccx
, ExprId(expr_id
), param_substs
);
183 let subst
::SeparateVecsPerParamSpace
{
187 } = rcvr_substs
.types
.split();
189 // Lookup the precise impl being called. To do that, we need to
190 // create a trait reference identifying the self type and other
191 // input type parameters. To create that trait reference, we have
192 // to pick apart the type parameters to identify just those that
193 // pertain to the trait. This is easiest to explain by example:
196 // fn from<U:Foo>(n: U) -> Option<Self>;
199 // let f = <Vec<int> as Convert>::from::<String>(...)
201 // Here, in this call, which I've written with explicit UFCS
202 // notation, the set of type parameters will be:
204 // rcvr_type: [] <-- nothing declared on the trait itself
205 // rcvr_self: [Vec<int>] <-- the self type
206 // rcvr_method: [String] <-- method type parameter
208 // So we create a trait reference using the first two,
209 // basically corresponding to `<Vec<int> as Convert>`.
210 // The remaining type parameters (`rcvr_method`) will be used below.
212 Substs
::erased(VecPerParamSpace
::new(rcvr_type
,
215 let trait_substs
= tcx
.mk_substs(trait_substs
);
216 debug
!("trait_substs={:?}", trait_substs
);
217 let trait_ref
= ty
::Binder(ty
::TraitRef
::new(trait_id
, trait_substs
));
218 let vtbl
= fulfill_obligation(ccx
,
222 // Now that we know which impl is being used, we can dispatch to
223 // the actual function:
225 traits
::VtableImpl(traits
::VtableImplData
{
226 impl_def_id
: impl_did
,
230 assert
!(!impl_substs
.types
.needs_infer());
232 // Create the substitutions that are in scope. This combines
233 // the type parameters from the impl with those declared earlier.
234 // To see what I mean, consider a possible impl:
236 // impl<T> Convert for Vec<T> {
237 // fn from<U:Foo>(n: U) { ... }
240 // Recall that we matched `<Vec<int> as Convert>`. Trait
241 // resolution will have given us a substitution
242 // containing `impl_substs=[[T=int],[],[]]` (the type
243 // parameters defined on the impl). We combine
244 // that with the `rcvr_method` from before, which tells us
245 // the type parameters from the *method*, to yield
246 // `callee_substs=[[T=int],[],[U=String]]`.
247 let subst
::SeparateVecsPerParamSpace
{
251 } = impl_substs
.types
.split();
253 Substs
::erased(VecPerParamSpace
::new(impl_type
,
257 let mth_id
= method_with_name(ccx
, impl_did
, mname
);
258 trans_fn_ref_with_substs(ccx
, mth_id
, ExprId(expr_id
),
262 traits
::VtableObject(ref data
) => {
263 let idx
= traits
::get_vtable_index_of_object_method(tcx
, data
, method_id
);
264 trans_object_shim(ccx
,
265 data
.upcast_trait_ref
.clone(),
270 tcx
.sess
.bug(&format
!("static call to invalid vtable: {:?}",
276 fn method_with_name(ccx
: &CrateContext
, impl_id
: ast
::DefId
, name
: ast
::Name
)
278 match ccx
.impl_method_cache().borrow().get(&(impl_id
, name
)).cloned() {
283 let impl_items
= ccx
.tcx().impl_items
.borrow();
285 impl_items
.get(&impl_id
)
286 .expect("could not find impl while translating");
287 let meth_did
= impl_items
.iter()
289 ccx
.tcx().impl_or_trait_item(did
.def_id()).name() == name
290 }).expect("could not find method while \
293 ccx
.impl_method_cache().borrow_mut().insert((impl_id
, name
),
298 fn trans_monomorphized_callee
<'blk
, 'tcx
>(bcx
: Block
<'blk
, 'tcx
>,
299 method_call
: MethodCall
,
300 self_expr
: Option
<&ast
::Expr
>,
301 trait_id
: ast
::DefId
,
302 method_id
: ast
::DefId
,
304 vtable
: traits
::Vtable
<'tcx
, ()>,
305 arg_cleanup_scope
: cleanup
::ScopeId
)
306 -> Callee
<'blk
, 'tcx
> {
307 let _icx
= push_ctxt("meth::trans_monomorphized_callee");
309 traits
::VtableImpl(vtable_impl
) => {
311 let impl_did
= vtable_impl
.impl_def_id
;
312 let mname
= match ccx
.tcx().impl_or_trait_item(method_id
) {
313 ty
::MethodTraitItem(method
) => method
.name
,
315 bcx
.tcx().sess
.bug("can't monomorphize a non-method trait \
319 let mth_id
= method_with_name(bcx
.ccx(), impl_did
, mname
);
321 // create a concatenated set of substitutions which includes
322 // those from the impl and those from the method:
324 combine_impl_and_methods_tps(
325 bcx
, MethodCallKey(method_call
), vtable_impl
.substs
);
327 // translate the function
328 let datum
= trans_fn_ref_with_substs(bcx
.ccx(),
330 MethodCallKey(method_call
),
331 bcx
.fcx
.param_substs
,
334 Callee { bcx: bcx, data: Fn(datum.val), ty: datum.ty }
336 traits
::VtableClosure(vtable_closure
) => {
337 // The substitutions should have no type parameters remaining
338 // after passing through fulfill_obligation
339 let trait_closure_kind
= bcx
.tcx().lang_items
.fn_trait_kind(trait_id
).unwrap();
340 let llfn
= closure
::trans_closure_method(bcx
.ccx(),
341 vtable_closure
.closure_def_id
,
342 vtable_closure
.substs
,
347 ty
: monomorphize_type(bcx
, method_ty
)
350 traits
::VtableFnPointer(fn_ty
) => {
351 let trait_closure_kind
= bcx
.tcx().lang_items
.fn_trait_kind(trait_id
).unwrap();
352 let llfn
= trans_fn_pointer_shim(bcx
.ccx(), trait_closure_kind
, fn_ty
);
356 ty
: monomorphize_type(bcx
, method_ty
)
359 traits
::VtableObject(ref data
) => {
360 let idx
= traits
::get_vtable_index_of_object_method(bcx
.tcx(), data
, method_id
);
361 if let Some(self_expr
) = self_expr
{
362 if let ty
::TyBareFn(_
, ref fty
) = monomorphize_type(bcx
, method_ty
).sty
{
363 let ty
= bcx
.tcx().mk_fn(None
, opaque_method_ty(bcx
.tcx(), fty
));
364 return trans_trait_callee(bcx
, ty
, idx
, self_expr
, arg_cleanup_scope
);
367 let datum
= trans_object_shim(bcx
.ccx(),
368 data
.upcast_trait_ref
.clone(),
371 Callee { bcx: bcx, data: Fn(datum.val), ty: datum.ty }
373 traits
::VtableBuiltin(..) |
374 traits
::VtableDefaultImpl(..) |
375 traits
::VtableParam(..) => {
377 &format
!("resolved vtable bad vtable {:?} in trans",
383 /// Creates a concatenated set of substitutions which includes those from the impl and those from
384 /// the method. This are some subtle complications here. Statically, we have a list of type
385 /// parameters like `[T0, T1, T2, M1, M2, M3]` where `Tn` are type parameters that appear on the
386 /// receiver. For example, if the receiver is a method parameter `A` with a bound like
387 /// `trait<B,C,D>` then `Tn` would be `[B,C,D]`.
389 /// The weird part is that the type `A` might now be bound to any other type, such as `foo<X>`.
390 /// In that case, the vector we want is: `[X, M1, M2, M3]`. Therefore, what we do now is to slice
391 /// off the method type parameters and append them to the type parameters from the type that the
392 /// receiver is mapped to.
393 fn combine_impl_and_methods_tps
<'blk
, 'tcx
>(bcx
: Block
<'blk
, 'tcx
>,
394 node
: ExprOrMethodCall
,
395 rcvr_substs
: subst
::Substs
<'tcx
>)
396 -> subst
::Substs
<'tcx
>
400 let node_substs
= node_id_substs(ccx
, node
, bcx
.fcx
.param_substs
);
402 debug
!("rcvr_substs={:?}", rcvr_substs
);
403 debug
!("node_substs={:?}", node_substs
);
405 // Break apart the type parameters from the node and type
406 // parameters from the receiver.
407 let node_method
= node_substs
.types
.split().fns
;
408 let subst
::SeparateVecsPerParamSpace
{
412 } = rcvr_substs
.types
.clone().split();
413 assert
!(rcvr_method
.is_empty());
415 regions
: subst
::ErasedRegions
,
416 types
: subst
::VecPerParamSpace
::new(rcvr_type
, rcvr_self
, node_method
)
420 /// Create a method callee where the method is coming from a trait object (e.g., Box<Trait> type).
421 /// In this case, we must pull the fn pointer out of the vtable that is packaged up with the
422 /// object. Objects are represented as a pair, so we first evaluate the self expression and then
423 /// extract the self data and vtable out of the pair.
424 fn trans_trait_callee
<'blk
, 'tcx
>(bcx
: Block
<'blk
, 'tcx
>,
425 opaque_fn_ty
: Ty
<'tcx
>,
427 self_expr
: &ast
::Expr
,
428 arg_cleanup_scope
: cleanup
::ScopeId
)
429 -> Callee
<'blk
, 'tcx
> {
430 let _icx
= push_ctxt("meth::trans_trait_callee");
433 // Translate self_datum and take ownership of the value by
434 // converting to an rvalue.
435 let self_datum
= unpack_datum
!(
436 bcx
, expr
::trans(bcx
, self_expr
));
438 let llval
= if bcx
.fcx
.type_needs_drop(self_datum
.ty
) {
439 let self_datum
= unpack_datum
!(
440 bcx
, self_datum
.to_rvalue_datum(bcx
, "trait_callee"));
442 // Convert to by-ref since `trans_trait_callee_from_llval` wants it
444 let self_datum
= unpack_datum
!(
445 bcx
, self_datum
.to_ref_datum(bcx
));
447 // Arrange cleanup in case something should go wrong before the
448 // actual call occurs.
449 self_datum
.add_clean(bcx
.fcx
, arg_cleanup_scope
)
451 // We don't have to do anything about cleanups for &Trait and &mut Trait.
452 assert
!(self_datum
.kind
.is_by_ref());
456 let llself
= Load(bcx
, GEPi(bcx
, llval
, &[0, abi
::FAT_PTR_ADDR
]));
457 let llvtable
= Load(bcx
, GEPi(bcx
, llval
, &[0, abi
::FAT_PTR_EXTRA
]));
458 trans_trait_callee_from_llval(bcx
, opaque_fn_ty
, vtable_index
, llself
, llvtable
)
461 /// Same as `trans_trait_callee()` above, except that it is given a by-ref pointer to the object
463 fn trans_trait_callee_from_llval
<'blk
, 'tcx
>(bcx
: Block
<'blk
, 'tcx
>,
464 opaque_fn_ty
: Ty
<'tcx
>,
468 -> Callee
<'blk
, 'tcx
> {
469 let _icx
= push_ctxt("meth::trans_trait_callee");
472 // Load the data pointer from the object.
473 debug
!("trans_trait_callee_from_llval(callee_ty={}, vtable_index={}, llself={}, llvtable={})",
476 bcx
.val_to_string(llself
),
477 bcx
.val_to_string(llvtable
));
479 // Replace the self type (&Self or Box<Self>) with an opaque pointer.
480 let mptr
= Load(bcx
, GEPi(bcx
, llvtable
, &[vtable_index
+ VTABLE_OFFSET
]));
481 let llcallee_ty
= type_of_fn_from_ty(ccx
, opaque_fn_ty
);
485 data
: TraitItem(MethodData
{
486 llfn
: PointerCast(bcx
, mptr
, llcallee_ty
.ptr_to()),
487 llself
: PointerCast(bcx
, llself
, Type
::i8p(ccx
)),
493 /// Generate a shim function that allows an object type like `SomeTrait` to
494 /// implement the type `SomeTrait`. Imagine a trait definition:
496 /// trait SomeTrait { fn get(&self) -> int; ... }
498 /// And a generic bit of code:
500 /// fn foo<T:SomeTrait>(t: &T) {
501 /// let x = SomeTrait::get;
505 /// What is the value of `x` when `foo` is invoked with `T=SomeTrait`?
506 /// The answer is that it it is a shim function generate by this
509 /// fn shim(t: &SomeTrait) -> int {
510 /// // ... call t.get() virtually ...
513 /// In fact, all virtual calls can be thought of as normal trait calls
514 /// that go through this shim function.
515 fn trans_object_shim
<'a
, 'tcx
>(
516 ccx
: &'a CrateContext
<'a
, 'tcx
>,
517 upcast_trait_ref
: ty
::PolyTraitRef
<'tcx
>,
518 method_id
: ast
::DefId
,
520 -> Datum
<'tcx
, Rvalue
>
522 let _icx
= push_ctxt("trans_object_shim");
525 debug
!("trans_object_shim(upcast_trait_ref={:?}, method_id={:?})",
529 // Upcast to the trait in question and extract out the substitutions.
530 let upcast_trait_ref
= tcx
.erase_late_bound_regions(&upcast_trait_ref
);
531 let object_substs
= upcast_trait_ref
.substs
.clone().erase_regions();
532 debug
!("trans_object_shim: object_substs={:?}", object_substs
);
534 // Lookup the type of this method as declared in the trait and apply substitutions.
535 let method_ty
= match tcx
.impl_or_trait_item(method_id
) {
536 ty
::MethodTraitItem(method
) => method
,
538 tcx
.sess
.bug("can't create a method shim for a non-method item")
541 let fty
= monomorphize
::apply_param_substs(tcx
, &object_substs
, &method_ty
.fty
);
542 let fty
= tcx
.mk_bare_fn(fty
);
543 let method_ty
= opaque_method_ty(tcx
, fty
);
544 debug
!("trans_object_shim: fty={:?} method_ty={:?}", fty
, method_ty
);
547 let shim_fn_ty
= tcx
.mk_fn(None
, fty
);
548 let method_bare_fn_ty
= tcx
.mk_fn(None
, method_ty
);
549 let function_name
= link
::mangle_internal_name_by_type_and_seq(ccx
, shim_fn_ty
, "object_shim");
550 let llfn
= declare
::define_internal_rust_fn(ccx
, &function_name
, shim_fn_ty
);
552 let sig
= ccx
.tcx().erase_late_bound_regions(&fty
.sig
);
554 let empty_substs
= tcx
.mk_substs(Substs
::trans_empty());
555 let (block_arena
, fcx
): (TypedArena
<_
>, FunctionContext
);
556 block_arena
= TypedArena
::new();
557 fcx
= new_fn_ctxt(ccx
,
565 let mut bcx
= init_function(&fcx
, false, sig
.output
);
567 let llargs
= get_params(fcx
.llfn
);
569 let self_idx
= fcx
.arg_offset();
570 let llself
= llargs
[self_idx
];
571 let llvtable
= llargs
[self_idx
+ 1];
573 debug
!("trans_object_shim: llself={}, llvtable={}",
574 bcx
.val_to_string(llself
), bcx
.val_to_string(llvtable
));
576 assert
!(!fcx
.needs_ret_allocas
);
579 fcx
.llretslotptr
.get().map(
580 |_
| expr
::SaveIn(fcx
.get_ret_slot(bcx
, sig
.output
, "ret_slot")));
582 debug
!("trans_object_shim: method_offset_in_vtable={}",
585 bcx
= trans_call_inner(bcx
,
587 |bcx
, _
| trans_trait_callee_from_llval(bcx
,
591 ArgVals(&llargs
[(self_idx
+ 2)..]),
594 finish_fn(&fcx
, bcx
, sig
.output
, DebugLoc
::None
);
596 immediate_rvalue(llfn
, shim_fn_ty
)
599 /// Creates a returns a dynamic vtable for the given type and vtable origin.
600 /// This is used only for objects.
602 /// The `trait_ref` encodes the erased self type. Hence if we are
603 /// making an object `Foo<Trait>` from a value of type `Foo<T>`, then
604 /// `trait_ref` would map `T:Trait`.
605 pub fn get_vtable
<'a
, 'tcx
>(ccx
: &CrateContext
<'a
, 'tcx
>,
606 trait_ref
: ty
::PolyTraitRef
<'tcx
>,
607 param_substs
: &'tcx subst
::Substs
<'tcx
>)
611 let _icx
= push_ctxt("meth::get_vtable");
613 debug
!("get_vtable(trait_ref={:?})", trait_ref
);
616 match ccx
.vtables().borrow().get(&trait_ref
) {
617 Some(&val
) => { return val }
621 // Not in the cache. Build it.
622 let methods
= traits
::supertraits(tcx
, trait_ref
.clone()).flat_map(|trait_ref
| {
623 let vtable
= fulfill_obligation(ccx
, DUMMY_SP
, trait_ref
.clone());
625 // Should default trait error here?
626 traits
::VtableDefaultImpl(_
) |
627 traits
::VtableBuiltin(_
) => {
628 Vec
::new().into_iter()
631 traits
::VtableImplData
{
635 emit_vtable_methods(ccx
, id
, substs
, param_substs
).into_iter()
637 traits
::VtableClosure(
638 traits
::VtableClosureData
{
642 let trait_closure_kind
= tcx
.lang_items
.fn_trait_kind(trait_ref
.def_id()).unwrap();
643 let llfn
= closure
::trans_closure_method(ccx
,
647 vec
![llfn
].into_iter()
649 traits
::VtableFnPointer(bare_fn_ty
) => {
650 let trait_closure_kind
= tcx
.lang_items
.fn_trait_kind(trait_ref
.def_id()).unwrap();
651 vec
![trans_fn_pointer_shim(ccx
, trait_closure_kind
, bare_fn_ty
)].into_iter()
653 traits
::VtableObject(ref data
) => {
654 // this would imply that the Self type being erased is
655 // an object type; this cannot happen because we
656 // cannot cast an unsized type into a trait object
658 &format
!("cannot get vtable for an object type: {:?}",
661 traits
::VtableParam(..) => {
663 &format
!("resolved vtable for {:?} to bad vtable {:?} in trans",
670 let size_ty
= sizing_type_of(ccx
, trait_ref
.self_ty());
671 let size
= machine
::llsize_of_alloc(ccx
, size_ty
);
672 let align
= align_of(ccx
, trait_ref
.self_ty());
674 let components
: Vec
<_
> = vec
![
675 // Generate a destructor for the vtable.
676 glue
::get_drop_glue(ccx
, trait_ref
.self_ty()),
679 ].into_iter().chain(methods
).collect();
681 let vtable
= consts
::addr_of(ccx
, C_struct(ccx
, &components
, false), "vtable");
683 ccx
.vtables().borrow_mut().insert(trait_ref
, vtable
);
687 fn emit_vtable_methods
<'a
, 'tcx
>(ccx
: &CrateContext
<'a
, 'tcx
>,
689 substs
: subst
::Substs
<'tcx
>,
690 param_substs
: &'tcx subst
::Substs
<'tcx
>)
695 debug
!("emit_vtable_methods(impl_id={:?}, substs={:?}, param_substs={:?})",
700 let trt_id
= match tcx
.impl_trait_ref(impl_id
) {
701 Some(t_id
) => t_id
.def_id
,
702 None
=> ccx
.sess().bug("make_impl_vtable: don't know how to \
703 make a vtable for a type impl!")
706 tcx
.populate_implementations_for_trait_if_necessary(trt_id
);
708 let nullptr
= C_null(Type
::nil(ccx
).ptr_to());
709 let trait_item_def_ids
= tcx
.trait_item_def_ids(trt_id
);
713 // Filter out non-method items.
714 .filter_map(|item_def_id
| {
716 ty
::MethodTraitItemId(def_id
) => Some(def_id
),
721 // Now produce pointers for each remaining method. If the
722 // method could never be called from this object, just supply
724 .map(|trait_method_def_id
| {
725 debug
!("emit_vtable_methods: trait_method_def_id={:?}",
726 trait_method_def_id
);
728 let trait_method_type
= match tcx
.impl_or_trait_item(trait_method_def_id
) {
729 ty
::MethodTraitItem(m
) => m
,
730 _
=> ccx
.sess().bug("should be a method, not other assoc item"),
732 let name
= trait_method_type
.name
;
734 // Some methods cannot be called on an object; skip those.
735 if !traits
::is_vtable_safe_method(tcx
, trt_id
, &trait_method_type
) {
736 debug
!("emit_vtable_methods: not vtable safe");
740 debug
!("emit_vtable_methods: trait_method_type={:?}",
743 // The substitutions we have are on the impl, so we grab
744 // the method type from the impl to substitute into.
745 let impl_method_def_id
= method_with_name(ccx
, impl_id
, name
);
746 let impl_method_type
= match tcx
.impl_or_trait_item(impl_method_def_id
) {
747 ty
::MethodTraitItem(m
) => m
,
748 _
=> ccx
.sess().bug("should be a method, not other assoc item"),
751 debug
!("emit_vtable_methods: impl_method_type={:?}",
754 // If this is a default method, it's possible that it
755 // relies on where clauses that do not hold for this
756 // particular set of type parameters. Note that this
757 // method could then never be called, so we do not want to
758 // try and trans it, in that case. Issue #23435.
759 if tcx
.provided_source(impl_method_def_id
).is_some() {
760 let predicates
= impl_method_type
.predicates
.predicates
.subst(tcx
, &substs
);
761 if !normalize_and_test_predicates(ccx
, predicates
.into_vec()) {
762 debug
!("emit_vtable_methods: predicates do not hold");
767 trans_fn_ref_with_substs(ccx
,
776 /// Replace the self type (&Self or Box<Self>) with an opaque pointer.
777 fn opaque_method_ty
<'tcx
>(tcx
: &ty
::ctxt
<'tcx
>, method_ty
: &ty
::BareFnTy
<'tcx
>)
778 -> &'tcx ty
::BareFnTy
<'tcx
> {
779 let mut inputs
= method_ty
.sig
.0.inputs
.clone();
780 inputs
[0] = tcx
.mk_mut_ptr(tcx
.mk_mach_int(ast
::TyI8
));
782 tcx
.mk_bare_fn(ty
::BareFnTy
{
783 unsafety
: method_ty
.unsafety
,
785 sig
: ty
::Binder(ty
::FnSig
{
787 output
: method_ty
.sig
.0.output
,
788 variadic
: method_ty
.sig
.0.variadic
,