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.
14 use lib::llvm::ValueRef;
16 use metadata::csearch;
17 use middle::trans::base::*;
18 use middle::trans::build::*;
19 use middle::trans::callee::*;
20 use middle::trans::callee;
21 use middle::trans::common::*;
22 use middle::trans::datum::*;
23 use middle::trans::expr::{SaveIn, Ignore};
24 use middle::trans::expr;
25 use middle::trans::glue;
26 use middle::trans::monomorphize;
27 use middle::trans::type_of::*;
30 use util::common::indenter;
31 use util::ppaux::Repr;
33 use middle::trans::type_::Type;
36 use syntax::ast_map::{path, path_mod, path_name};
38 use syntax::{ast, ast_map};
41 The main "translation" pass for methods. Generates code
42 for non-monomorphized methods only. Other methods will
43 be generated once they are invoked with specific type parameters,
44 see `trans::base::lval_static_fn()` or `trans::base::monomorphic_fn()`.
46 pub fn trans_impl(ccx: @mut CrateContext,
49 methods: &[@ast::method],
50 generics: &ast::Generics,
52 let _icx = push_ctxt("impl::trans_impl");
55 debug!("trans_impl(path=%s, name=%s, id=%?)",
56 path.repr(tcx), name.repr(tcx), id);
58 if !generics.ty_params.is_empty() { return; }
59 let sub_path = vec::append_one(path, path_name(name));
60 for methods.iter().advance |method| {
61 if method.generics.ty_params.len() == 0u {
62 let llfn = get_item_val(ccx, method.id);
63 let path = vec::append_one(sub_path.clone(),
64 path_name(method.ident));
75 /// Translates a (possibly monomorphized) method body.
78 /// * `path`: the path to the method
79 /// * `method`: the AST node for the method
80 /// * `param_substs`: if this is a generic method, the current values for
81 /// type parameters and so forth, else none
82 /// * `llfn`: the LLVM ValueRef for the method
83 /// * `impl_id`: the node ID of the impl this method is inside
85 /// XXX(pcwalton) Can we take `path` by reference?
86 pub fn trans_method(ccx: @mut CrateContext,
89 param_substs: Option<@param_substs>,
91 // figure out how self is being passed
92 let self_arg = match method.explicit_self.node {
97 // determine the (monomorphized) type that `self` maps to for
99 let self_ty = ty::node_id_to_type(ccx.tcx, method.self_id);
100 let self_ty = match param_substs {
102 Some(@param_substs {tys: ref tys, self_ty: ref self_sub, _}) => {
103 ty::subst_tps(ccx.tcx, *tys, *self_sub, self_ty)
106 debug!("calling trans_fn with self_ty %s",
107 self_ty.repr(ccx.tcx));
108 match method.explicit_self.node {
109 ast::sty_value => impl_self(self_ty, ty::ByRef),
110 _ => impl_self(self_ty, ty::ByCopy),
115 // generate the actual code
127 pub fn trans_self_arg(bcx: @mut Block,
129 temp_cleanups: &mut ~[ValueRef],
130 mentry: typeck::method_map_entry) -> Result {
131 let _icx = push_ctxt("impl::trans_self_arg");
133 // self is passed as an opaque box in the environment slot
134 let self_ty = ty::mk_opaque_box(bcx.tcx());
144 pub fn trans_method_callee(bcx: @mut Block,
145 callee_id: ast::node_id,
147 mentry: typeck::method_map_entry)
149 let _icx = push_ctxt("impl::trans_method_callee");
152 debug!("trans_method_callee(callee_id=%?, this=%s, mentry=%s)",
154 bcx.expr_to_str(this),
155 mentry.repr(bcx.tcx()));
157 // Replace method_self with method_static here.
158 let mut origin = mentry.origin;
160 typeck::method_super(trait_id, method_index) => {
161 // <self_ty> is the self type for this method call
162 let self_ty = node_id_type(bcx, this.id);
163 // <impl_id> is the ID of the implementation of
164 // trait <trait_id> for type <self_ty>
165 let impl_id = ty::bogus_get_impl_id_from_ty(tcx, trait_id, self_ty);
166 // Get the supertrait's methods
167 let supertrait_method_def_ids = ty::trait_method_def_ids(tcx, trait_id);
168 // Make sure to fail with a readable error message if
169 // there's some internal error here
170 if !(method_index < supertrait_method_def_ids.len()) {
171 tcx.sess.bug("trans_method_callee: supertrait method \
172 index is out of bounds");
174 // Get the method name using the method index in the origin
176 ty::method(tcx, supertrait_method_def_ids[method_index]).ident;
177 // Now that we know the impl ID, we can look up the method
179 origin = typeck::method_static(
180 method_with_name(bcx.ccx(), impl_id, method_name));
182 typeck::method_self(*) |
183 typeck::method_static(*) | typeck::method_param(*) |
184 typeck::method_trait(*) => {}
187 debug!("origin=%?", origin);
190 typeck::method_static(did) => {
191 let callee_fn = callee::trans_fn_ref(bcx, did, callee_id);
192 let mut temp_cleanups = ~[];
193 let Result {bcx, val} = trans_self_arg(bcx, this, &mut temp_cleanups, mentry);
196 data: Method(MethodData {
197 llfn: callee_fn.llfn,
199 temp_cleanup: temp_cleanups.head_opt().map(|&v| *v),
200 self_ty: node_id_type(bcx, this.id),
201 self_mode: mentry.self_mode,
205 typeck::method_param(typeck::method_param {
211 match bcx.fcx.param_substs {
213 let vtbl = find_vtable(bcx.tcx(), substs, p, b);
214 trans_monomorphized_callee(bcx, callee_id, this, mentry,
217 // how to get rid of this?
218 None => fail!("trans_method_callee: missing param_substs")
222 typeck::method_self(trait_id, method_index) => {
223 match bcx.fcx.param_substs {
225 {self_vtable: Some(ref vtbl), _}) => {
226 trans_monomorphized_callee(bcx,
235 fail!("trans_method_callee: missing self_vtable")
240 typeck::method_trait(_, off, store) => {
241 trans_trait_callee(bcx,
246 mentry.explicit_self)
248 typeck::method_super(*) => {
249 fail!("method_super should have been handled above")
254 pub fn trans_static_method_callee(bcx: @mut Block,
255 method_id: ast::def_id,
256 trait_id: ast::def_id,
257 callee_id: ast::node_id)
259 let _icx = push_ctxt("impl::trans_static_method_callee");
262 debug!("trans_static_method_callee(method_id=%?, trait_id=%s, \
265 ty::item_path_str(bcx.tcx(), trait_id),
267 let _indenter = indenter();
269 // When we translate a static fn defined in a trait like:
271 // trait<T1...Tn> Trait {
272 // fn foo<M1...Mn>(...) {...}
275 // this winds up being translated as something like:
277 // fn foo<T1...Tn,self: Trait<T1...Tn>,M1...Mn>(...) {...}
279 // So when we see a call to this function foo, we have to figure
280 // out which impl the `Trait<T1...Tn>` bound on the type `self` was
282 let bound_index = ty::lookup_trait_def(bcx.tcx(), trait_id).
283 generics.type_param_defs.len();
285 let mname = if method_id.crate == ast::local_crate {
286 match bcx.tcx().items.get_copy(&method_id.node) {
287 ast_map::node_trait_method(trait_method, _, _) => {
288 ast_util::trait_method_to_ty_method(trait_method).ident
290 _ => fail!("callee is not a trait method")
293 let path = csearch::get_item_path(bcx.tcx(), method_id);
294 match path[path.len()-1] {
295 path_name(s) => { s }
296 path_mod(_) => { fail!("path doesn't have a name?") }
299 debug!("trans_static_method_callee: method_id=%?, callee_id=%?, \
300 name=%s", method_id, callee_id, ccx.sess.str_of(mname));
302 let vtbls = resolve_vtables_in_fn_ctxt(
303 bcx.fcx, ccx.maps.vtable_map.get_copy(&callee_id));
305 match vtbls[bound_index][0] {
306 typeck::vtable_static(impl_did, ref rcvr_substs, rcvr_origins) => {
307 assert!(rcvr_substs.iter().all(|t| !ty::type_needs_infer(*t)));
309 let mth_id = method_with_name(bcx.ccx(), impl_did, mname);
310 let (callee_substs, callee_origins) =
311 combine_impl_and_methods_tps(
312 bcx, mth_id, callee_id,
313 *rcvr_substs, rcvr_origins);
315 let FnData {llfn: lval} =
316 trans_fn_ref_with_vtables(bcx,
320 Some(callee_origins));
322 let callee_ty = node_id_type(bcx, callee_id);
323 let llty = type_of_fn_from_ty(ccx, callee_ty).ptr_to();
324 FnData {llfn: PointerCast(bcx, lval, llty)}
327 fail!("vtable_param left in monomorphized \
328 function's vtable substs");
333 pub fn method_with_name(ccx: &mut CrateContext,
334 impl_id: ast::def_id,
335 name: ast::ident) -> ast::def_id {
336 let meth_id_opt = ccx.impl_method_cache.find_copy(&(impl_id, name));
342 let imp = ccx.tcx.impls.find(&impl_id)
343 .expect("could not find impl while translating");
344 let meth = imp.methods.iter().find_(|m| m.ident == name)
345 .expect("could not find method while translating");
347 ccx.impl_method_cache.insert((impl_id, name), meth.def_id);
351 pub fn trans_monomorphized_callee(bcx: @mut Block,
352 callee_id: ast::node_id,
354 mentry: typeck::method_map_entry,
355 trait_id: ast::def_id,
357 vtbl: typeck::vtable_origin)
359 let _icx = push_ctxt("impl::trans_monomorphized_callee");
361 typeck::vtable_static(impl_did, ref rcvr_substs, rcvr_origins) => {
363 let mname = ty::trait_method(ccx.tcx, trait_id, n_method).ident;
364 let mth_id = method_with_name(bcx.ccx(), impl_did, mname);
366 // obtain the `self` value:
367 let mut temp_cleanups = ~[];
368 let Result {bcx, val: llself_val} =
369 trans_self_arg(bcx, base, &mut temp_cleanups, mentry);
371 // create a concatenated set of substitutions which includes
372 // those from the impl and those from the method:
373 let (callee_substs, callee_origins) =
374 combine_impl_and_methods_tps(
375 bcx, mth_id, callee_id,
376 *rcvr_substs, rcvr_origins);
378 // translate the function
379 let callee = trans_fn_ref_with_vtables(bcx,
383 Some(callee_origins));
385 // create a llvalue that represents the fn ptr
386 let fn_ty = node_id_type(bcx, callee_id);
387 let llfn_ty = type_of_fn_from_ty(ccx, fn_ty).ptr_to();
388 let llfn_val = PointerCast(bcx, callee.llfn, llfn_ty);
390 // combine the self environment with the rest
393 data: Method(MethodData {
396 temp_cleanup: temp_cleanups.head_opt().map(|&v| *v),
397 self_ty: node_id_type(bcx, base.id),
398 self_mode: mentry.self_mode,
402 typeck::vtable_param(*) => {
403 fail!("vtable_param left in monomorphized function's vtable substs");
405 typeck::vtable_self(*) => {
406 fail!("vtable_self left in monomorphized function's vtable substs");
412 pub fn combine_impl_and_methods_tps(bcx: @mut Block,
413 mth_did: ast::def_id,
414 callee_id: ast::node_id,
415 rcvr_substs: &[ty::t],
416 rcvr_origins: typeck::vtable_res)
417 -> (~[ty::t], typeck::vtable_res) {
420 * Creates a concatenated set of substitutions which includes
421 * those from the impl and those from the method. This are
422 * some subtle complications here. Statically, we have a list
423 * of type parameters like `[T0, T1, T2, M1, M2, M3]` where
424 * `Tn` are type parameters that appear on the receiver. For
425 * example, if the receiver is a method parameter `A` with a
426 * bound like `trait<B,C,D>` then `Tn` would be `[B,C,D]`.
428 * The weird part is that the type `A` might now be bound to
429 * any other type, such as `foo<X>`. In that case, the vector
430 * we want is: `[X, M1, M2, M3]`. Therefore, what we do now is
431 * to slice off the method type parameters and append them to
432 * the type parameters from the type that the receiver is
436 let method = ty::method(ccx.tcx, mth_did);
437 let n_m_tps = method.generics.type_param_defs.len();
438 let node_substs = node_id_type_params(bcx, callee_id);
439 debug!("rcvr_substs=%?", rcvr_substs.repr(ccx.tcx));
441 = vec::append(rcvr_substs.to_owned(),
442 node_substs.tailn(node_substs.len() - n_m_tps));
443 debug!("n_m_tps=%?", n_m_tps);
444 debug!("node_substs=%?", node_substs.repr(ccx.tcx));
445 debug!("ty_substs=%?", ty_substs.repr(ccx.tcx));
448 // Now, do the same work for the vtables. The vtables might not
449 // exist, in which case we need to make them.
450 let r_m_origins = match node_vtables(bcx, callee_id) {
452 None => @vec::from_elem(node_substs.len(), @~[])
455 = @vec::append(rcvr_origins.to_owned(),
456 r_m_origins.tailn(r_m_origins.len() - n_m_tps));
458 return (ty_substs, vtables);
462 pub fn trans_trait_callee(bcx: @mut Block,
463 callee_id: ast::node_id,
465 self_expr: @ast::expr,
466 store: ty::TraitStore,
467 explicit_self: ast::explicit_self_)
471 // Create a method callee where the method is coming from a trait
472 // instance (e.g., @Trait type). In this case, we must pull the
473 // fn pointer out of the vtable that is packaged up with the
474 // @/~/&Trait instance. @/~/&Traits are represented as a pair, so we
475 // first evaluate the self expression (expected a by-ref result) and then
476 // extract the self data and vtable out of the pair.
478 let _icx = push_ctxt("impl::trans_trait_callee");
480 let self_datum = unpack_datum!(bcx,
481 expr::trans_to_datum(bcx, self_expr));
482 let llpair = self_datum.to_ref_llval(bcx);
484 let llpair = match explicit_self {
485 ast::sty_region(*) => Load(bcx, llpair),
486 ast::sty_static | ast::sty_value |
487 ast::sty_box(_) | ast::sty_uniq => llpair
490 let callee_ty = node_id_type(bcx, callee_id);
491 trans_trait_callee_from_llval(bcx,
499 pub fn trans_trait_callee_from_llval(bcx: @mut Block,
503 store: ty::TraitStore,
504 explicit_self: ast::explicit_self_)
508 // Same as `trans_trait_callee()` above, except that it is given
509 // a by-ref pointer to the @Trait pair.
511 let _icx = push_ctxt("impl::trans_trait_callee");
514 // Load the vtable from the @Trait pair
515 debug!("(translating trait callee) loading vtable from pair %s",
516 bcx.val_to_str(llpair));
517 let llvtable = Load(bcx,
520 [0u, abi::trt_field_vtable]),
521 Type::vtable().ptr_to().ptr_to()));
523 // Load the box from the @Trait pair and GEP over the box header if
526 debug!("(translating trait callee) loading second index from pair");
527 let llboxptr = GEPi(bcx, llpair, [0u, abi::trt_field_box]);
528 let llbox = Load(bcx, llboxptr);
530 // Munge `llself` appropriately for the type of `self` in the method.
531 match explicit_self {
533 bcx.tcx().sess.bug("shouldn't see static method here");
536 bcx.tcx().sess.bug("methods with by-value self should not be \
539 ast::sty_region(*) => {
542 if !ty::type_contents(bcx.tcx(), callee_ty).contains_managed() => {
546 ty::UniqTraitStore => {
547 llself = GEPi(bcx, llbox, [0u, abi::box_field_body]);
549 ty::RegionTraitStore(_) => {
555 // Bump the reference count on the box.
556 debug!("(translating trait callee) callee type is `%s`",
557 bcx.ty_to_str(callee_ty));
558 glue::incr_refcnt_of_boxed(bcx, llbox);
560 // Pass a pointer to the box.
562 ty::BoxTraitStore => llself = llbox,
563 _ => bcx.tcx().sess.bug("@self receiver with non-@Trait")
567 // Pass the unique pointer.
569 ty::UniqTraitStore => llself = llbox,
570 _ => bcx.tcx().sess.bug("~self receiver with non-~Trait")
573 zero_mem(bcx, llboxptr, ty::mk_opaque_box(bcx.tcx()));
577 llself = PointerCast(bcx, llself, Type::opaque_box(ccx).ptr_to());
578 let scratch = scratch_datum(bcx, ty::mk_opaque_box(bcx.tcx()),
579 "__trait_callee", false);
580 Store(bcx, llself, scratch.val);
581 scratch.add_clean(bcx);
583 // Load the function from the vtable and cast it to the expected type.
584 debug!("(translating trait callee) loading method");
585 let llcallee_ty = type_of_fn_from_ty(ccx, callee_ty);
587 // Plus one in order to skip past the type descriptor.
588 let mptr = Load(bcx, GEPi(bcx, llvtable, [0u, n_method + 1]));
590 let mptr = PointerCast(bcx, mptr, llcallee_ty.ptr_to());
594 data: Method(MethodData {
596 llself: scratch.to_value_llval(bcx),
597 temp_cleanup: Some(scratch.val),
599 self_mode: ty::ByCopy,
600 /* XXX: Some(llbox) */
605 pub fn vtable_id(ccx: @mut CrateContext,
606 origin: &typeck::vtable_origin)
609 &typeck::vtable_static(impl_id, ref substs, sub_vtables) => {
610 let psubsts = param_substs {
611 tys: (*substs).clone(),
612 vtables: Some(sub_vtables),
617 monomorphize::make_mono_id(
624 // can't this be checked at the callee?
625 _ => fail!("vtable_id")
629 /// Creates a returns a dynamic vtable for the given type and vtable origin.
630 /// This is used only for objects.
631 pub fn get_vtable(bcx: @mut Block,
633 origin: typeck::vtable_origin)
635 let hash_id = vtable_id(bcx.ccx(), &origin);
636 match bcx.ccx().vtables.find(&hash_id) {
640 typeck::vtable_static(id, substs, sub_vtables) => {
641 make_impl_vtable(bcx, id, self_ty, substs, sub_vtables)
643 _ => fail!("get_vtable: expected a static origin"),
649 /// Helper function to declare and initialize the vtable.
650 pub fn make_vtable(ccx: &mut CrateContext,
651 tydesc: &tydesc_info,
655 let _icx = push_ctxt("impl::make_vtable");
657 let mut components = ~[ tydesc.tydesc ];
658 for ptrs.iter().advance |&ptr| {
662 let tbl = C_struct(components);
663 let vtable = ccx.sess.str_of(gensym_name("vtable"));
664 let vt_gvar = do vtable.as_c_str |buf| {
665 llvm::LLVMAddGlobal(ccx.llmod, val_ty(tbl).to_ref(), buf)
667 llvm::LLVMSetInitializer(vt_gvar, tbl);
668 llvm::LLVMSetGlobalConstant(vt_gvar, lib::llvm::True);
669 lib::llvm::SetLinkage(vt_gvar, lib::llvm::InternalLinkage);
674 /// Generates a dynamic vtable for objects.
675 pub fn make_impl_vtable(bcx: @mut Block,
676 impl_id: ast::def_id,
679 vtables: typeck::vtable_res)
682 let _icx = push_ctxt("impl::make_impl_vtable");
685 let trt_id = match ty::impl_trait_ref(tcx, impl_id) {
686 Some(t_id) => t_id.def_id,
687 None => ccx.sess.bug("make_impl_vtable: don't know how to \
688 make a vtable for a type impl!")
691 let trait_method_def_ids = ty::trait_method_def_ids(tcx, trt_id);
692 let methods = do trait_method_def_ids.map |method_def_id| {
693 let im = ty::method(tcx, *method_def_id);
694 let fty = ty::subst_tps(tcx,
697 ty::mk_bare_fn(tcx, im.fty.clone()));
698 if im.generics.has_type_params() || ty::type_has_self(fty) {
699 debug!("(making impl vtable) method has self or type params: %s",
700 tcx.sess.str_of(im.ident));
701 C_null(Type::nil().ptr_to())
703 debug!("(making impl vtable) adding method to vtable: %s",
704 tcx.sess.str_of(im.ident));
705 let m_id = method_with_name(ccx, impl_id, im.ident);
707 trans_fn_ref_with_vtables(bcx, m_id, 0,
708 substs, Some(vtables)).llfn
712 // Generate a type descriptor for the vtable.
713 let tydesc = get_tydesc(ccx, self_ty);
714 glue::lazily_emit_all_tydesc_glue(ccx, tydesc);
716 make_vtable(ccx, tydesc, methods)
719 pub fn trans_trait_cast(bcx: @mut Block,
723 _store: ty::TraitStore)
726 let _icx = push_ctxt("impl::trans_cast");
728 let lldest = match dest {
730 return expr::trans_into(bcx, val, Ignore);
736 let v_ty = expr_ty(bcx, val);
738 let mut llboxdest = GEPi(bcx, lldest, [0u, abi::trt_field_box]);
739 // Just store the pointer into the pair. (Region/borrowed
740 // and boxed trait objects are represented as pairs, and
741 // have no type descriptor field.)
742 llboxdest = PointerCast(bcx,
744 type_of(bcx.ccx(), v_ty).ptr_to());
745 bcx = expr::trans_into(bcx, val, SaveIn(llboxdest));
747 // Store the vtable into the pair or triple.
748 let orig = ccx.maps.vtable_map.get(&id)[0][0].clone();
749 let orig = resolve_vtable_in_fn_ctxt(bcx.fcx, &orig);
750 let vtable = get_vtable(bcx, v_ty, orig);
751 Store(bcx, vtable, PointerCast(bcx,
752 GEPi(bcx, lldest, [0u, abi::trt_field_vtable]),
753 val_ty(vtable).ptr_to()));