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;
13 use llvm::{ValueRef, get_params};
14 use middle::def_id::DefId;
16 use middle::subst::{Subst, Substs};
17 use middle::subst::VecPerParamSpace;
29 use trans::debuginfo::DebugLoc;
31 use trans::expr::SaveIn;
35 use trans::monomorphize;
36 use trans::type_::Type;
37 use trans::type_of::*;
38 use middle::ty::{self, Ty, HasTypeFlags};
39 use middle::ty::MethodCall;
43 use syntax::codemap::DUMMY_SP;
48 // drop_glue pointer, size, align.
49 const VTABLE_OFFSET: usize = 3;
51 /// The main "translation" pass for methods. Generates code
52 /// for non-monomorphized methods only. Other methods will
53 /// be generated once they are invoked with specific type parameters,
54 /// see `trans::base::lval_static_fn()` or `trans::base::monomorphic_fn()`.
55 pub fn trans_impl(ccx: &CrateContext,
57 impl_items: &[P<hir::ImplItem>],
58 generics: &hir::Generics,
60 let _icx = push_ctxt("meth::trans_impl");
63 debug!("trans_impl(name={}, id={})", name, id);
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() {
71 for impl_item in impl_items {
72 match impl_item.node {
73 hir::ImplItemKind::Method(ref sig, ref body) => {
74 if sig.generics.ty_params.is_empty() {
75 let trans_everywhere = attr::requests_inline(&impl_item.attrs);
76 for (ref ccx, is_origin) in ccx.maybe_iter(trans_everywhere) {
77 let llfn = get_item_val(ccx, impl_item.id);
78 let empty_substs = tcx.mk_substs(Substs::trans_empty());
79 trans_fn(ccx, &sig.decl, body, llfn,
80 empty_substs, impl_item.id, &[]);
84 if is_origin { OriginalTranslation } else { InlinedCopy });
93 pub fn trans_method_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
94 method_call: MethodCall,
95 self_expr: Option<&hir::Expr>,
96 arg_cleanup_scope: cleanup::ScopeId)
97 -> Callee<'blk, 'tcx> {
98 let _icx = push_ctxt("meth::trans_method_callee");
100 let method = bcx.tcx().tables.borrow().method_map[&method_call];
102 match bcx.tcx().impl_or_trait_item(method.def_id).container() {
103 ty::ImplContainer(_) => {
104 debug!("trans_method_callee: static, {:?}", method.def_id);
105 let datum = callee::trans_fn_ref(bcx.ccx(),
107 MethodCallKey(method_call),
108 bcx.fcx.param_substs);
116 ty::TraitContainer(trait_def_id) => {
117 let trait_substs = method.substs.clone().method_to_trait();
118 let trait_substs = bcx.tcx().mk_substs(trait_substs);
119 let trait_ref = ty::TraitRef::new(trait_def_id, trait_substs);
121 let trait_ref = ty::Binder(bcx.monomorphize(&trait_ref));
122 let span = bcx.tcx().map.span(method_call.expr_id);
123 debug!("method_call={:?} trait_ref={:?} trait_ref id={:?} substs={:?}",
128 let origin = fulfill_obligation(bcx.ccx(),
131 debug!("origin = {:?}", origin);
132 trans_monomorphized_callee(bcx,
144 pub fn trans_static_method_callee<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
147 expr_id: ast::NodeId,
148 param_substs: &'tcx subst::Substs<'tcx>)
149 -> Datum<'tcx, Rvalue>
151 let _icx = push_ctxt("meth::trans_static_method_callee");
154 debug!("trans_static_method_callee(method_id={:?}, trait_id={}, \
157 tcx.item_path_str(trait_id),
160 let mname = tcx.item_name(method_id);
162 debug!("trans_static_method_callee: method_id={:?}, expr_id={}, \
163 name={}", method_id, expr_id, mname);
165 // Find the substitutions for the fn itself. This includes
166 // type parameters that belong to the trait but also some that
167 // belong to the method:
168 let rcvr_substs = node_id_substs(ccx, ExprId(expr_id), param_substs);
169 let subst::SeparateVecsPerParamSpace {
173 } = rcvr_substs.types.split();
175 // Lookup the precise impl being called. To do that, we need to
176 // create a trait reference identifying the self type and other
177 // input type parameters. To create that trait reference, we have
178 // to pick apart the type parameters to identify just those that
179 // pertain to the trait. This is easiest to explain by example:
182 // fn from<U:Foo>(n: U) -> Option<Self>;
185 // let f = <Vec<int> as Convert>::from::<String>(...)
187 // Here, in this call, which I've written with explicit UFCS
188 // notation, the set of type parameters will be:
190 // rcvr_type: [] <-- nothing declared on the trait itself
191 // rcvr_self: [Vec<int>] <-- the self type
192 // rcvr_method: [String] <-- method type parameter
194 // So we create a trait reference using the first two,
195 // basically corresponding to `<Vec<int> as Convert>`.
196 // The remaining type parameters (`rcvr_method`) will be used below.
198 Substs::erased(VecPerParamSpace::new(rcvr_type,
201 let trait_substs = tcx.mk_substs(trait_substs);
202 debug!("trait_substs={:?}", trait_substs);
203 let trait_ref = ty::Binder(ty::TraitRef::new(trait_id, trait_substs));
204 let vtbl = fulfill_obligation(ccx,
208 // Now that we know which impl is being used, we can dispatch to
209 // the actual function:
211 traits::VtableImpl(traits::VtableImplData {
212 impl_def_id: impl_did,
216 assert!(!impl_substs.types.needs_infer());
218 // Create the substitutions that are in scope. This combines
219 // the type parameters from the impl with those declared earlier.
220 // To see what I mean, consider a possible impl:
222 // impl<T> Convert for Vec<T> {
223 // fn from<U:Foo>(n: U) { ... }
226 // Recall that we matched `<Vec<int> as Convert>`. Trait
227 // resolution will have given us a substitution
228 // containing `impl_substs=[[T=int],[],[]]` (the type
229 // parameters defined on the impl). We combine
230 // that with the `rcvr_method` from before, which tells us
231 // the type parameters from the *method*, to yield
232 // `callee_substs=[[T=int],[],[U=String]]`.
233 let subst::SeparateVecsPerParamSpace {
237 } = impl_substs.types.split();
239 Substs::erased(VecPerParamSpace::new(impl_type,
243 let mth = tcx.get_impl_method(impl_did, callee_substs, mname);
244 trans_fn_ref_with_substs(ccx, mth.method.def_id, ExprId(expr_id),
248 traits::VtableObject(ref data) => {
249 let idx = traits::get_vtable_index_of_object_method(tcx, data, method_id);
250 trans_object_shim(ccx,
251 data.upcast_trait_ref.clone(),
256 tcx.sess.bug(&format!("static call to invalid vtable: {:?}",
262 fn trans_monomorphized_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
263 method_call: MethodCall,
264 self_expr: Option<&hir::Expr>,
268 vtable: traits::Vtable<'tcx, ()>,
269 arg_cleanup_scope: cleanup::ScopeId)
270 -> Callee<'blk, 'tcx> {
271 let _icx = push_ctxt("meth::trans_monomorphized_callee");
273 traits::VtableImpl(vtable_impl) => {
275 let impl_did = vtable_impl.impl_def_id;
276 let mname = match ccx.tcx().impl_or_trait_item(method_id) {
277 ty::MethodTraitItem(method) => method.name,
279 bcx.tcx().sess.bug("can't monomorphize a non-method trait \
283 // create a concatenated set of substitutions which includes
284 // those from the impl and those from the method:
286 combine_impl_and_methods_tps(
287 bcx, MethodCallKey(method_call), vtable_impl.substs);
289 let mth = bcx.tcx().get_impl_method(impl_did, callee_substs, mname);
290 // translate the function
291 let datum = trans_fn_ref_with_substs(bcx.ccx(),
293 MethodCallKey(method_call),
294 bcx.fcx.param_substs,
297 Callee { bcx: bcx, data: Fn(datum.val), ty: datum.ty }
299 traits::VtableClosure(vtable_closure) => {
300 // The substitutions should have no type parameters remaining
301 // after passing through fulfill_obligation
302 let trait_closure_kind = bcx.tcx().lang_items.fn_trait_kind(trait_id).unwrap();
303 let llfn = closure::trans_closure_method(bcx.ccx(),
304 vtable_closure.closure_def_id,
305 vtable_closure.substs,
310 ty: monomorphize_type(bcx, method_ty)
313 traits::VtableFnPointer(fn_ty) => {
314 let trait_closure_kind = bcx.tcx().lang_items.fn_trait_kind(trait_id).unwrap();
315 let llfn = trans_fn_pointer_shim(bcx.ccx(), trait_closure_kind, fn_ty);
319 ty: monomorphize_type(bcx, method_ty)
322 traits::VtableObject(ref data) => {
323 let idx = traits::get_vtable_index_of_object_method(bcx.tcx(), data, method_id);
324 if let Some(self_expr) = self_expr {
325 if let ty::TyBareFn(_, ref fty) = monomorphize_type(bcx, method_ty).sty {
326 let ty = bcx.tcx().mk_fn(None, opaque_method_ty(bcx.tcx(), fty));
327 return trans_trait_callee(bcx, ty, idx, self_expr, arg_cleanup_scope);
330 let datum = trans_object_shim(bcx.ccx(),
331 data.upcast_trait_ref.clone(),
334 Callee { bcx: bcx, data: Fn(datum.val), ty: datum.ty }
336 traits::VtableBuiltin(..) |
337 traits::VtableDefaultImpl(..) |
338 traits::VtableParam(..) => {
340 &format!("resolved vtable bad vtable {:?} in trans",
346 /// Creates a concatenated set of substitutions which includes those from the impl and those from
347 /// the method. This are some subtle complications here. Statically, we have a list of type
348 /// parameters like `[T0, T1, T2, M1, M2, M3]` where `Tn` are type parameters that appear on the
349 /// receiver. For example, if the receiver is a method parameter `A` with a bound like
350 /// `trait<B,C,D>` then `Tn` would be `[B,C,D]`.
352 /// The weird part is that the type `A` might now be bound to any other type, such as `foo<X>`.
353 /// In that case, the vector we want is: `[X, M1, M2, M3]`. Therefore, what we do now is to slice
354 /// off the method type parameters and append them to the type parameters from the type that the
355 /// receiver is mapped to.
356 fn combine_impl_and_methods_tps<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
357 node: ExprOrMethodCall,
358 rcvr_substs: subst::Substs<'tcx>)
359 -> subst::Substs<'tcx>
363 let node_substs = node_id_substs(ccx, node, bcx.fcx.param_substs);
365 debug!("rcvr_substs={:?}", rcvr_substs);
366 debug!("node_substs={:?}", node_substs);
368 // Break apart the type parameters from the node and type
369 // parameters from the receiver.
370 let node_method = node_substs.types.split().fns;
371 let subst::SeparateVecsPerParamSpace {
375 } = rcvr_substs.types.clone().split();
376 assert!(rcvr_method.is_empty());
378 regions: subst::ErasedRegions,
379 types: subst::VecPerParamSpace::new(rcvr_type, rcvr_self, node_method)
383 /// Create a method callee where the method is coming from a trait object (e.g., Box<Trait> type).
384 /// In this case, we must pull the fn pointer out of the vtable that is packaged up with the
385 /// object. Objects are represented as a pair, so we first evaluate the self expression and then
386 /// extract the self data and vtable out of the pair.
387 fn trans_trait_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
388 opaque_fn_ty: Ty<'tcx>,
390 self_expr: &hir::Expr,
391 arg_cleanup_scope: cleanup::ScopeId)
392 -> Callee<'blk, 'tcx> {
393 let _icx = push_ctxt("meth::trans_trait_callee");
396 // Translate self_datum and take ownership of the value by
397 // converting to an rvalue.
398 let self_datum = unpack_datum!(
399 bcx, expr::trans(bcx, self_expr));
401 let llval = if bcx.fcx.type_needs_drop(self_datum.ty) {
402 let self_datum = unpack_datum!(
403 bcx, self_datum.to_rvalue_datum(bcx, "trait_callee"));
405 // Convert to by-ref since `trans_trait_callee_from_llval` wants it
407 let self_datum = unpack_datum!(
408 bcx, self_datum.to_ref_datum(bcx));
410 // Arrange cleanup in case something should go wrong before the
411 // actual call occurs.
412 self_datum.add_clean(bcx.fcx, arg_cleanup_scope)
414 // We don't have to do anything about cleanups for &Trait and &mut Trait.
415 assert!(self_datum.kind.is_by_ref());
419 let llself = Load(bcx, expr::get_dataptr(bcx, llval));
420 let llvtable = Load(bcx, expr::get_meta(bcx, llval));
421 trans_trait_callee_from_llval(bcx, opaque_fn_ty, vtable_index, llself, llvtable)
424 /// Same as `trans_trait_callee()` above, except that it is given a by-ref pointer to the object
426 fn trans_trait_callee_from_llval<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
427 opaque_fn_ty: Ty<'tcx>,
431 -> Callee<'blk, 'tcx> {
432 let _icx = push_ctxt("meth::trans_trait_callee");
435 // Load the data pointer from the object.
436 debug!("trans_trait_callee_from_llval(callee_ty={}, vtable_index={}, llself={}, llvtable={})",
439 bcx.val_to_string(llself),
440 bcx.val_to_string(llvtable));
442 // Replace the self type (&Self or Box<Self>) with an opaque pointer.
443 let mptr = Load(bcx, GEPi(bcx, llvtable, &[vtable_index + VTABLE_OFFSET]));
444 let llcallee_ty = type_of_fn_from_ty(ccx, opaque_fn_ty);
448 data: TraitItem(MethodData {
449 llfn: PointerCast(bcx, mptr, llcallee_ty.ptr_to()),
450 llself: PointerCast(bcx, llself, Type::i8p(ccx)),
456 /// Generate a shim function that allows an object type like `SomeTrait` to
457 /// implement the type `SomeTrait`. Imagine a trait definition:
459 /// trait SomeTrait { fn get(&self) -> int; ... }
461 /// And a generic bit of code:
463 /// fn foo<T:SomeTrait>(t: &T) {
464 /// let x = SomeTrait::get;
468 /// What is the value of `x` when `foo` is invoked with `T=SomeTrait`?
469 /// The answer is that it is a shim function generated by this routine:
471 /// fn shim(t: &SomeTrait) -> int {
472 /// // ... call t.get() virtually ...
475 /// In fact, all virtual calls can be thought of as normal trait calls
476 /// that go through this shim function.
477 fn trans_object_shim<'a, 'tcx>(
478 ccx: &'a CrateContext<'a, 'tcx>,
479 upcast_trait_ref: ty::PolyTraitRef<'tcx>,
482 -> Datum<'tcx, Rvalue>
484 let _icx = push_ctxt("trans_object_shim");
487 debug!("trans_object_shim(upcast_trait_ref={:?}, method_id={:?})",
491 // Upcast to the trait in question and extract out the substitutions.
492 let upcast_trait_ref = tcx.erase_late_bound_regions(&upcast_trait_ref);
493 let object_substs = upcast_trait_ref.substs.clone().erase_regions();
494 debug!("trans_object_shim: object_substs={:?}", object_substs);
496 // Lookup the type of this method as declared in the trait and apply substitutions.
497 let method_ty = match tcx.impl_or_trait_item(method_id) {
498 ty::MethodTraitItem(method) => method,
500 tcx.sess.bug("can't create a method shim for a non-method item")
503 let fty = monomorphize::apply_param_substs(tcx, &object_substs, &method_ty.fty);
504 let fty = tcx.mk_bare_fn(fty);
505 let method_ty = opaque_method_ty(tcx, fty);
506 debug!("trans_object_shim: fty={:?} method_ty={:?}", fty, method_ty);
509 let shim_fn_ty = tcx.mk_fn(None, fty);
510 let method_bare_fn_ty = tcx.mk_fn(None, method_ty);
511 let function_name = link::mangle_internal_name_by_type_and_seq(ccx, shim_fn_ty, "object_shim");
512 let llfn = declare::define_internal_rust_fn(ccx, &function_name, shim_fn_ty);
514 let sig = ccx.tcx().erase_late_bound_regions(&fty.sig);
515 let sig = infer::normalize_associated_type(ccx.tcx(), &sig);
517 let empty_substs = tcx.mk_substs(Substs::trans_empty());
518 let (block_arena, fcx): (TypedArena<_>, FunctionContext);
519 block_arena = TypedArena::new();
520 fcx = new_fn_ctxt(ccx,
528 let mut bcx = init_function(&fcx, false, sig.output);
530 let llargs = get_params(fcx.llfn);
532 let self_idx = fcx.arg_offset();
533 let llself = llargs[self_idx];
534 let llvtable = llargs[self_idx + 1];
536 debug!("trans_object_shim: llself={}, llvtable={}",
537 bcx.val_to_string(llself), bcx.val_to_string(llvtable));
539 assert!(!fcx.needs_ret_allocas);
542 fcx.llretslotptr.get().map(
543 |_| expr::SaveIn(fcx.get_ret_slot(bcx, sig.output, "ret_slot")));
545 debug!("trans_object_shim: method_offset_in_vtable={}",
548 bcx = trans_call_inner(bcx,
550 |bcx, _| trans_trait_callee_from_llval(bcx,
554 ArgVals(&llargs[(self_idx + 2)..]),
557 finish_fn(&fcx, bcx, sig.output, DebugLoc::None);
559 immediate_rvalue(llfn, shim_fn_ty)
562 /// Creates a returns a dynamic vtable for the given type and vtable origin.
563 /// This is used only for objects.
565 /// The `trait_ref` encodes the erased self type. Hence if we are
566 /// making an object `Foo<Trait>` from a value of type `Foo<T>`, then
567 /// `trait_ref` would map `T:Trait`.
568 pub fn get_vtable<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
569 trait_ref: ty::PolyTraitRef<'tcx>,
570 param_substs: &'tcx subst::Substs<'tcx>)
574 let _icx = push_ctxt("meth::get_vtable");
576 debug!("get_vtable(trait_ref={:?})", trait_ref);
579 match ccx.vtables().borrow().get(&trait_ref) {
580 Some(&val) => { return val }
584 // Not in the cache. Build it.
585 let methods = traits::supertraits(tcx, trait_ref.clone()).flat_map(|trait_ref| {
586 let vtable = fulfill_obligation(ccx, DUMMY_SP, trait_ref.clone());
588 // Should default trait error here?
589 traits::VtableDefaultImpl(_) |
590 traits::VtableBuiltin(_) => {
591 Vec::new().into_iter()
594 traits::VtableImplData {
598 emit_vtable_methods(ccx, id, substs, param_substs).into_iter()
600 traits::VtableClosure(
601 traits::VtableClosureData {
605 let trait_closure_kind = tcx.lang_items.fn_trait_kind(trait_ref.def_id()).unwrap();
606 let llfn = closure::trans_closure_method(ccx,
610 vec![llfn].into_iter()
612 traits::VtableFnPointer(bare_fn_ty) => {
613 let trait_closure_kind = tcx.lang_items.fn_trait_kind(trait_ref.def_id()).unwrap();
614 vec![trans_fn_pointer_shim(ccx, trait_closure_kind, bare_fn_ty)].into_iter()
616 traits::VtableObject(ref data) => {
617 // this would imply that the Self type being erased is
618 // an object type; this cannot happen because we
619 // cannot cast an unsized type into a trait object
621 &format!("cannot get vtable for an object type: {:?}",
624 traits::VtableParam(..) => {
626 &format!("resolved vtable for {:?} to bad vtable {:?} in trans",
633 let size_ty = sizing_type_of(ccx, trait_ref.self_ty());
634 let size = machine::llsize_of_alloc(ccx, size_ty);
635 let align = align_of(ccx, trait_ref.self_ty());
637 let components: Vec<_> = vec![
638 // Generate a destructor for the vtable.
639 glue::get_drop_glue(ccx, trait_ref.self_ty()),
642 ].into_iter().chain(methods).collect();
644 let vtable_const = C_struct(ccx, &components, false);
645 let align = machine::llalign_of_pref(ccx, val_ty(vtable_const));
646 let vtable = consts::addr_of(ccx, vtable_const, align, "vtable");
648 ccx.vtables().borrow_mut().insert(trait_ref, vtable);
652 fn emit_vtable_methods<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
654 substs: subst::Substs<'tcx>,
655 param_substs: &'tcx subst::Substs<'tcx>)
660 debug!("emit_vtable_methods(impl_id={:?}, substs={:?}, param_substs={:?})",
665 let trt_id = match tcx.impl_trait_ref(impl_id) {
666 Some(t_id) => t_id.def_id,
667 None => ccx.sess().bug("make_impl_vtable: don't know how to \
668 make a vtable for a type impl!")
671 tcx.populate_implementations_for_trait_if_necessary(trt_id);
673 let nullptr = C_null(Type::nil(ccx).ptr_to());
674 let trait_item_def_ids = tcx.trait_item_def_ids(trt_id);
678 // Filter out non-method items.
679 .filter_map(|item_def_id| {
681 ty::MethodTraitItemId(def_id) => Some(def_id),
686 // Now produce pointers for each remaining method. If the
687 // method could never be called from this object, just supply
689 .map(|trait_method_def_id| {
690 debug!("emit_vtable_methods: trait_method_def_id={:?}",
691 trait_method_def_id);
693 let trait_method_type = match tcx.impl_or_trait_item(trait_method_def_id) {
694 ty::MethodTraitItem(m) => m,
695 _ => ccx.sess().bug("should be a method, not other assoc item"),
697 let name = trait_method_type.name;
699 // Some methods cannot be called on an object; skip those.
700 if !traits::is_vtable_safe_method(tcx, trt_id, &trait_method_type) {
701 debug!("emit_vtable_methods: not vtable safe");
705 debug!("emit_vtable_methods: trait_method_type={:?}",
708 // The substitutions we have are on the impl, so we grab
709 // the method type from the impl to substitute into.
710 let mth = tcx.get_impl_method(impl_id, substs.clone(), name);
712 debug!("emit_vtable_methods: mth={:?}", mth);
714 // If this is a default method, it's possible that it
715 // relies on where clauses that do not hold for this
716 // particular set of type parameters. Note that this
717 // method could then never be called, so we do not want to
718 // try and trans it, in that case. Issue #23435.
720 let predicates = mth.method.predicates.predicates.subst(tcx, &mth.substs);
721 if !normalize_and_test_predicates(ccx, predicates.into_vec()) {
722 debug!("emit_vtable_methods: predicates do not hold");
727 trans_fn_ref_with_substs(ccx,
736 /// Replace the self type (&Self or Box<Self>) with an opaque pointer.
737 fn opaque_method_ty<'tcx>(tcx: &ty::ctxt<'tcx>, method_ty: &ty::BareFnTy<'tcx>)
738 -> &'tcx ty::BareFnTy<'tcx> {
739 let mut inputs = method_ty.sig.0.inputs.clone();
740 inputs[0] = tcx.mk_mut_ptr(tcx.mk_mach_int(ast::TyI8));
742 tcx.mk_bare_fn(ty::BareFnTy {
743 unsafety: method_ty.unsafety,
745 sig: ty::Binder(ty::FnSig {
747 output: method_ty.sig.0.output,
748 variadic: method_ty.sig.0.variadic,