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::{mod, 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::{mod, Ty};
34 use middle::ty::MethodCall;
35 use util::ppaux::Repr;
37 use std::c_str::ToCStr;
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,
127 MethodCallKey(method_call))),
131 ty::MethodTypeParam(ty::MethodParam {
135 let trait_ref = ty::Binder(bcx.monomorphize(trait_ref));
136 let span = bcx.tcx().map.span(method_call.expr_id);
137 debug!("method_call={} trait_ref={}",
139 trait_ref.repr(bcx.tcx()));
140 let origin = fulfill_obligation(bcx.ccx(),
143 debug!("origin = {}", origin.repr(bcx.tcx()));
144 trans_monomorphized_callee(bcx,
151 ty::MethodTraitObject(ref mt) => {
152 let self_expr = match self_expr {
153 Some(self_expr) => self_expr,
155 bcx.sess().span_bug(bcx.tcx().map.span(method_call.expr_id),
156 "self expr wasn't provided for trait object \
157 callee (trying to call overloaded op?)")
160 trans_trait_callee(bcx,
161 monomorphize_type(bcx, method_ty),
169 pub fn trans_static_method_callee(bcx: Block,
170 method_id: ast::DefId,
171 trait_id: ast::DefId,
172 expr_id: ast::NodeId)
175 let _icx = push_ctxt("meth::trans_static_method_callee");
178 debug!("trans_static_method_callee(method_id={}, trait_id={}, \
181 ty::item_path_str(bcx.tcx(), trait_id),
184 let mname = if method_id.krate == ast::LOCAL_CRATE {
185 match bcx.tcx().map.get(method_id.node) {
186 ast_map::NodeTraitItem(method) => {
187 let ident = match *method {
188 ast::RequiredMethod(ref m) => m.ident,
189 ast::ProvidedMethod(ref m) => m.pe_ident(),
190 ast::TypeTraitItem(_) => {
191 bcx.tcx().sess.bug("trans_static_method_callee() on \
192 an associated type?!")
197 _ => panic!("callee is not a trait method")
200 csearch::get_item_path(bcx.tcx(), method_id).last().unwrap().name()
202 debug!("trans_static_method_callee: method_id={}, expr_id={}, \
203 name={}", method_id, expr_id, token::get_name(mname));
205 // Find the substitutions for the fn itself. This includes
206 // type parameters that belong to the trait but also some that
207 // belong to the method:
208 let rcvr_substs = node_id_substs(bcx, ExprId(expr_id));
209 let subst::SeparateVecsPerParamSpace {
213 } = rcvr_substs.types.split();
215 // Lookup the precise impl being called. To do that, we need to
216 // create a trait reference identifying the self type and other
217 // input type parameters. To create that trait reference, we have
218 // to pick apart the type parameters to identify just those that
219 // pertain to the trait. This is easiest to explain by example:
222 // fn from<U:Foo>(n: U) -> Option<Self>;
225 // let f = <Vec<int> as Convert>::from::<String>(...)
227 // Here, in this call, which I've written with explicit UFCS
228 // notation, the set of type parameters will be:
230 // rcvr_type: [] <-- nothing declared on the trait itself
231 // rcvr_self: [Vec<int>] <-- the self type
232 // rcvr_method: [String] <-- method type parameter
234 // So we create a trait reference using the first two,
235 // basically corresponding to `<Vec<int> as Convert>`.
236 // The remaining type parameters (`rcvr_method`) will be used below.
238 Substs::erased(VecPerParamSpace::new(rcvr_type,
241 let trait_substs = bcx.tcx().mk_substs(trait_substs);
242 debug!("trait_substs={}", trait_substs.repr(bcx.tcx()));
243 let trait_ref = ty::Binder(Rc::new(ty::TraitRef { def_id: trait_id,
244 substs: trait_substs }));
245 let vtbl = fulfill_obligation(bcx.ccx(),
249 // Now that we know which impl is being used, we can dispatch to
250 // the actual function:
252 traits::VtableImpl(traits::VtableImplData {
253 impl_def_id: impl_did,
257 assert!(impl_substs.types.all(|t| !ty::type_needs_infer(*t)));
259 // Create the substitutions that are in scope. This combines
260 // the type parameters from the impl with those declared earlier.
261 // To see what I mean, consider a possible impl:
263 // impl<T> Convert for Vec<T> {
264 // fn from<U:Foo>(n: U) { ... }
267 // Recall that we matched `<Vec<int> as Convert>`. Trait
268 // resolution will have given us a substitution
269 // containing `impl_substs=[[T=int],[],[]]` (the type
270 // parameters defined on the impl). We combine
271 // that with the `rcvr_method` from before, which tells us
272 // the type parameters from the *method*, to yield
273 // `callee_substs=[[T=int],[],[U=String]]`.
274 let subst::SeparateVecsPerParamSpace {
278 } = impl_substs.types.split();
280 Substs::erased(VecPerParamSpace::new(impl_type,
284 let mth_id = method_with_name(ccx, impl_did, mname);
285 let llfn = trans_fn_ref_with_substs(bcx, mth_id, ExprId(expr_id),
288 let callee_ty = node_id_type(bcx, expr_id);
289 let llty = type_of_fn_from_ty(ccx, callee_ty).ptr_to();
290 PointerCast(bcx, llfn, llty)
294 format!("static call to invalid vtable: {}",
295 vtbl.repr(bcx.tcx()))[]);
300 fn method_with_name(ccx: &CrateContext, impl_id: ast::DefId, name: ast::Name)
302 match ccx.impl_method_cache().borrow().get(&(impl_id, name)).cloned() {
307 let impl_items = ccx.tcx().impl_items.borrow();
309 impl_items.get(&impl_id)
310 .expect("could not find impl while translating");
311 let meth_did = impl_items.iter()
313 ty::impl_or_trait_item(ccx.tcx(), did.def_id()).name() == name
314 }).expect("could not find method while \
317 ccx.impl_method_cache().borrow_mut().insert((impl_id, name),
322 fn trans_monomorphized_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
323 method_call: MethodCall,
324 trait_id: ast::DefId,
326 vtable: traits::Vtable<'tcx, ()>)
327 -> Callee<'blk, 'tcx> {
328 let _icx = push_ctxt("meth::trans_monomorphized_callee");
330 traits::VtableImpl(vtable_impl) => {
332 let impl_did = vtable_impl.impl_def_id;
333 let mname = match ty::trait_item(ccx.tcx(), trait_id, n_method) {
334 ty::MethodTraitItem(method) => method.name,
335 ty::TypeTraitItem(_) => {
336 bcx.tcx().sess.bug("can't monomorphize an associated \
340 let mth_id = method_with_name(bcx.ccx(), impl_did, mname);
342 // create a concatenated set of substitutions which includes
343 // those from the impl and those from the method:
345 combine_impl_and_methods_tps(
346 bcx, MethodCallKey(method_call), vtable_impl.substs);
348 // translate the function
349 let llfn = trans_fn_ref_with_substs(bcx,
351 MethodCallKey(method_call),
354 Callee { bcx: bcx, data: Fn(llfn) }
356 traits::VtableUnboxedClosure(closure_def_id, substs) => {
357 // The substitutions should have no type parameters remaining
358 // after passing through fulfill_obligation
359 let llfn = trans_fn_ref_with_substs(bcx,
361 MethodCallKey(method_call),
369 traits::VtableFnPointer(fn_ty) => {
370 let llfn = trans_fn_pointer_shim(bcx.ccx(), fn_ty);
371 Callee { bcx: bcx, data: Fn(llfn) }
373 traits::VtableObject(ref data) => {
374 let llfn = trans_object_shim(bcx.ccx(), data.object_ty, trait_id, n_method);
375 Callee { bcx: bcx, data: Fn(llfn) }
377 traits::VtableBuiltin(..) |
378 traits::VtableParam(..) => {
380 format!("resolved vtable bad vtable {} in trans",
381 vtable.repr(bcx.tcx()))[]);
386 /// Creates a concatenated set of substitutions which includes those from the impl and those from
387 /// the method. This are some subtle complications here. Statically, we have a list of type
388 /// parameters like `[T0, T1, T2, M1, M2, M3]` where `Tn` are type parameters that appear on the
389 /// receiver. For example, if the receiver is a method parameter `A` with a bound like
390 /// `trait<B,C,D>` then `Tn` would be `[B,C,D]`.
392 /// The weird part is that the type `A` might now be bound to any other type, such as `foo<X>`.
393 /// In that case, the vector we want is: `[X, M1, M2, M3]`. Therefore, what we do now is to slice
394 /// off the method type parameters and append them to the type parameters from the type that the
395 /// receiver is mapped to.
396 fn combine_impl_and_methods_tps<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
397 node: ExprOrMethodCall,
398 rcvr_substs: subst::Substs<'tcx>)
399 -> subst::Substs<'tcx>
403 let node_substs = node_id_substs(bcx, node);
405 debug!("rcvr_substs={}", rcvr_substs.repr(ccx.tcx()));
406 debug!("node_substs={}", node_substs.repr(ccx.tcx()));
408 // Break apart the type parameters from the node and type
409 // parameters from the receiver.
410 let node_method = node_substs.types.split().fns;
411 let subst::SeparateVecsPerParamSpace {
415 } = rcvr_substs.types.clone().split();
416 assert!(rcvr_method.is_empty());
418 regions: subst::ErasedRegions,
419 types: subst::VecPerParamSpace::new(rcvr_type, rcvr_self, node_method)
423 /// Create a method callee where the method is coming from a trait object (e.g., Box<Trait> type).
424 /// In this case, we must pull the fn pointer out of the vtable that is packaged up with the
425 /// object. Objects are represented as a pair, so we first evaluate the self expression and then
426 /// extract the self data and vtable out of the pair.
427 fn trans_trait_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
430 self_expr: &ast::Expr,
431 arg_cleanup_scope: cleanup::ScopeId)
432 -> Callee<'blk, 'tcx> {
433 let _icx = push_ctxt("meth::trans_trait_callee");
436 // Translate self_datum and take ownership of the value by
437 // converting to an rvalue.
438 let self_datum = unpack_datum!(
439 bcx, expr::trans(bcx, self_expr));
441 let llval = if type_needs_drop(bcx.tcx(), self_datum.ty) {
442 let self_datum = unpack_datum!(
443 bcx, self_datum.to_rvalue_datum(bcx, "trait_callee"));
445 // Convert to by-ref since `trans_trait_callee_from_llval` wants it
447 let self_datum = unpack_datum!(
448 bcx, self_datum.to_ref_datum(bcx));
450 // Arrange cleanup in case something should go wrong before the
451 // actual call occurs.
452 self_datum.add_clean(bcx.fcx, arg_cleanup_scope)
454 // We don't have to do anything about cleanups for &Trait and &mut Trait.
455 assert!(self_datum.kind.is_by_ref());
459 trans_trait_callee_from_llval(bcx, method_ty, n_method, llval)
462 /// Same as `trans_trait_callee()` above, except that it is given a by-ref pointer to the object
464 pub fn trans_trait_callee_from_llval<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
468 -> Callee<'blk, 'tcx> {
469 let _icx = push_ctxt("meth::trans_trait_callee");
472 // Load the data pointer from the object.
473 debug!("(translating trait callee) loading second index from pair");
474 let llboxptr = GEPi(bcx, llpair, &[0u, abi::FAT_PTR_ADDR]);
475 let llbox = Load(bcx, llboxptr);
476 let llself = PointerCast(bcx, llbox, Type::i8p(ccx));
478 // Load the function from the vtable and cast it to the expected type.
479 debug!("(translating trait callee) loading method");
480 // Replace the self type (&Self or Box<Self>) with an opaque pointer.
481 let llcallee_ty = match callee_ty.sty {
482 ty::ty_bare_fn(_, ref f) if f.abi == Rust || f.abi == RustCall => {
484 Some(Type::i8p(ccx)),
485 f.sig.0.inputs.slice_from(1),
490 ccx.sess().bug("meth::trans_trait_callee given non-bare-rust-fn");
493 let llvtable = Load(bcx,
496 &[0u, abi::FAT_PTR_EXTRA]),
497 Type::vtable(ccx).ptr_to().ptr_to()));
498 let mptr = Load(bcx, GEPi(bcx, llvtable, &[0u, n_method + VTABLE_OFFSET]));
499 let mptr = PointerCast(bcx, mptr, llcallee_ty.ptr_to());
503 data: TraitItem(MethodData {
510 /// Generate a shim function that allows an object type like `SomeTrait` to
511 /// implement the type `SomeTrait`. Imagine a trait definition:
513 /// trait SomeTrait { fn get(&self) -> int; ... }
515 /// And a generic bit of code:
517 /// fn foo<T:SomeTrait>(t: &T) {
518 /// let x = SomeTrait::get;
522 /// What is the value of `x` when `foo` is invoked with `T=SomeTrait`?
523 /// The answer is that it it is a shim function generate by this
526 /// fn shim(t: &SomeTrait) -> int {
527 /// // ... call t.get() virtually ...
530 /// In fact, all virtual calls can be thought of as normal trait calls
531 /// that go through this shim function.
532 pub fn trans_object_shim<'a, 'tcx>(
533 ccx: &'a CrateContext<'a, 'tcx>,
535 trait_id: ast::DefId,
536 method_offset_in_trait: uint)
539 let _icx = push_ctxt("trans_object_shim");
542 debug!("trans_object_shim(object_ty={}, trait_id={}, n_method={})",
545 method_offset_in_trait);
547 let object_trait_ref =
548 match object_ty.sty {
549 ty::ty_trait(ref data) => {
550 data.principal_trait_ref_with_self_ty(tcx, object_ty)
553 tcx.sess.bug(format!("trans_object_shim() called on non-object: {}",
554 object_ty.repr(tcx)).as_slice());
558 // Upcast to the trait in question and extract out the substitutions.
559 let upcast_trait_ref = traits::upcast(ccx.tcx(), object_trait_ref.clone(), trait_id).unwrap();
560 let object_substs = upcast_trait_ref.substs().clone().erase_regions();
561 debug!("trans_object_shim: object_substs={}", object_substs.repr(tcx));
563 // Lookup the type of this method as deeclared in the trait and apply substitutions.
564 let method_ty = match ty::trait_item(tcx, trait_id, method_offset_in_trait) {
565 ty::MethodTraitItem(method) => method,
566 ty::TypeTraitItem(_) => {
567 tcx.sess.bug("can't create a method shim for an associated type")
570 let fty = method_ty.fty.subst(tcx, &object_substs);
571 let fty = tcx.mk_bare_fn(fty);
572 debug!("trans_object_shim: fty={}", fty.repr(tcx));
575 let method_bare_fn_ty =
576 ty::mk_bare_fn(tcx, None, fty);
578 link::mangle_internal_name_by_type_and_seq(ccx, method_bare_fn_ty, "object_shim");
580 decl_internal_rust_fn(ccx, method_bare_fn_ty, function_name.as_slice());
583 let block_arena = TypedArena::new();
584 let empty_substs = Substs::trans_empty();
585 let fcx = new_fn_ctxt(ccx,
593 let mut bcx = init_function(&fcx, false, fty.sig.0.output);
595 // the first argument (`self`) will be a trait object
596 let llobject = get_param(fcx.llfn, fcx.arg_pos(0) as u32);
598 debug!("trans_object_shim: llobject={}",
599 bcx.val_to_string(llobject));
601 // the remaining arguments will be, well, whatever they are
603 fty.sig.0.inputs[1..].iter()
606 let llarg = get_param(fcx.llfn, fcx.arg_pos(i+1) as u32);
607 debug!("trans_object_shim: input #{} == {}",
608 i, bcx.val_to_string(llarg));
612 assert!(!fcx.needs_ret_allocas);
615 fcx.llretslotptr.get().map(
616 |_| expr::SaveIn(fcx.get_ret_slot(bcx, fty.sig.0.output, "ret_slot")));
618 let method_offset_in_vtable =
619 traits::get_vtable_index_of_object_method(bcx.tcx(),
620 object_trait_ref.clone(),
622 method_offset_in_trait);
623 debug!("trans_object_shim: method_offset_in_vtable={}",
624 method_offset_in_vtable);
626 bcx = trans_call_inner(bcx,
629 |bcx, _| trans_trait_callee_from_llval(bcx,
631 method_offset_in_vtable,
633 ArgVals(llargs.as_slice()),
636 finish_fn(&fcx, bcx, fty.sig.0.output);
641 /// Creates a returns a dynamic vtable for the given type and vtable origin.
642 /// This is used only for objects.
644 /// The `trait_ref` encodes the erased self type. Hence if we are
645 /// making an object `Foo<Trait>` from a value of type `Foo<T>`, then
646 /// `trait_ref` would map `T:Trait`, but `box_ty` would be
647 /// `Foo<T>`. This `box_ty` is primarily used to encode the destructor.
648 /// This will hopefully change now that DST is underway.
649 pub fn get_vtable<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
651 trait_ref: ty::PolyTraitRef<'tcx>)
654 debug!("get_vtable(box_ty={}, trait_ref={})",
655 box_ty.repr(bcx.tcx()),
656 trait_ref.repr(bcx.tcx()));
660 let _icx = push_ctxt("meth::get_vtable");
663 let cache_key = (box_ty, trait_ref.clone());
664 match ccx.vtables().borrow().get(&cache_key) {
665 Some(&val) => { return val }
669 // Not in the cache. Build it.
670 let methods = traits::supertraits(tcx, trait_ref.clone()).flat_map(|trait_ref| {
671 let vtable = fulfill_obligation(bcx.ccx(),
675 traits::VtableBuiltin(_) => {
676 Vec::new().into_iter()
679 traits::VtableImplData {
683 emit_vtable_methods(bcx, id, substs).into_iter()
685 traits::VtableUnboxedClosure(closure_def_id, substs) => {
686 let llfn = trans_fn_ref_with_substs(
692 (vec!(llfn)).into_iter()
694 traits::VtableFnPointer(bare_fn_ty) => {
695 let llfn = vec![trans_fn_pointer_shim(bcx.ccx(), bare_fn_ty)];
698 traits::VtableObject(ref data) => {
699 // this would imply that the Self type being erased is
700 // an object type; this cannot happen because we
701 // cannot cast an unsized type into a trait object
703 format!("cannot get vtable for an object type: {}",
704 data.repr(bcx.tcx())).as_slice());
706 traits::VtableParam => {
708 format!("resolved vtable for {} to bad vtable {} in trans",
709 trait_ref.repr(bcx.tcx()),
710 vtable.repr(bcx.tcx()))[]);
715 let size_ty = sizing_type_of(ccx, trait_ref.self_ty());
716 let size = machine::llsize_of_alloc(ccx, size_ty);
717 let ll_size = C_uint(ccx, size);
718 let align = align_of(ccx, trait_ref.self_ty());
719 let ll_align = C_uint(ccx, align);
721 // Generate a destructor for the vtable.
722 let drop_glue = glue::get_drop_glue(ccx, box_ty);
723 let vtable = make_vtable(ccx, drop_glue, ll_size, ll_align, methods);
725 ccx.vtables().borrow_mut().insert(cache_key, vtable);
729 /// Helper function to declare and initialize the vtable.
730 pub fn make_vtable<I: Iterator<Item=ValueRef>>(ccx: &CrateContext,
736 let _icx = push_ctxt("meth::make_vtable");
738 let head = vec![drop_glue, size, align];
739 let components: Vec<_> = head.into_iter().chain(ptrs).collect();
742 let tbl = C_struct(ccx, components[], false);
743 let sym = token::gensym("vtable");
744 let vt_gvar = format!("vtable{}", sym.uint()).with_c_str(|buf| {
745 llvm::LLVMAddGlobal(ccx.llmod(), val_ty(tbl).to_ref(), buf)
747 llvm::LLVMSetInitializer(vt_gvar, tbl);
748 llvm::LLVMSetGlobalConstant(vt_gvar, llvm::True);
749 llvm::SetLinkage(vt_gvar, llvm::InternalLinkage);
754 fn emit_vtable_methods<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
756 substs: subst::Substs<'tcx>)
761 let trt_id = match ty::impl_trait_ref(tcx, impl_id) {
762 Some(t_id) => t_id.def_id,
763 None => ccx.sess().bug("make_impl_vtable: don't know how to \
764 make a vtable for a type impl!")
767 ty::populate_implementations_for_trait_if_necessary(bcx.tcx(), trt_id);
769 let trait_item_def_ids = ty::trait_item_def_ids(tcx, trt_id);
770 trait_item_def_ids.iter().flat_map(|method_def_id| {
771 let method_def_id = method_def_id.def_id();
772 let name = ty::impl_or_trait_item(tcx, method_def_id).name();
773 // The substitutions we have are on the impl, so we grab
774 // the method type from the impl to substitute into.
775 let m_id = method_with_name(ccx, impl_id, name);
776 let ti = ty::impl_or_trait_item(tcx, m_id);
778 ty::MethodTraitItem(m) => {
779 debug!("(making impl vtable) emitting method {} at subst {}",
782 if m.generics.has_type_params(subst::FnSpace) ||
783 ty::type_has_self(ty::mk_bare_fn(tcx, None, tcx.mk_bare_fn(m.fty.clone())))
785 debug!("(making impl vtable) method has self or type \
787 token::get_name(name));
788 Some(C_null(Type::nil(ccx).ptr_to())).into_iter()
790 let fn_ref = trans_fn_ref_with_substs(
796 // currently, at least, by-value self is not object safe
797 assert!(m.explicit_self != ty::ByValueExplicitSelfCategory);
799 Some(fn_ref).into_iter()
802 ty::TypeTraitItem(_) => {
809 /// Generates the code to convert from a pointer (`Box<T>`, `&T`, etc) into an object
810 /// (`Box<Trait>`, `&Trait`, etc). This means creating a pair where the first word is the vtable
811 /// and the second word is the pointer.
812 pub fn trans_trait_cast<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
813 datum: Datum<'tcx, Expr>,
815 trait_ref: ty::PolyTraitRef<'tcx>,
817 -> Block<'blk, 'tcx> {
819 let _icx = push_ctxt("meth::trans_trait_cast");
821 let lldest = match dest {
823 return datum.clean(bcx, "trait_trait_cast", id);
828 debug!("trans_trait_cast: trait_ref={}",
829 trait_ref.repr(bcx.tcx()));
831 let datum_ty = datum.ty;
832 let llbox_ty = type_of(bcx.ccx(), datum_ty);
834 // Store the pointer into the first half of pair.
835 let llboxdest = GEPi(bcx, lldest, &[0u, abi::FAT_PTR_ADDR]);
836 let llboxdest = PointerCast(bcx, llboxdest, llbox_ty.ptr_to());
837 bcx = datum.store_to(bcx, llboxdest);
839 // Store the vtable into the second half of pair.
840 let vtable = get_vtable(bcx, datum_ty, trait_ref);
841 let llvtabledest = GEPi(bcx, lldest, &[0u, abi::FAT_PTR_EXTRA]);
842 let llvtabledest = PointerCast(bcx, llvtabledest, val_ty(vtable).ptr_to());
843 Store(bcx, vtable, llvtabledest);