]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/meth.rs
4ddba0ee83944298f43c82c1a3f270efaff85ba7
[rust.git] / src / librustc / middle / trans / meth.rs
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.
4 //
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.
10
11
12 use back::abi;
13 use llvm;
14 use llvm::ValueRef;
15 use metadata::csearch;
16 use middle::subst::{Subst,Substs};
17 use middle::subst::VecPerParamSpace;
18 use middle::subst;
19 use middle::traits;
20 use middle::trans::base::*;
21 use middle::trans::build::*;
22 use middle::trans::callee::*;
23 use middle::trans::callee;
24 use middle::trans::cleanup;
25 use middle::trans::common::*;
26 use middle::trans::datum::*;
27 use middle::trans::expr::{SaveIn, Ignore};
28 use middle::trans::expr;
29 use middle::trans::glue;
30 use middle::trans::machine;
31 use middle::trans::type_::Type;
32 use middle::trans::type_of::*;
33 use middle::ty;
34 use middle::typeck;
35 use middle::typeck::MethodCall;
36 use util::ppaux::Repr;
37
38 use std::c_str::ToCStr;
39 use std::rc::Rc;
40 use syntax::abi::{Rust, RustCall};
41 use syntax::parse::token;
42 use syntax::{ast, ast_map, attr, visit};
43 use syntax::ast_util::PostExpansionMethod;
44 use syntax::codemap::DUMMY_SP;
45
46 // drop_glue pointer, size, align.
47 static VTABLE_OFFSET: uint = 3;
48
49 /**
50 The main "translation" pass for methods.  Generates code
51 for non-monomorphized methods only.  Other methods will
52 be generated once they are invoked with specific type parameters,
53 see `trans::base::lval_static_fn()` or `trans::base::monomorphic_fn()`.
54 */
55 pub fn trans_impl(ccx: &CrateContext,
56                   name: ast::Ident,
57                   impl_items: &[ast::ImplItem],
58                   generics: &ast::Generics,
59                   id: ast::NodeId) {
60     let _icx = push_ctxt("meth::trans_impl");
61     let tcx = ccx.tcx();
62
63     debug!("trans_impl(name={}, id={})", name.repr(tcx), id);
64
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() {
68         let mut v = TransItemVisitor{ ccx: ccx };
69         for impl_item in impl_items.iter() {
70             match *impl_item {
71                 ast::MethodImplItem(ref method) => {
72                     visit::walk_method_helper(&mut v, &**method);
73                 }
74                 ast::TypeImplItem(_) => {}
75             }
76         }
77         return;
78     }
79     for impl_item in impl_items.iter() {
80         match *impl_item {
81             ast::MethodImplItem(ref method) => {
82                 if method.pe_generics().ty_params.len() == 0u {
83                     let trans_everywhere = attr::requests_inline(method.attrs.as_slice());
84                     for (ref ccx, is_origin) in ccx.maybe_iter(trans_everywhere) {
85                         let llfn = get_item_val(ccx, method.id);
86                         trans_fn(ccx,
87                                  method.pe_fn_decl(),
88                                  method.pe_body(),
89                                  llfn,
90                                  &param_substs::empty(),
91                                  method.id,
92                                  []);
93                         update_linkage(ccx,
94                                        llfn,
95                                        Some(method.id),
96                                        if is_origin { OriginalTranslation } else { InlinedCopy });
97                     }
98                 }
99                 let mut v = TransItemVisitor {
100                     ccx: ccx,
101                 };
102                 visit::walk_method_helper(&mut v, &**method);
103             }
104             ast::TypeImplItem(_) => {}
105         }
106     }
107 }
108
109 pub fn trans_method_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
110                                        method_call: MethodCall,
111                                        self_expr: Option<&ast::Expr>,
112                                        arg_cleanup_scope: cleanup::ScopeId)
113                                        -> Callee<'blk, 'tcx> {
114     let _icx = push_ctxt("meth::trans_method_callee");
115
116     let (origin, method_ty) =
117         bcx.tcx().method_map
118                  .borrow()
119                  .get(&method_call)
120                  .map(|method| (method.origin.clone(), method.ty))
121                  .unwrap();
122
123     match origin {
124         typeck::MethodStatic(did) |
125         typeck::MethodStaticUnboxedClosure(did) => {
126             Callee {
127                 bcx: bcx,
128                 data: Fn(callee::trans_fn_ref(bcx,
129                                               did,
130                                               MethodCall(method_call))),
131             }
132         }
133
134         typeck::MethodTypeParam(typeck::MethodParam {
135             ref trait_ref,
136             method_num
137         }) => {
138             let trait_ref =
139                 Rc::new(trait_ref.subst(bcx.tcx(),
140                                         &bcx.fcx.param_substs.substs));
141             let span = bcx.tcx().map.span(method_call.expr_id);
142             let origin = fulfill_obligation(bcx.ccx(),
143                                             span,
144                                             (*trait_ref).clone());
145             debug!("origin = {}", origin.repr(bcx.tcx()));
146             trans_monomorphized_callee(bcx, method_call, trait_ref.def_id,
147                                        method_num, origin)
148         }
149
150         typeck::MethodTraitObject(ref mt) => {
151             let self_expr = match self_expr {
152                 Some(self_expr) => self_expr,
153                 None => {
154                     bcx.sess().span_bug(bcx.tcx().map.span(method_call.expr_id),
155                                         "self expr wasn't provided for trait object \
156                                          callee (trying to call overloaded op?)")
157                 }
158             };
159             trans_trait_callee(bcx,
160                                monomorphize_type(bcx, method_ty),
161                                mt.real_index,
162                                self_expr,
163                                arg_cleanup_scope)
164         }
165     }
166 }
167
168 pub fn trans_static_method_callee(bcx: Block,
169                                   method_id: ast::DefId,
170                                   trait_id: ast::DefId,
171                                   expr_id: ast::NodeId)
172                                   -> ValueRef
173 {
174     let _icx = push_ctxt("meth::trans_static_method_callee");
175     let ccx = bcx.ccx();
176
177     debug!("trans_static_method_callee(method_id={}, trait_id={}, \
178             expr_id={})",
179            method_id,
180            ty::item_path_str(bcx.tcx(), trait_id),
181            expr_id);
182
183     let mname = if method_id.krate == ast::LOCAL_CRATE {
184         match bcx.tcx().map.get(method_id.node) {
185             ast_map::NodeTraitItem(method) => {
186                 let ident = match *method {
187                     ast::RequiredMethod(ref m) => m.ident,
188                     ast::ProvidedMethod(ref m) => m.pe_ident(),
189                     ast::TypeTraitItem(_) => {
190                         bcx.tcx().sess.bug("trans_static_method_callee() on \
191                                             an associated type?!")
192                     }
193                 };
194                 ident.name
195             }
196             _ => panic!("callee is not a trait method")
197         }
198     } else {
199         csearch::get_item_path(bcx.tcx(), method_id).last().unwrap().name()
200     };
201     debug!("trans_static_method_callee: method_id={}, expr_id={}, \
202             name={}", method_id, expr_id, token::get_name(mname));
203
204     // Find the substitutions for the fn itself. This includes
205     // type parameters that belong to the trait but also some that
206     // belong to the method:
207     let rcvr_substs = node_id_substs(bcx, ExprId(expr_id));
208     let subst::SeparateVecsPerParamSpace {
209         types: rcvr_type,
210         selfs: rcvr_self,
211         assocs: rcvr_assoc,
212         fns: rcvr_method
213     } = rcvr_substs.types.split();
214
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:
220     //
221     //     trait Convert {
222     //         fn from<U:Foo>(n: U) -> Option<Self>;
223     //     }
224     //     ...
225     //     let f = <Vec<int> as Convert>::from::<String>(...)
226     //
227     // Here, in this call, which I've written with explicit UFCS
228     // notation, the set of type parameters will be:
229     //
230     //     rcvr_type: [] <-- nothing declared on the trait itself
231     //     rcvr_self: [Vec<int>] <-- the self type
232     //     rcvr_method: [String] <-- method type parameter
233     //
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.
237     let trait_substs =
238         Substs::erased(VecPerParamSpace::new(rcvr_type,
239                                              rcvr_self,
240                                              rcvr_assoc,
241                                              Vec::new()));
242     debug!("trait_substs={}", trait_substs.repr(bcx.tcx()));
243     let trait_ref = Rc::new(ty::TraitRef { def_id: trait_id,
244                                            substs: trait_substs });
245     let vtbl = fulfill_obligation(bcx.ccx(),
246                                   DUMMY_SP,
247                                   trait_ref);
248
249     // Now that we know which impl is being used, we can dispatch to
250     // the actual function:
251     match vtbl {
252         traits::VtableImpl(traits::VtableImplData {
253             impl_def_id: impl_did,
254             substs: impl_substs,
255             nested: _ }) =>
256         {
257             assert!(impl_substs.types.all(|t| !ty::type_needs_infer(*t)));
258
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:
262             //
263             //    impl<T> Convert for Vec<T> {
264             //        fn from<U:Foo>(n: U) { ... }
265             //    }
266             //
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 {
275                 types: impl_type,
276                 selfs: impl_self,
277                 assocs: impl_assoc,
278                 fns: _
279             } = impl_substs.types.split();
280             let callee_substs =
281                 Substs::erased(VecPerParamSpace::new(impl_type,
282                                                      impl_self,
283                                                      impl_assoc,
284                                                      rcvr_method));
285
286             let mth_id = method_with_name(ccx, impl_did, mname);
287             let llfn = trans_fn_ref_with_substs(bcx, mth_id, ExprId(expr_id),
288                                                 callee_substs);
289
290             let callee_ty = node_id_type(bcx, expr_id);
291             let llty = type_of_fn_from_ty(ccx, callee_ty).ptr_to();
292             PointerCast(bcx, llfn, llty)
293         }
294         _ => {
295             bcx.tcx().sess.bug(
296                 format!("static call to invalid vtable: {}",
297                         vtbl.repr(bcx.tcx())).as_slice());
298         }
299     }
300 }
301
302 fn method_with_name(ccx: &CrateContext, impl_id: ast::DefId, name: ast::Name)
303                     -> ast::DefId {
304     match ccx.impl_method_cache().borrow().find_copy(&(impl_id, name)) {
305         Some(m) => return m,
306         None => {}
307     }
308
309     let impl_items = ccx.tcx().impl_items.borrow();
310     let impl_items =
311         impl_items.get(&impl_id)
312                   .expect("could not find impl while translating");
313     let meth_did = impl_items.iter()
314                              .find(|&did| {
315                                 ty::impl_or_trait_item(ccx.tcx(), did.def_id()).name() == name
316                              }).expect("could not find method while \
317                                         translating");
318
319     ccx.impl_method_cache().borrow_mut().insert((impl_id, name),
320                                               meth_did.def_id());
321     meth_did.def_id()
322 }
323
324 fn trans_monomorphized_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
325                                           method_call: MethodCall,
326                                           trait_id: ast::DefId,
327                                           n_method: uint,
328                                           vtable: traits::Vtable<()>)
329                                           -> Callee<'blk, 'tcx> {
330     let _icx = push_ctxt("meth::trans_monomorphized_callee");
331     match vtable {
332         traits::VtableImpl(vtable_impl) => {
333             let ccx = bcx.ccx();
334             let impl_did = vtable_impl.impl_def_id;
335             let mname = match ty::trait_item(ccx.tcx(), trait_id, n_method) {
336                 ty::MethodTraitItem(method) => method.name,
337                 ty::TypeTraitItem(_) => {
338                     bcx.tcx().sess.bug("can't monomorphize an associated \
339                                         type")
340                 }
341             };
342             let mth_id = method_with_name(bcx.ccx(), impl_did, mname);
343
344             // create a concatenated set of substitutions which includes
345             // those from the impl and those from the method:
346             let callee_substs =
347                 combine_impl_and_methods_tps(
348                     bcx, MethodCall(method_call), vtable_impl.substs);
349
350             // translate the function
351             let llfn = trans_fn_ref_with_substs(bcx,
352                                                 mth_id,
353                                                 MethodCall(method_call),
354                                                 callee_substs);
355
356             Callee { bcx: bcx, data: Fn(llfn) }
357         }
358         traits::VtableUnboxedClosure(closure_def_id, substs) => {
359             // The substitutions should have no type parameters remaining
360             // after passing through fulfill_obligation
361             let llfn = trans_fn_ref_with_substs(bcx,
362                                                 closure_def_id,
363                                                 MethodCall(method_call),
364                                                 substs);
365
366             Callee {
367                 bcx: bcx,
368                 data: Fn(llfn),
369             }
370         }
371         _ => {
372             bcx.tcx().sess.bug(
373                 "vtable_param left in monomorphized function's vtable substs");
374         }
375     }
376 }
377
378 fn combine_impl_and_methods_tps(bcx: Block,
379                                 node: ExprOrMethodCall,
380                                 rcvr_substs: subst::Substs)
381                                 -> subst::Substs
382 {
383     /*!
384      * Creates a concatenated set of substitutions which includes
385      * those from the impl and those from the method.  This are
386      * some subtle complications here.  Statically, we have a list
387      * of type parameters like `[T0, T1, T2, M1, M2, M3]` where
388      * `Tn` are type parameters that appear on the receiver.  For
389      * example, if the receiver is a method parameter `A` with a
390      * bound like `trait<B,C,D>` then `Tn` would be `[B,C,D]`.
391      *
392      * The weird part is that the type `A` might now be bound to
393      * any other type, such as `foo<X>`.  In that case, the vector
394      * we want is: `[X, M1, M2, M3]`.  Therefore, what we do now is
395      * to slice off the method type parameters and append them to
396      * the type parameters from the type that the receiver is
397      * mapped to.
398      */
399
400     let ccx = bcx.ccx();
401
402     let node_substs = node_id_substs(bcx, node);
403
404     debug!("rcvr_substs={}", rcvr_substs.repr(ccx.tcx()));
405     debug!("node_substs={}", node_substs.repr(ccx.tcx()));
406
407     // Break apart the type parameters from the node and type
408     // parameters from the receiver.
409     let node_method = node_substs.types.split().fns;
410     let subst::SeparateVecsPerParamSpace {
411         types: rcvr_type,
412         selfs: rcvr_self,
413         assocs: rcvr_assoc,
414         fns: rcvr_method
415     } = rcvr_substs.types.clone().split();
416     assert!(rcvr_method.is_empty());
417     subst::Substs {
418         regions: subst::ErasedRegions,
419         types: subst::VecPerParamSpace::new(rcvr_type, rcvr_self, rcvr_assoc, node_method)
420     }
421 }
422
423 fn trans_trait_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
424                                   method_ty: ty::t,
425                                   n_method: uint,
426                                   self_expr: &ast::Expr,
427                                   arg_cleanup_scope: cleanup::ScopeId)
428                                   -> Callee<'blk, 'tcx> {
429     /*!
430      * Create a method callee where the method is coming from a trait
431      * object (e.g., Box<Trait> type).  In this case, we must pull the fn
432      * pointer out of the vtable that is packaged up with the object.
433      * Objects are represented as a pair, so we first evaluate the self
434      * expression and then extract the self data and vtable out of the
435      * pair.
436      */
437
438     let _icx = push_ctxt("meth::trans_trait_callee");
439     let mut bcx = bcx;
440
441     // Translate self_datum and take ownership of the value by
442     // converting to an rvalue.
443     let self_datum = unpack_datum!(
444         bcx, expr::trans(bcx, self_expr));
445
446     let llval = if ty::type_needs_drop(bcx.tcx(), self_datum.ty) {
447         let self_datum = unpack_datum!(
448             bcx, self_datum.to_rvalue_datum(bcx, "trait_callee"));
449
450         // Convert to by-ref since `trans_trait_callee_from_llval` wants it
451         // that way.
452         let self_datum = unpack_datum!(
453             bcx, self_datum.to_ref_datum(bcx));
454
455         // Arrange cleanup in case something should go wrong before the
456         // actual call occurs.
457         self_datum.add_clean(bcx.fcx, arg_cleanup_scope)
458     } else {
459         // We don't have to do anything about cleanups for &Trait and &mut Trait.
460         assert!(self_datum.kind.is_by_ref());
461         self_datum.val
462     };
463
464     trans_trait_callee_from_llval(bcx, method_ty, n_method, llval)
465 }
466
467 pub fn trans_trait_callee_from_llval<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
468                                                  callee_ty: ty::t,
469                                                  n_method: uint,
470                                                  llpair: ValueRef)
471                                                  -> Callee<'blk, 'tcx> {
472     /*!
473      * Same as `trans_trait_callee()` above, except that it is given
474      * a by-ref pointer to the object pair.
475      */
476
477     let _icx = push_ctxt("meth::trans_trait_callee");
478     let ccx = bcx.ccx();
479
480     // Load the data pointer from the object.
481     debug!("(translating trait callee) loading second index from pair");
482     let llboxptr = GEPi(bcx, llpair, [0u, abi::trt_field_box]);
483     let llbox = Load(bcx, llboxptr);
484     let llself = PointerCast(bcx, llbox, Type::i8p(ccx));
485
486     // Load the function from the vtable and cast it to the expected type.
487     debug!("(translating trait callee) loading method");
488     // Replace the self type (&Self or Box<Self>) with an opaque pointer.
489     let llcallee_ty = match ty::get(callee_ty).sty {
490         ty::ty_bare_fn(ref f) if f.abi == Rust || f.abi == RustCall => {
491             type_of_rust_fn(ccx,
492                             Some(Type::i8p(ccx)),
493                             f.sig.inputs.slice_from(1),
494                             f.sig.output,
495                             f.abi)
496         }
497         _ => {
498             ccx.sess().bug("meth::trans_trait_callee given non-bare-rust-fn");
499         }
500     };
501     let llvtable = Load(bcx,
502                         PointerCast(bcx,
503                                     GEPi(bcx, llpair,
504                                          [0u, abi::trt_field_vtable]),
505                                     Type::vtable(ccx).ptr_to().ptr_to()));
506     let mptr = Load(bcx, GEPi(bcx, llvtable, [0u, n_method + VTABLE_OFFSET]));
507     let mptr = PointerCast(bcx, mptr, llcallee_ty.ptr_to());
508
509     return Callee {
510         bcx: bcx,
511         data: TraitItem(MethodData {
512             llfn: mptr,
513             llself: llself,
514         })
515     };
516 }
517
518 /// Creates a returns a dynamic vtable for the given type and vtable origin.
519 /// This is used only for objects.
520 ///
521 /// The `trait_ref` encodes the erased self type. Hence if we are
522 /// making an object `Foo<Trait>` from a value of type `Foo<T>`, then
523 /// `trait_ref` would map `T:Trait`, but `box_ty` would be
524 /// `Foo<T>`. This `box_ty` is primarily used to encode the destructor.
525 /// This will hopefully change now that DST is underway.
526 pub fn get_vtable(bcx: Block,
527                   box_ty: ty::t,
528                   trait_ref: Rc<ty::TraitRef>)
529                   -> ValueRef
530 {
531     debug!("get_vtable(box_ty={}, trait_ref={})",
532            box_ty.repr(bcx.tcx()),
533            trait_ref.repr(bcx.tcx()));
534
535     let tcx = bcx.tcx();
536     let ccx = bcx.ccx();
537     let _icx = push_ctxt("meth::get_vtable");
538
539     // Check the cache.
540     let cache_key = (box_ty, trait_ref.clone());
541     match ccx.vtables().borrow().get(&cache_key) {
542         Some(&val) => { return val }
543         None => { }
544     }
545
546     // Not in the cache. Build it.
547     let methods = traits::supertraits(tcx, trait_ref.clone()).flat_map(|trait_ref| {
548         let vtable = fulfill_obligation(bcx.ccx(),
549                                         DUMMY_SP,
550                                         trait_ref.clone());
551         match vtable {
552             traits::VtableBuiltin(_) => {
553                 Vec::new().into_iter()
554             }
555             traits::VtableImpl(
556                 traits::VtableImplData {
557                     impl_def_id: id,
558                     substs,
559                     nested: _ }) => {
560                 emit_vtable_methods(bcx, id, substs).into_iter()
561             }
562             traits::VtableUnboxedClosure(closure_def_id, substs) => {
563                 // Look up closure type
564                 let self_ty = ty::node_id_to_type(bcx.tcx(), closure_def_id.node);
565                 // Apply substitutions from closure param environment.
566                 // The substitutions should have no type parameters
567                 // remaining after passing through fulfill_obligation
568                 let self_ty = self_ty.subst(bcx.tcx(), &substs);
569
570                 let mut llfn = trans_fn_ref_with_substs(
571                     bcx,
572                     closure_def_id,
573                     ExprId(0),
574                     substs.clone());
575
576                 {
577                     let unboxed_closures = bcx.tcx()
578                                               .unboxed_closures
579                                               .borrow();
580                     let closure_info =
581                         unboxed_closures.get(&closure_def_id)
582                                         .expect("get_vtable(): didn't find \
583                                                  unboxed closure");
584                     if closure_info.kind == ty::FnOnceUnboxedClosureKind {
585                         // Untuple the arguments and create an unboxing shim.
586                         let (new_inputs, new_output) = match ty::get(self_ty).sty {
587                             ty::ty_unboxed_closure(_, _, ref substs) => {
588                                 let mut new_inputs = vec![self_ty.clone()];
589                                 match ty::get(closure_info.closure_type
590                                               .sig
591                                               .inputs[0]).sty {
592                                     ty::ty_tup(ref elements) => {
593                                         for element in elements.iter() {
594                                             new_inputs.push(element.subst(bcx.tcx(), substs));
595                                         }
596                                     }
597                                     ty::ty_nil => {}
598                                     _ => {
599                                         bcx.tcx().sess.bug("get_vtable(): closure \
600                                                             type wasn't a tuple")
601                                     }
602                                 }
603                                 (new_inputs,
604                                  closure_info.closure_type.sig.output.subst(bcx.tcx(), substs))
605                             },
606                             _ => bcx.tcx().sess.bug("get_vtable(): def wasn't an unboxed closure")
607                         };
608
609                         let closure_type = ty::BareFnTy {
610                             fn_style: closure_info.closure_type.fn_style,
611                             abi: Rust,
612                             sig: ty::FnSig {
613                                 binder_id: closure_info.closure_type
614                                                        .sig
615                                                        .binder_id,
616                                 inputs: new_inputs,
617                                 output: new_output,
618                                 variadic: false,
619                             },
620                         };
621                         debug!("get_vtable(): closure type is {}",
622                                closure_type.repr(bcx.tcx()));
623                         llfn = trans_unboxing_shim(bcx,
624                                                    llfn,
625                                                    &closure_type,
626                                                    closure_def_id,
627                                                    substs);
628                     }
629                 }
630
631                 (vec!(llfn)).into_iter()
632             }
633             traits::VtableParam(..) => {
634                 bcx.sess().bug(
635                     format!("resolved vtable for {} to bad vtable {} in trans",
636                             trait_ref.repr(bcx.tcx()),
637                             vtable.repr(bcx.tcx())).as_slice());
638             }
639         }
640     });
641
642     let size_ty = sizing_type_of(ccx, trait_ref.self_ty());
643     let size = machine::llsize_of_alloc(ccx, size_ty);
644     let ll_size = C_uint(ccx, size);
645     let align = align_of(ccx, trait_ref.self_ty());
646     let ll_align = C_uint(ccx, align);
647
648     // Generate a destructor for the vtable.
649     let drop_glue = glue::get_drop_glue(ccx, box_ty);
650     let vtable = make_vtable(ccx, drop_glue, ll_size, ll_align, methods);
651
652     ccx.vtables().borrow_mut().insert(cache_key, vtable);
653     vtable
654 }
655
656 /// Helper function to declare and initialize the vtable.
657 pub fn make_vtable<I: Iterator<ValueRef>>(ccx: &CrateContext,
658                                           drop_glue: ValueRef,
659                                           size: ValueRef,
660                                           align: ValueRef,
661                                           ptrs: I)
662                                           -> ValueRef {
663     let _icx = push_ctxt("meth::make_vtable");
664
665     let head = vec![drop_glue, size, align];
666     let components: Vec<_> = head.into_iter().chain(ptrs).collect();
667
668     unsafe {
669         let tbl = C_struct(ccx, components.as_slice(), false);
670         let sym = token::gensym("vtable");
671         let vt_gvar = format!("vtable{}", sym.uint()).with_c_str(|buf| {
672             llvm::LLVMAddGlobal(ccx.llmod(), val_ty(tbl).to_ref(), buf)
673         });
674         llvm::LLVMSetInitializer(vt_gvar, tbl);
675         llvm::LLVMSetGlobalConstant(vt_gvar, llvm::True);
676         llvm::SetLinkage(vt_gvar, llvm::InternalLinkage);
677         vt_gvar
678     }
679 }
680
681 fn emit_vtable_methods(bcx: Block,
682                        impl_id: ast::DefId,
683                        substs: subst::Substs)
684                        -> Vec<ValueRef> {
685     let ccx = bcx.ccx();
686     let tcx = ccx.tcx();
687
688     let trt_id = match ty::impl_trait_ref(tcx, impl_id) {
689         Some(t_id) => t_id.def_id,
690         None       => ccx.sess().bug("make_impl_vtable: don't know how to \
691                                       make a vtable for a type impl!")
692     };
693
694     ty::populate_implementations_for_trait_if_necessary(bcx.tcx(), trt_id);
695
696     let trait_item_def_ids = ty::trait_item_def_ids(tcx, trt_id);
697     trait_item_def_ids.iter().flat_map(|method_def_id| {
698         let method_def_id = method_def_id.def_id();
699         let name = ty::impl_or_trait_item(tcx, method_def_id).name();
700         // The substitutions we have are on the impl, so we grab
701         // the method type from the impl to substitute into.
702         let m_id = method_with_name(ccx, impl_id, name);
703         let ti = ty::impl_or_trait_item(tcx, m_id);
704         match ti {
705             ty::MethodTraitItem(m) => {
706                 debug!("(making impl vtable) emitting method {} at subst {}",
707                        m.repr(tcx),
708                        substs.repr(tcx));
709                 if m.generics.has_type_params(subst::FnSpace) ||
710                    ty::type_has_self(ty::mk_bare_fn(tcx, m.fty.clone())) {
711                     debug!("(making impl vtable) method has self or type \
712                             params: {}",
713                            token::get_name(name));
714                     Some(C_null(Type::nil(ccx).ptr_to())).into_iter()
715                 } else {
716                     let mut fn_ref = trans_fn_ref_with_substs(
717                         bcx,
718                         m_id,
719                         ExprId(0),
720                         substs.clone());
721                     if m.explicit_self == ty::ByValueExplicitSelfCategory {
722                         fn_ref = trans_unboxing_shim(bcx,
723                                                      fn_ref,
724                                                      &m.fty,
725                                                      m_id,
726                                                      substs.clone());
727                     }
728                     Some(fn_ref).into_iter()
729                 }
730             }
731             ty::TypeTraitItem(_) => {
732                 None.into_iter()
733             }
734         }
735     }).collect()
736 }
737
738 pub fn trans_trait_cast<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
739                                     datum: Datum<Expr>,
740                                     id: ast::NodeId,
741                                     trait_ref: Rc<ty::TraitRef>,
742                                     dest: expr::Dest)
743                                     -> Block<'blk, 'tcx> {
744     /*!
745      * Generates the code to convert from a pointer (`Box<T>`, `&T`, etc)
746      * into an object (`Box<Trait>`, `&Trait`, etc). This means creating a
747      * pair where the first word is the vtable and the second word is
748      * the pointer.
749      */
750
751     let mut bcx = bcx;
752     let _icx = push_ctxt("meth::trans_trait_cast");
753
754     let lldest = match dest {
755         Ignore => {
756             return datum.clean(bcx, "trait_trait_cast", id);
757         }
758         SaveIn(dest) => dest
759     };
760
761     debug!("trans_trait_cast: trait_ref={}",
762            trait_ref.repr(bcx.tcx()));
763
764     let datum_ty = datum.ty;
765     let llbox_ty = type_of(bcx.ccx(), datum_ty);
766
767     // Store the pointer into the first half of pair.
768     let llboxdest = GEPi(bcx, lldest, [0u, abi::trt_field_box]);
769     let llboxdest = PointerCast(bcx, llboxdest, llbox_ty.ptr_to());
770     bcx = datum.store_to(bcx, llboxdest);
771
772     // Store the vtable into the second half of pair.
773     let vtable = get_vtable(bcx, datum_ty, trait_ref);
774     let llvtabledest = GEPi(bcx, lldest, [0u, abi::trt_field_vtable]);
775     let llvtabledest = PointerCast(bcx, llvtabledest, val_ty(vtable).ptr_to());
776     Store(bcx, vtable, llvtabledest);
777
778     bcx
779 }