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;
35 use std::c_str::ToCStr;
37 use syntax::ast_map::{path, path_mod, path_name};
39 use syntax::{ast, ast_map};
42 The main "translation" pass for methods. Generates code
43 for non-monomorphized methods only. Other methods will
44 be generated once they are invoked with specific type parameters,
45 see `trans::base::lval_static_fn()` or `trans::base::monomorphic_fn()`.
47 pub fn trans_impl(ccx: @mut CrateContext,
50 methods: &[@ast::method],
51 generics: &ast::Generics,
53 let _icx = push_ctxt("impl::trans_impl");
56 debug!("trans_impl(path=%s, name=%s, id=%?)",
57 path.repr(tcx), name.repr(tcx), id);
59 if !generics.ty_params.is_empty() { return; }
60 let sub_path = vec::append_one(path, path_name(name));
61 for method in methods.iter() {
62 if method.generics.ty_params.len() == 0u {
63 let llfn = get_item_val(ccx, method.id);
64 let path = vec::append_one(sub_path.clone(),
65 path_name(method.ident));
76 /// Translates a (possibly monomorphized) method body.
79 /// * `path`: the path to the method
80 /// * `method`: the AST node for the method
81 /// * `param_substs`: if this is a generic method, the current values for
82 /// type parameters and so forth, else none
83 /// * `llfn`: the LLVM ValueRef for the method
84 /// * `impl_id`: the node ID of the impl this method is inside
86 /// XXX(pcwalton) Can we take `path` by reference?
87 pub fn trans_method(ccx: @mut CrateContext,
90 param_substs: Option<@param_substs>,
92 // figure out how self is being passed
93 let self_arg = match method.explicit_self.node {
98 // determine the (monomorphized) type that `self` maps to for
100 let self_ty = ty::node_id_to_type(ccx.tcx, method.self_id);
101 let self_ty = match param_substs {
103 Some(@param_substs {tys: ref tys, self_ty: ref self_sub, _}) => {
104 ty::subst_tps(ccx.tcx, *tys, *self_sub, self_ty)
107 debug!("calling trans_fn with self_ty %s",
108 self_ty.repr(ccx.tcx));
109 match method.explicit_self.node {
110 ast::sty_value => impl_self(self_ty, ty::ByRef),
111 _ => impl_self(self_ty, ty::ByCopy),
116 // generate the actual code
128 pub fn trans_self_arg(bcx: @mut Block,
130 temp_cleanups: &mut ~[ValueRef],
131 mentry: typeck::method_map_entry) -> Result {
132 let _icx = push_ctxt("impl::trans_self_arg");
134 // self is passed as an opaque box in the environment slot
135 let self_ty = ty::mk_opaque_box(bcx.tcx());
144 pub fn trans_method_callee(bcx: @mut Block,
145 callee_id: ast::NodeId,
147 mentry: typeck::method_map_entry)
149 let _icx = push_ctxt("impl::trans_method_callee");
151 debug!("trans_method_callee(callee_id=%?, this=%s, mentry=%s)",
153 bcx.expr_to_str(this),
154 mentry.repr(bcx.tcx()));
156 match mentry.origin {
157 typeck::method_static(did) => {
158 let callee_fn = callee::trans_fn_ref(bcx, did, callee_id);
159 let mut temp_cleanups = ~[];
160 let Result {bcx, val} = trans_self_arg(bcx, this, &mut temp_cleanups, mentry);
163 data: Method(MethodData {
164 llfn: callee_fn.llfn,
166 temp_cleanup: temp_cleanups.head_opt().map(|&v| *v),
167 self_ty: node_id_type(bcx, this.id),
168 self_mode: mentry.self_mode,
172 typeck::method_param(typeck::method_param {
178 match bcx.fcx.param_substs {
180 let vtbl = find_vtable(bcx.tcx(), substs,
182 trans_monomorphized_callee(bcx, callee_id, this, mentry,
185 // how to get rid of this?
186 None => fail!("trans_method_callee: missing param_substs")
190 typeck::method_trait(_, off, store) => {
191 trans_trait_callee(bcx,
196 mentry.explicit_self)
201 pub fn trans_static_method_callee(bcx: @mut Block,
202 method_id: ast::def_id,
203 trait_id: ast::def_id,
204 callee_id: ast::NodeId)
206 let _icx = push_ctxt("impl::trans_static_method_callee");
209 debug!("trans_static_method_callee(method_id=%?, trait_id=%s, \
212 ty::item_path_str(bcx.tcx(), trait_id),
214 let _indenter = indenter();
216 // When we translate a static fn defined in a trait like:
218 // trait<T1...Tn> Trait {
219 // fn foo<M1...Mn>(...) {...}
222 // this winds up being translated as something like:
224 // fn foo<T1...Tn,self: Trait<T1...Tn>,M1...Mn>(...) {...}
226 // So when we see a call to this function foo, we have to figure
227 // out which impl the `Trait<T1...Tn>` bound on the type `self` was
229 let bound_index = ty::lookup_trait_def(bcx.tcx(), trait_id).
230 generics.type_param_defs.len();
232 let mname = if method_id.crate == ast::LOCAL_CRATE {
233 match bcx.tcx().items.get_copy(&method_id.node) {
234 ast_map::node_trait_method(trait_method, _, _) => {
235 ast_util::trait_method_to_ty_method(trait_method).ident
237 _ => fail!("callee is not a trait method")
240 let path = csearch::get_item_path(bcx.tcx(), method_id);
241 match path[path.len()-1] {
242 path_name(s) => { s }
243 path_mod(_) => { fail!("path doesn't have a name?") }
246 debug!("trans_static_method_callee: method_id=%?, callee_id=%?, \
247 name=%s", method_id, callee_id, ccx.sess.str_of(mname));
249 let vtbls = resolve_vtables_in_fn_ctxt(
250 bcx.fcx, ccx.maps.vtable_map.get_copy(&callee_id));
252 match vtbls[bound_index][0] {
253 typeck::vtable_static(impl_did, ref rcvr_substs, rcvr_origins) => {
254 assert!(rcvr_substs.iter().all(|t| !ty::type_needs_infer(*t)));
256 let mth_id = method_with_name(bcx.ccx(), impl_did, mname);
257 let (callee_substs, callee_origins) =
258 combine_impl_and_methods_tps(
259 bcx, mth_id, callee_id,
260 *rcvr_substs, rcvr_origins);
262 let FnData {llfn: lval} =
263 trans_fn_ref_with_vtables(bcx,
267 Some(callee_origins));
269 let callee_ty = node_id_type(bcx, callee_id);
270 let llty = type_of_fn_from_ty(ccx, callee_ty).ptr_to();
271 FnData {llfn: PointerCast(bcx, lval, llty)}
274 fail!("vtable_param left in monomorphized \
275 function's vtable substs");
280 pub fn method_with_name(ccx: &mut CrateContext,
281 impl_id: ast::def_id,
282 name: ast::ident) -> ast::def_id {
283 let meth_id_opt = ccx.impl_method_cache.find_copy(&(impl_id, name));
289 let imp = ccx.tcx.impls.find(&impl_id)
290 .expect("could not find impl while translating");
291 let meth = imp.methods.iter().find_(|m| m.ident == name)
292 .expect("could not find method while translating");
294 ccx.impl_method_cache.insert((impl_id, name), meth.def_id);
298 pub fn trans_monomorphized_callee(bcx: @mut Block,
299 callee_id: ast::NodeId,
301 mentry: typeck::method_map_entry,
302 trait_id: ast::def_id,
304 vtbl: typeck::vtable_origin)
306 let _icx = push_ctxt("impl::trans_monomorphized_callee");
308 typeck::vtable_static(impl_did, ref rcvr_substs, rcvr_origins) => {
310 let mname = ty::trait_method(ccx.tcx, trait_id, n_method).ident;
311 let mth_id = method_with_name(bcx.ccx(), impl_did, mname);
313 // obtain the `self` value:
314 let mut temp_cleanups = ~[];
315 let Result {bcx, val: llself_val} =
316 trans_self_arg(bcx, base, &mut temp_cleanups, mentry);
318 // create a concatenated set of substitutions which includes
319 // those from the impl and those from the method:
320 let (callee_substs, callee_origins) =
321 combine_impl_and_methods_tps(
322 bcx, mth_id, callee_id,
323 *rcvr_substs, rcvr_origins);
325 // translate the function
326 let callee = trans_fn_ref_with_vtables(bcx,
330 Some(callee_origins));
332 // create a llvalue that represents the fn ptr
333 let fn_ty = node_id_type(bcx, callee_id);
334 let llfn_ty = type_of_fn_from_ty(ccx, fn_ty).ptr_to();
335 let llfn_val = PointerCast(bcx, callee.llfn, llfn_ty);
337 // combine the self environment with the rest
340 data: Method(MethodData {
343 temp_cleanup: temp_cleanups.head_opt().map(|&v| *v),
344 self_ty: node_id_type(bcx, base.id),
345 self_mode: mentry.self_mode,
349 typeck::vtable_param(*) => {
350 fail!("vtable_param left in monomorphized function's vtable substs");
356 pub fn combine_impl_and_methods_tps(bcx: @mut Block,
357 mth_did: ast::def_id,
358 callee_id: ast::NodeId,
359 rcvr_substs: &[ty::t],
360 rcvr_origins: typeck::vtable_res)
361 -> (~[ty::t], typeck::vtable_res) {
364 * Creates a concatenated set of substitutions which includes
365 * those from the impl and those from the method. This are
366 * some subtle complications here. Statically, we have a list
367 * of type parameters like `[T0, T1, T2, M1, M2, M3]` where
368 * `Tn` are type parameters that appear on the receiver. For
369 * example, if the receiver is a method parameter `A` with a
370 * bound like `trait<B,C,D>` then `Tn` would be `[B,C,D]`.
372 * The weird part is that the type `A` might now be bound to
373 * any other type, such as `foo<X>`. In that case, the vector
374 * we want is: `[X, M1, M2, M3]`. Therefore, what we do now is
375 * to slice off the method type parameters and append them to
376 * the type parameters from the type that the receiver is
380 let method = ty::method(ccx.tcx, mth_did);
381 let n_m_tps = method.generics.type_param_defs.len();
382 let node_substs = node_id_type_params(bcx, callee_id);
383 debug!("rcvr_substs=%?", rcvr_substs.repr(ccx.tcx));
385 = vec::append(rcvr_substs.to_owned(),
386 node_substs.tailn(node_substs.len() - n_m_tps));
387 debug!("n_m_tps=%?", n_m_tps);
388 debug!("node_substs=%?", node_substs.repr(ccx.tcx));
389 debug!("ty_substs=%?", ty_substs.repr(ccx.tcx));
392 // Now, do the same work for the vtables. The vtables might not
393 // exist, in which case we need to make them.
394 let r_m_origins = match node_vtables(bcx, callee_id) {
396 None => @vec::from_elem(node_substs.len(), @~[])
399 = @vec::append(rcvr_origins.to_owned(),
400 r_m_origins.tailn(r_m_origins.len() - n_m_tps));
402 return (ty_substs, vtables);
406 pub fn trans_trait_callee(bcx: @mut Block,
407 callee_id: ast::NodeId,
409 self_expr: @ast::expr,
410 store: ty::TraitStore,
411 explicit_self: ast::explicit_self_)
415 // Create a method callee where the method is coming from a trait
416 // instance (e.g., @Trait type). In this case, we must pull the
417 // fn pointer out of the vtable that is packaged up with the
418 // @/~/&Trait instance. @/~/&Traits are represented as a pair, so we
419 // first evaluate the self expression (expected a by-ref result) and then
420 // extract the self data and vtable out of the pair.
422 let _icx = push_ctxt("impl::trans_trait_callee");
424 let self_datum = unpack_datum!(bcx,
425 expr::trans_to_datum(bcx, self_expr));
426 let llpair = self_datum.to_ref_llval(bcx);
428 let llpair = match explicit_self {
429 ast::sty_region(*) => Load(bcx, llpair),
430 ast::sty_static | ast::sty_value |
431 ast::sty_box(_) | ast::sty_uniq => llpair
434 let callee_ty = node_id_type(bcx, callee_id);
435 trans_trait_callee_from_llval(bcx,
443 pub fn trans_trait_callee_from_llval(bcx: @mut Block,
447 store: ty::TraitStore,
448 explicit_self: ast::explicit_self_)
452 // Same as `trans_trait_callee()` above, except that it is given
453 // a by-ref pointer to the @Trait pair.
455 let _icx = push_ctxt("impl::trans_trait_callee");
458 // Load the vtable from the @Trait pair
459 debug!("(translating trait callee) loading vtable from pair %s",
460 bcx.val_to_str(llpair));
461 let llvtable = Load(bcx,
464 [0u, abi::trt_field_vtable]),
465 Type::vtable().ptr_to().ptr_to()));
467 // Load the box from the @Trait pair and GEP over the box header if
470 debug!("(translating trait callee) loading second index from pair");
471 let llboxptr = GEPi(bcx, llpair, [0u, abi::trt_field_box]);
472 let llbox = Load(bcx, llboxptr);
474 // Munge `llself` appropriately for the type of `self` in the method.
475 match explicit_self {
477 bcx.tcx().sess.bug("shouldn't see static method here");
480 bcx.tcx().sess.bug("methods with by-value self should not be \
483 ast::sty_region(*) => {
486 if !ty::type_contents(bcx.tcx(), callee_ty).contains_managed() => {
490 ty::UniqTraitStore => {
491 llself = GEPi(bcx, llbox, [0u, abi::box_field_body]);
493 ty::RegionTraitStore(_) => {
499 // Bump the reference count on the box.
500 debug!("(translating trait callee) callee type is `%s`",
501 bcx.ty_to_str(callee_ty));
502 glue::incr_refcnt_of_boxed(bcx, llbox);
504 // Pass a pointer to the box.
506 ty::BoxTraitStore => llself = llbox,
507 _ => bcx.tcx().sess.bug("@self receiver with non-@Trait")
511 // Pass the unique pointer.
513 ty::UniqTraitStore => llself = llbox,
514 _ => bcx.tcx().sess.bug("~self receiver with non-~Trait")
517 zero_mem(bcx, llboxptr, ty::mk_opaque_box(bcx.tcx()));
521 llself = PointerCast(bcx, llself, Type::opaque_box(ccx).ptr_to());
522 let scratch = scratch_datum(bcx, ty::mk_opaque_box(bcx.tcx()),
523 "__trait_callee", false);
524 Store(bcx, llself, scratch.val);
525 scratch.add_clean(bcx);
527 // Load the function from the vtable and cast it to the expected type.
528 debug!("(translating trait callee) loading method");
529 let llcallee_ty = type_of_fn_from_ty(ccx, callee_ty);
531 // Plus one in order to skip past the type descriptor.
532 let mptr = Load(bcx, GEPi(bcx, llvtable, [0u, n_method + 1]));
534 let mptr = PointerCast(bcx, mptr, llcallee_ty.ptr_to());
538 data: Method(MethodData {
540 llself: scratch.to_value_llval(bcx),
541 temp_cleanup: Some(scratch.val),
543 self_mode: ty::ByCopy,
544 /* XXX: Some(llbox) */
549 pub fn vtable_id(ccx: @mut CrateContext,
550 origin: &typeck::vtable_origin)
553 &typeck::vtable_static(impl_id, ref substs, sub_vtables) => {
554 let psubsts = param_substs {
555 tys: (*substs).clone(),
556 vtables: Some(sub_vtables),
561 monomorphize::make_mono_id(
568 // can't this be checked at the callee?
569 _ => fail!("vtable_id")
573 /// Creates a returns a dynamic vtable for the given type and vtable origin.
574 /// This is used only for objects.
575 pub fn get_vtable(bcx: @mut Block,
577 origin: typeck::vtable_origin)
579 let hash_id = vtable_id(bcx.ccx(), &origin);
580 match bcx.ccx().vtables.find(&hash_id) {
584 typeck::vtable_static(id, substs, sub_vtables) => {
585 make_impl_vtable(bcx, id, self_ty, substs, sub_vtables)
587 _ => fail!("get_vtable: expected a static origin"),
593 /// Helper function to declare and initialize the vtable.
594 pub fn make_vtable(ccx: &mut CrateContext,
595 tydesc: &tydesc_info,
599 let _icx = push_ctxt("impl::make_vtable");
601 let mut components = ~[ tydesc.tydesc ];
602 for &ptr in ptrs.iter() {
606 let tbl = C_struct(components);
607 let vtable = ccx.sess.str_of(gensym_name("vtable"));
608 let vt_gvar = do vtable.to_c_str().with_ref |buf| {
609 llvm::LLVMAddGlobal(ccx.llmod, val_ty(tbl).to_ref(), buf)
611 llvm::LLVMSetInitializer(vt_gvar, tbl);
612 llvm::LLVMSetGlobalConstant(vt_gvar, lib::llvm::True);
613 lib::llvm::SetLinkage(vt_gvar, lib::llvm::InternalLinkage);
618 /// Generates a dynamic vtable for objects.
619 pub fn make_impl_vtable(bcx: @mut Block,
620 impl_id: ast::def_id,
623 vtables: typeck::vtable_res)
626 let _icx = push_ctxt("impl::make_impl_vtable");
629 let trt_id = match ty::impl_trait_ref(tcx, impl_id) {
630 Some(t_id) => t_id.def_id,
631 None => ccx.sess.bug("make_impl_vtable: don't know how to \
632 make a vtable for a type impl!")
635 let trait_method_def_ids = ty::trait_method_def_ids(tcx, trt_id);
636 let methods = do trait_method_def_ids.map |method_def_id| {
637 let im = ty::method(tcx, *method_def_id);
638 let fty = ty::subst_tps(tcx,
641 ty::mk_bare_fn(tcx, im.fty.clone()));
642 if im.generics.has_type_params() || ty::type_has_self(fty) {
643 debug!("(making impl vtable) method has self or type params: %s",
644 tcx.sess.str_of(im.ident));
645 C_null(Type::nil().ptr_to())
647 debug!("(making impl vtable) adding method to vtable: %s",
648 tcx.sess.str_of(im.ident));
649 let m_id = method_with_name(ccx, impl_id, im.ident);
651 trans_fn_ref_with_vtables(bcx, m_id, 0,
652 substs, Some(vtables)).llfn
656 // Generate a type descriptor for the vtable.
657 let tydesc = get_tydesc(ccx, self_ty);
658 glue::lazily_emit_all_tydesc_glue(ccx, tydesc);
660 make_vtable(ccx, tydesc, methods)
663 pub fn trans_trait_cast(bcx: @mut Block,
667 _store: ty::TraitStore)
670 let _icx = push_ctxt("impl::trans_cast");
672 let lldest = match dest {
674 return expr::trans_into(bcx, val, Ignore);
680 let v_ty = expr_ty(bcx, val);
682 let mut llboxdest = GEPi(bcx, lldest, [0u, abi::trt_field_box]);
683 // Just store the pointer into the pair. (Region/borrowed
684 // and boxed trait objects are represented as pairs, and
685 // have no type descriptor field.)
686 llboxdest = PointerCast(bcx,
688 type_of(bcx.ccx(), v_ty).ptr_to());
689 bcx = expr::trans_into(bcx, val, SaveIn(llboxdest));
691 // Store the vtable into the pair or triple.
692 let orig = ccx.maps.vtable_map.get(&id)[0][0].clone();
693 let orig = resolve_vtable_in_fn_ctxt(bcx.fcx, &orig);
694 let vtable = get_vtable(bcx, v_ty, orig);
695 Store(bcx, vtable, PointerCast(bcx,
696 GEPi(bcx, lldest, [0u, abi::trt_field_vtable]),
697 val_ty(vtable).ptr_to()));