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::{self, ValueRef, get_param};
15 use metadata::csearch;
16 use middle::subst::{Subst, Substs};
17 use middle::subst::VecPerParamSpace;
27 use trans::expr::{SaveIn, Ignore};
31 use trans::type_::Type;
32 use trans::type_of::*;
33 use middle::ty::{self, Ty};
34 use middle::ty::MethodCall;
35 use util::ppaux::Repr;
37 use std::ffi::CString;
39 use syntax::abi::{Rust, RustCall};
40 use syntax::parse::token;
41 use syntax::{ast, ast_map, attr, visit};
42 use syntax::ast_util::PostExpansionMethod;
43 use syntax::codemap::DUMMY_SP;
45 // drop_glue pointer, size, align.
46 static VTABLE_OFFSET: uint = 3;
48 /// The main "translation" pass for methods. Generates code
49 /// for non-monomorphized methods only. Other methods will
50 /// be generated once they are invoked with specific type parameters,
51 /// see `trans::base::lval_static_fn()` or `trans::base::monomorphic_fn()`.
52 pub fn trans_impl(ccx: &CrateContext,
54 impl_items: &[ast::ImplItem],
55 generics: &ast::Generics,
57 let _icx = push_ctxt("meth::trans_impl");
60 debug!("trans_impl(name={}, id={})", name.repr(tcx), id);
62 // Both here and below with generic methods, be sure to recurse and look for
63 // items that we need to translate.
64 if !generics.ty_params.is_empty() {
65 let mut v = TransItemVisitor{ ccx: ccx };
66 for impl_item in impl_items.iter() {
68 ast::MethodImplItem(ref method) => {
69 visit::walk_method_helper(&mut v, &**method);
71 ast::TypeImplItem(_) => {}
76 for impl_item in impl_items.iter() {
78 ast::MethodImplItem(ref method) => {
79 if method.pe_generics().ty_params.len() == 0u {
80 let trans_everywhere = attr::requests_inline(&method.attrs[]);
81 for (ref ccx, is_origin) in ccx.maybe_iter(trans_everywhere) {
82 let llfn = get_item_val(ccx, method.id);
87 &Substs::trans_empty(),
93 if is_origin { OriginalTranslation } else { InlinedCopy });
96 let mut v = TransItemVisitor {
99 visit::walk_method_helper(&mut v, &**method);
101 ast::TypeImplItem(_) => {}
106 pub fn trans_method_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
107 method_call: MethodCall,
108 self_expr: Option<&ast::Expr>,
109 arg_cleanup_scope: cleanup::ScopeId)
110 -> Callee<'blk, 'tcx> {
111 let _icx = push_ctxt("meth::trans_method_callee");
113 let (origin, method_ty) =
117 .map(|method| (method.origin.clone(), method.ty))
121 ty::MethodStatic(did) |
122 ty::MethodStaticUnboxedClosure(did) => {
125 data: Fn(callee::trans_fn_ref(bcx.ccx(),
127 MethodCallKey(method_call),
128 bcx.fcx.param_substs).val),
132 ty::MethodTypeParam(ty::MethodParam {
136 let trait_ref = ty::Binder(bcx.monomorphize(trait_ref));
137 let span = bcx.tcx().map.span(method_call.expr_id);
138 debug!("method_call={:?} trait_ref={}",
140 trait_ref.repr(bcx.tcx()));
141 let origin = fulfill_obligation(bcx.ccx(),
144 debug!("origin = {}", origin.repr(bcx.tcx()));
145 trans_monomorphized_callee(bcx,
152 ty::MethodTraitObject(ref mt) => {
153 let self_expr = match self_expr {
154 Some(self_expr) => self_expr,
156 bcx.sess().span_bug(bcx.tcx().map.span(method_call.expr_id),
157 "self expr wasn't provided for trait object \
158 callee (trying to call overloaded op?)")
161 trans_trait_callee(bcx,
162 monomorphize_type(bcx, method_ty),
170 pub fn trans_static_method_callee<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
171 method_id: ast::DefId,
172 trait_id: ast::DefId,
173 expr_id: ast::NodeId,
174 param_substs: &subst::Substs<'tcx>)
175 -> Datum<'tcx, Rvalue>
177 let _icx = push_ctxt("meth::trans_static_method_callee");
180 debug!("trans_static_method_callee(method_id={:?}, trait_id={}, \
183 ty::item_path_str(tcx, trait_id),
186 let mname = if method_id.krate == ast::LOCAL_CRATE {
187 match tcx.map.get(method_id.node) {
188 ast_map::NodeTraitItem(method) => {
189 let ident = match *method {
190 ast::RequiredMethod(ref m) => m.ident,
191 ast::ProvidedMethod(ref m) => m.pe_ident(),
192 ast::TypeTraitItem(_) => {
193 tcx.sess.bug("trans_static_method_callee() on \
194 an associated type?!")
199 _ => panic!("callee is not a trait method")
202 csearch::get_item_path(tcx, method_id).last().unwrap().name()
204 debug!("trans_static_method_callee: method_id={:?}, expr_id={}, \
205 name={}", method_id, expr_id, token::get_name(mname));
207 // Find the substitutions for the fn itself. This includes
208 // type parameters that belong to the trait but also some that
209 // belong to the method:
210 let rcvr_substs = node_id_substs(ccx, ExprId(expr_id), param_substs);
211 let subst::SeparateVecsPerParamSpace {
215 } = rcvr_substs.types.split();
217 // Lookup the precise impl being called. To do that, we need to
218 // create a trait reference identifying the self type and other
219 // input type parameters. To create that trait reference, we have
220 // to pick apart the type parameters to identify just those that
221 // pertain to the trait. This is easiest to explain by example:
224 // fn from<U:Foo>(n: U) -> Option<Self>;
227 // let f = <Vec<int> as Convert>::from::<String>(...)
229 // Here, in this call, which I've written with explicit UFCS
230 // notation, the set of type parameters will be:
232 // rcvr_type: [] <-- nothing declared on the trait itself
233 // rcvr_self: [Vec<int>] <-- the self type
234 // rcvr_method: [String] <-- method type parameter
236 // So we create a trait reference using the first two,
237 // basically corresponding to `<Vec<int> as Convert>`.
238 // The remaining type parameters (`rcvr_method`) will be used below.
240 Substs::erased(VecPerParamSpace::new(rcvr_type,
243 let trait_substs = tcx.mk_substs(trait_substs);
244 debug!("trait_substs={}", trait_substs.repr(tcx));
245 let trait_ref = ty::Binder(Rc::new(ty::TraitRef { def_id: trait_id,
246 substs: trait_substs }));
247 let vtbl = fulfill_obligation(ccx,
251 // Now that we know which impl is being used, we can dispatch to
252 // the actual function:
254 traits::VtableImpl(traits::VtableImplData {
255 impl_def_id: impl_did,
259 assert!(impl_substs.types.all(|t| !ty::type_needs_infer(*t)));
261 // Create the substitutions that are in scope. This combines
262 // the type parameters from the impl with those declared earlier.
263 // To see what I mean, consider a possible impl:
265 // impl<T> Convert for Vec<T> {
266 // fn from<U:Foo>(n: U) { ... }
269 // Recall that we matched `<Vec<int> as Convert>`. Trait
270 // resolution will have given us a substitution
271 // containing `impl_substs=[[T=int],[],[]]` (the type
272 // parameters defined on the impl). We combine
273 // that with the `rcvr_method` from before, which tells us
274 // the type parameters from the *method*, to yield
275 // `callee_substs=[[T=int],[],[U=String]]`.
276 let subst::SeparateVecsPerParamSpace {
280 } = impl_substs.types.split();
282 Substs::erased(VecPerParamSpace::new(impl_type,
286 let mth_id = method_with_name(ccx, impl_did, mname);
287 trans_fn_ref_with_substs(ccx, mth_id, ExprId(expr_id),
291 traits::VtableObject(ref data) => {
292 let trait_item_def_ids =
293 ty::trait_item_def_ids(ccx.tcx(), trait_id);
294 let method_offset_in_trait =
295 trait_item_def_ids.iter()
296 .position(|item| item.def_id() == method_id)
299 trans_object_shim(ccx, data.object_ty, trait_id, method_offset_in_trait);
300 immediate_rvalue(llfn, ty)
303 tcx.sess.bug(&format!("static call to invalid vtable: {}",
309 fn method_with_name(ccx: &CrateContext, impl_id: ast::DefId, name: ast::Name)
311 match ccx.impl_method_cache().borrow().get(&(impl_id, name)).cloned() {
316 let impl_items = ccx.tcx().impl_items.borrow();
318 impl_items.get(&impl_id)
319 .expect("could not find impl while translating");
320 let meth_did = impl_items.iter()
322 ty::impl_or_trait_item(ccx.tcx(), did.def_id()).name() == name
323 }).expect("could not find method while \
326 ccx.impl_method_cache().borrow_mut().insert((impl_id, name),
331 fn trans_monomorphized_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
332 method_call: MethodCall,
333 trait_id: ast::DefId,
335 vtable: traits::Vtable<'tcx, ()>)
336 -> Callee<'blk, 'tcx> {
337 let _icx = push_ctxt("meth::trans_monomorphized_callee");
339 traits::VtableImpl(vtable_impl) => {
341 let impl_did = vtable_impl.impl_def_id;
342 let mname = match ty::trait_item(ccx.tcx(), trait_id, n_method) {
343 ty::MethodTraitItem(method) => method.name,
344 ty::TypeTraitItem(_) => {
345 bcx.tcx().sess.bug("can't monomorphize an associated \
349 let mth_id = method_with_name(bcx.ccx(), impl_did, mname);
351 // create a concatenated set of substitutions which includes
352 // those from the impl and those from the method:
354 combine_impl_and_methods_tps(
355 bcx, MethodCallKey(method_call), vtable_impl.substs);
357 // translate the function
358 let llfn = trans_fn_ref_with_substs(bcx.ccx(),
360 MethodCallKey(method_call),
361 bcx.fcx.param_substs,
364 Callee { bcx: bcx, data: Fn(llfn) }
366 traits::VtableUnboxedClosure(closure_def_id, substs) => {
367 // The substitutions should have no type parameters remaining
368 // after passing through fulfill_obligation
369 let llfn = trans_fn_ref_with_substs(bcx.ccx(),
371 MethodCallKey(method_call),
372 bcx.fcx.param_substs,
380 traits::VtableFnPointer(fn_ty) => {
381 let llfn = trans_fn_pointer_shim(bcx.ccx(), fn_ty);
382 Callee { bcx: bcx, data: Fn(llfn) }
384 traits::VtableObject(ref data) => {
385 let (llfn, _) = trans_object_shim(bcx.ccx(), data.object_ty, trait_id, n_method);
386 Callee { bcx: bcx, data: Fn(llfn) }
388 traits::VtableBuiltin(..) |
389 traits::VtableParam(..) => {
391 &format!("resolved vtable bad vtable {} in trans",
392 vtable.repr(bcx.tcx()))[]);
397 /// Creates a concatenated set of substitutions which includes those from the impl and those from
398 /// the method. This are some subtle complications here. Statically, we have a list of type
399 /// parameters like `[T0, T1, T2, M1, M2, M3]` where `Tn` are type parameters that appear on the
400 /// receiver. For example, if the receiver is a method parameter `A` with a bound like
401 /// `trait<B,C,D>` then `Tn` would be `[B,C,D]`.
403 /// The weird part is that the type `A` might now be bound to any other type, such as `foo<X>`.
404 /// In that case, the vector we want is: `[X, M1, M2, M3]`. Therefore, what we do now is to slice
405 /// off the method type parameters and append them to the type parameters from the type that the
406 /// receiver is mapped to.
407 fn combine_impl_and_methods_tps<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
408 node: ExprOrMethodCall,
409 rcvr_substs: subst::Substs<'tcx>)
410 -> subst::Substs<'tcx>
414 let node_substs = node_id_substs(ccx, node, bcx.fcx.param_substs);
416 debug!("rcvr_substs={}", rcvr_substs.repr(ccx.tcx()));
417 debug!("node_substs={}", node_substs.repr(ccx.tcx()));
419 // Break apart the type parameters from the node and type
420 // parameters from the receiver.
421 let node_method = node_substs.types.split().fns;
422 let subst::SeparateVecsPerParamSpace {
426 } = rcvr_substs.types.clone().split();
427 assert!(rcvr_method.is_empty());
429 regions: subst::ErasedRegions,
430 types: subst::VecPerParamSpace::new(rcvr_type, rcvr_self, node_method)
434 /// Create a method callee where the method is coming from a trait object (e.g., Box<Trait> type).
435 /// In this case, we must pull the fn pointer out of the vtable that is packaged up with the
436 /// object. Objects are represented as a pair, so we first evaluate the self expression and then
437 /// extract the self data and vtable out of the pair.
438 fn trans_trait_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
441 self_expr: &ast::Expr,
442 arg_cleanup_scope: cleanup::ScopeId)
443 -> Callee<'blk, 'tcx> {
444 let _icx = push_ctxt("meth::trans_trait_callee");
447 // Translate self_datum and take ownership of the value by
448 // converting to an rvalue.
449 let self_datum = unpack_datum!(
450 bcx, expr::trans(bcx, self_expr));
452 let llval = if type_needs_drop(bcx.tcx(), self_datum.ty) {
453 let self_datum = unpack_datum!(
454 bcx, self_datum.to_rvalue_datum(bcx, "trait_callee"));
456 // Convert to by-ref since `trans_trait_callee_from_llval` wants it
458 let self_datum = unpack_datum!(
459 bcx, self_datum.to_ref_datum(bcx));
461 // Arrange cleanup in case something should go wrong before the
462 // actual call occurs.
463 self_datum.add_clean(bcx.fcx, arg_cleanup_scope)
465 // We don't have to do anything about cleanups for &Trait and &mut Trait.
466 assert!(self_datum.kind.is_by_ref());
470 trans_trait_callee_from_llval(bcx, method_ty, n_method, llval)
473 /// Same as `trans_trait_callee()` above, except that it is given a by-ref pointer to the object
475 pub fn trans_trait_callee_from_llval<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
479 -> Callee<'blk, 'tcx> {
480 let _icx = push_ctxt("meth::trans_trait_callee");
483 // Load the data pointer from the object.
484 debug!("(translating trait callee) loading second index from pair");
485 let llboxptr = GEPi(bcx, llpair, &[0u, abi::FAT_PTR_ADDR]);
486 let llbox = Load(bcx, llboxptr);
487 let llself = PointerCast(bcx, llbox, Type::i8p(ccx));
489 // Load the function from the vtable and cast it to the expected type.
490 debug!("(translating trait callee) loading method");
492 // Replace the self type (&Self or Box<Self>) with an opaque pointer.
493 let llcallee_ty = match callee_ty.sty {
494 ty::ty_bare_fn(_, ref f) if f.abi == Rust || f.abi == RustCall => {
496 ty::Binder(ty::FnSig {
497 inputs: f.sig.0.inputs.slice_from(1).to_vec(),
498 output: f.sig.0.output,
499 variadic: f.sig.0.variadic,
502 Some(Type::i8p(ccx)),
507 ccx.sess().bug("meth::trans_trait_callee given non-bare-rust-fn");
510 let llvtable = Load(bcx,
513 &[0u, abi::FAT_PTR_EXTRA]),
514 Type::vtable(ccx).ptr_to().ptr_to()));
515 let mptr = Load(bcx, GEPi(bcx, llvtable, &[0u, n_method + VTABLE_OFFSET]));
516 let mptr = PointerCast(bcx, mptr, llcallee_ty.ptr_to());
520 data: TraitItem(MethodData {
527 /// Generate a shim function that allows an object type like `SomeTrait` to
528 /// implement the type `SomeTrait`. Imagine a trait definition:
530 /// trait SomeTrait { fn get(&self) -> int; ... }
532 /// And a generic bit of code:
534 /// fn foo<T:SomeTrait>(t: &T) {
535 /// let x = SomeTrait::get;
539 /// What is the value of `x` when `foo` is invoked with `T=SomeTrait`?
540 /// The answer is that it it is a shim function generate by this
543 /// fn shim(t: &SomeTrait) -> int {
544 /// // ... call t.get() virtually ...
547 /// In fact, all virtual calls can be thought of as normal trait calls
548 /// that go through this shim function.
549 pub fn trans_object_shim<'a, 'tcx>(
550 ccx: &'a CrateContext<'a, 'tcx>,
552 trait_id: ast::DefId,
553 method_offset_in_trait: uint)
554 -> (ValueRef, Ty<'tcx>)
556 let _icx = push_ctxt("trans_object_shim");
559 debug!("trans_object_shim(object_ty={}, trait_id={}, n_method={})",
562 method_offset_in_trait);
564 let object_trait_ref =
565 match object_ty.sty {
566 ty::ty_trait(ref data) => {
567 data.principal_trait_ref_with_self_ty(tcx, object_ty)
570 tcx.sess.bug(format!("trans_object_shim() called on non-object: {}",
571 object_ty.repr(tcx)).as_slice());
575 // Upcast to the trait in question and extract out the substitutions.
576 let upcast_trait_ref = traits::upcast(ccx.tcx(), object_trait_ref.clone(), trait_id).unwrap();
577 let upcast_trait_ref = ty::erase_late_bound_regions(tcx, &upcast_trait_ref);
578 let object_substs = upcast_trait_ref.substs.clone().erase_regions();
579 debug!("trans_object_shim: object_substs={}", object_substs.repr(tcx));
581 // Lookup the type of this method as declared in the trait and apply substitutions.
582 let method_ty = match ty::trait_item(tcx, trait_id, method_offset_in_trait) {
583 ty::MethodTraitItem(method) => method,
584 ty::TypeTraitItem(_) => {
585 tcx.sess.bug("can't create a method shim for an associated type")
588 let fty = method_ty.fty.subst(tcx, &object_substs);
589 let fty = tcx.mk_bare_fn(fty);
590 debug!("trans_object_shim: fty={}", fty.repr(tcx));
593 let method_bare_fn_ty =
594 ty::mk_bare_fn(tcx, None, fty);
596 link::mangle_internal_name_by_type_and_seq(ccx, method_bare_fn_ty, "object_shim");
598 decl_internal_rust_fn(ccx, method_bare_fn_ty, function_name.as_slice());
600 let sig = ty::erase_late_bound_regions(ccx.tcx(), &fty.sig);
603 let block_arena = TypedArena::new();
604 let empty_substs = Substs::trans_empty();
605 let fcx = new_fn_ctxt(ccx,
613 let mut bcx = init_function(&fcx, false, sig.output);
615 // the first argument (`self`) will be a trait object
616 let llobject = get_param(fcx.llfn, fcx.arg_pos(0) as u32);
618 debug!("trans_object_shim: llobject={}",
619 bcx.val_to_string(llobject));
621 // the remaining arguments will be, well, whatever they are
625 // unpack the tuple to extract the input type arguments:
626 match sig.inputs[1].sty {
627 ty::ty_tup(ref tys) => tys.as_slice(),
630 format!("rust-call expects a tuple not {}",
631 sig.inputs[1].repr(tcx)).as_slice());
636 // skip the self parameter:
637 sig.inputs.slice_from(1)
645 let llarg = get_param(fcx.llfn, fcx.arg_pos(i+1) as u32);
646 debug!("trans_object_shim: input #{} == {}",
647 i, bcx.val_to_string(llarg));
652 assert!(!fcx.needs_ret_allocas);
655 ty::erase_late_bound_regions(bcx.tcx(), &fty.sig);
658 fcx.llretslotptr.get().map(
659 |_| expr::SaveIn(fcx.get_ret_slot(bcx, sig.output, "ret_slot")));
661 let method_offset_in_vtable =
662 traits::get_vtable_index_of_object_method(bcx.tcx(),
663 object_trait_ref.clone(),
665 method_offset_in_trait);
666 debug!("trans_object_shim: method_offset_in_vtable={}",
667 method_offset_in_vtable);
669 bcx = trans_call_inner(bcx,
672 |bcx, _| trans_trait_callee_from_llval(bcx,
674 method_offset_in_vtable,
676 ArgVals(llargs.as_slice()),
679 finish_fn(&fcx, bcx, sig.output);
681 (llfn, method_bare_fn_ty)
684 /// Creates a returns a dynamic vtable for the given type and vtable origin.
685 /// This is used only for objects.
687 /// The `trait_ref` encodes the erased self type. Hence if we are
688 /// making an object `Foo<Trait>` from a value of type `Foo<T>`, then
689 /// `trait_ref` would map `T:Trait`, but `box_ty` would be
690 /// `Foo<T>`. This `box_ty` is primarily used to encode the destructor.
691 /// This will hopefully change now that DST is underway.
692 pub fn get_vtable<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
694 trait_ref: ty::PolyTraitRef<'tcx>)
697 debug!("get_vtable(box_ty={}, trait_ref={})",
698 box_ty.repr(bcx.tcx()),
699 trait_ref.repr(bcx.tcx()));
703 let _icx = push_ctxt("meth::get_vtable");
706 let cache_key = (box_ty, trait_ref.clone());
707 match ccx.vtables().borrow().get(&cache_key) {
708 Some(&val) => { return val }
712 // Not in the cache. Build it.
713 let methods = traits::supertraits(tcx, trait_ref.clone()).flat_map(|trait_ref| {
714 let vtable = fulfill_obligation(bcx.ccx(),
718 traits::VtableBuiltin(_) => {
719 Vec::new().into_iter()
722 traits::VtableImplData {
726 emit_vtable_methods(bcx, id, substs).into_iter()
728 traits::VtableUnboxedClosure(closure_def_id, substs) => {
729 let llfn = trans_fn_ref_with_substs(
733 bcx.fcx.param_substs,
736 (vec!(llfn)).into_iter()
738 traits::VtableFnPointer(bare_fn_ty) => {
739 let llfn = vec![trans_fn_pointer_shim(bcx.ccx(), bare_fn_ty)];
742 traits::VtableObject(ref data) => {
743 // this would imply that the Self type being erased is
744 // an object type; this cannot happen because we
745 // cannot cast an unsized type into a trait object
747 format!("cannot get vtable for an object type: {}",
748 data.repr(bcx.tcx())).as_slice());
750 traits::VtableParam(..) => {
752 &format!("resolved vtable for {} to bad vtable {} in trans",
753 trait_ref.repr(bcx.tcx()),
754 vtable.repr(bcx.tcx()))[]);
759 let size_ty = sizing_type_of(ccx, trait_ref.self_ty());
760 let size = machine::llsize_of_alloc(ccx, size_ty);
761 let ll_size = C_uint(ccx, size);
762 let align = align_of(ccx, trait_ref.self_ty());
763 let ll_align = C_uint(ccx, align);
765 // Generate a destructor for the vtable.
766 let drop_glue = glue::get_drop_glue(ccx, box_ty);
767 let vtable = make_vtable(ccx, drop_glue, ll_size, ll_align, methods);
769 ccx.vtables().borrow_mut().insert(cache_key, vtable);
773 /// Helper function to declare and initialize the vtable.
774 pub fn make_vtable<I: Iterator<Item=ValueRef>>(ccx: &CrateContext,
780 let _icx = push_ctxt("meth::make_vtable");
782 let head = vec![drop_glue, size, align];
783 let components: Vec<_> = head.into_iter().chain(ptrs).collect();
786 let tbl = C_struct(ccx, &components[], false);
787 let sym = token::gensym("vtable");
788 let buf = CString::from_vec(format!("vtable{}", sym.uint()).into_bytes());
789 let vt_gvar = llvm::LLVMAddGlobal(ccx.llmod(), val_ty(tbl).to_ref(),
791 llvm::LLVMSetInitializer(vt_gvar, tbl);
792 llvm::LLVMSetGlobalConstant(vt_gvar, llvm::True);
793 llvm::SetLinkage(vt_gvar, llvm::InternalLinkage);
798 fn emit_vtable_methods<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
800 substs: subst::Substs<'tcx>)
805 let trt_id = match ty::impl_trait_ref(tcx, impl_id) {
806 Some(t_id) => t_id.def_id,
807 None => ccx.sess().bug("make_impl_vtable: don't know how to \
808 make a vtable for a type impl!")
811 ty::populate_implementations_for_trait_if_necessary(bcx.tcx(), trt_id);
813 let trait_item_def_ids = ty::trait_item_def_ids(tcx, trt_id);
814 trait_item_def_ids.iter().flat_map(|method_def_id| {
815 let method_def_id = method_def_id.def_id();
816 let name = ty::impl_or_trait_item(tcx, method_def_id).name();
817 // The substitutions we have are on the impl, so we grab
818 // the method type from the impl to substitute into.
819 let m_id = method_with_name(ccx, impl_id, name);
820 let ti = ty::impl_or_trait_item(tcx, m_id);
822 ty::MethodTraitItem(m) => {
823 debug!("(making impl vtable) emitting method {} at subst {}",
826 if m.generics.has_type_params(subst::FnSpace) ||
827 ty::type_has_self(ty::mk_bare_fn(tcx, None, tcx.mk_bare_fn(m.fty.clone())))
829 debug!("(making impl vtable) method has self or type \
831 token::get_name(name));
832 Some(C_null(Type::nil(ccx).ptr_to())).into_iter()
834 let fn_ref = trans_fn_ref_with_substs(
838 bcx.fcx.param_substs,
841 // currently, at least, by-value self is not object safe
842 assert!(m.explicit_self != ty::ByValueExplicitSelfCategory);
844 Some(fn_ref).into_iter()
847 ty::TypeTraitItem(_) => {
854 /// Generates the code to convert from a pointer (`Box<T>`, `&T`, etc) into an object
855 /// (`Box<Trait>`, `&Trait`, etc). This means creating a pair where the first word is the vtable
856 /// and the second word is the pointer.
857 pub fn trans_trait_cast<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
858 datum: Datum<'tcx, Expr>,
860 trait_ref: ty::PolyTraitRef<'tcx>,
862 -> Block<'blk, 'tcx> {
864 let _icx = push_ctxt("meth::trans_trait_cast");
866 let lldest = match dest {
868 return datum.clean(bcx, "trait_trait_cast", id);
873 debug!("trans_trait_cast: trait_ref={}",
874 trait_ref.repr(bcx.tcx()));
876 let datum_ty = datum.ty;
877 let llbox_ty = type_of(bcx.ccx(), datum_ty);
879 // Store the pointer into the first half of pair.
880 let llboxdest = GEPi(bcx, lldest, &[0u, abi::FAT_PTR_ADDR]);
881 let llboxdest = PointerCast(bcx, llboxdest, llbox_ty.ptr_to());
882 bcx = datum.store_to(bcx, llboxdest);
884 // Store the vtable into the second half of pair.
885 let vtable = get_vtable(bcx, datum_ty, trait_ref);
886 let llvtabledest = GEPi(bcx, lldest, &[0u, abi::FAT_PTR_EXTRA]);
887 let llvtabledest = PointerCast(bcx, llvtabledest, val_ty(vtable).ptr_to());
888 Store(bcx, vtable, llvtabledest);