]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/meth.rs
Remove unused imports
[rust.git] / src / librustc_trans / 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 use arena::TypedArena;
12 use back::link;
13 use llvm::{ValueRef, get_params};
14 use middle::def_id::DefId;
15 use middle::infer;
16 use middle::subst::{Subst, Substs};
17 use middle::subst::VecPerParamSpace;
18 use middle::subst;
19 use middle::traits;
20 use trans::base::*;
21 use trans::build::*;
22 use trans::callee::*;
23 use trans::callee;
24 use trans::cleanup;
25 use trans::closure;
26 use trans::common::*;
27 use trans::consts;
28 use trans::datum::*;
29 use trans::debuginfo::DebugLoc;
30 use trans::declare;
31 use trans::expr;
32 use trans::glue;
33 use trans::machine;
34 use trans::monomorphize;
35 use trans::type_::Type;
36 use trans::type_of::*;
37 use middle::ty::{self, Ty, HasTypeFlags};
38 use middle::ty::MethodCall;
39
40 use syntax::ast;
41 use syntax::attr;
42 use syntax::codemap::DUMMY_SP;
43
44 use rustc_front::hir;
45
46 // drop_glue pointer, size, align.
47 const VTABLE_OFFSET: usize = 3;
48
49 /// The main "translation" pass for methods.  Generates code
50 /// for non-monomorphized methods only.  Other methods will
51 /// be generated once they are invoked with specific type parameters,
52 /// see `trans::base::lval_static_fn()` or `trans::base::monomorphic_fn()`.
53 pub fn trans_impl(ccx: &CrateContext,
54                   name: ast::Name,
55                   impl_items: &[hir::ImplItem],
56                   generics: &hir::Generics,
57                   id: ast::NodeId) {
58     let _icx = push_ctxt("meth::trans_impl");
59     let tcx = ccx.tcx();
60
61     debug!("trans_impl(name={}, id={})", name, id);
62
63     // Both here and below with generic methods, be sure to recurse and look for
64     // items that we need to translate.
65     if !generics.ty_params.is_empty() {
66         return;
67     }
68
69     for impl_item in impl_items {
70         match impl_item.node {
71             hir::ImplItemKind::Method(ref sig, ref body) => {
72                 if sig.generics.ty_params.is_empty() {
73                     let trans_everywhere = attr::requests_inline(&impl_item.attrs);
74                     for (ref ccx, is_origin) in ccx.maybe_iter(trans_everywhere) {
75                         let llfn = get_item_val(ccx, impl_item.id);
76                         let empty_substs = tcx.mk_substs(Substs::trans_empty());
77                         trans_fn(ccx, &sig.decl, body, llfn,
78                                  empty_substs, impl_item.id, &[]);
79                         update_linkage(ccx,
80                                        llfn,
81                                        Some(impl_item.id),
82                                        if is_origin { OriginalTranslation } else { InlinedCopy });
83                     }
84                 }
85             }
86             _ => {}
87         }
88     }
89 }
90
91 pub fn trans_method_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
92                                        method_call: MethodCall,
93                                        self_expr: Option<&hir::Expr>,
94                                        arg_cleanup_scope: cleanup::ScopeId)
95                                        -> Callee<'blk, 'tcx> {
96     let _icx = push_ctxt("meth::trans_method_callee");
97
98     let method = bcx.tcx().tables.borrow().method_map[&method_call];
99
100     match bcx.tcx().impl_or_trait_item(method.def_id).container() {
101         ty::ImplContainer(_) => {
102             debug!("trans_method_callee: static, {:?}", method.def_id);
103             let datum = callee::trans_fn_ref(bcx.ccx(),
104                                              method.def_id,
105                                              MethodCallKey(method_call),
106                                              bcx.fcx.param_substs);
107             Callee {
108                 bcx: bcx,
109                 data: Fn(datum.val),
110                 ty: datum.ty
111             }
112         }
113
114         ty::TraitContainer(trait_def_id) => {
115             let trait_substs = method.substs.clone().method_to_trait();
116             let trait_substs = bcx.tcx().mk_substs(trait_substs);
117             let trait_ref = ty::TraitRef::new(trait_def_id, trait_substs);
118
119             let trait_ref = ty::Binder(bcx.monomorphize(&trait_ref));
120             let span = bcx.tcx().map.span(method_call.expr_id);
121             debug!("method_call={:?} trait_ref={:?} trait_ref id={:?} substs={:?}",
122                    method_call,
123                    trait_ref,
124                    trait_ref.0.def_id,
125                    trait_ref.0.substs);
126             let origin = fulfill_obligation(bcx.ccx(),
127                                             span,
128                                             trait_ref.clone());
129             debug!("origin = {:?}", origin);
130             trans_monomorphized_callee(bcx,
131                                        method_call,
132                                        self_expr,
133                                        trait_def_id,
134                                        method.def_id,
135                                        method.ty,
136                                        origin,
137                                        arg_cleanup_scope)
138         }
139     }
140 }
141
142 pub fn trans_static_method_callee<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
143                                             method_id: DefId,
144                                             trait_id: DefId,
145                                             expr_id: ast::NodeId,
146                                             param_substs: &'tcx subst::Substs<'tcx>)
147                                             -> Datum<'tcx, Rvalue>
148 {
149     let _icx = push_ctxt("meth::trans_static_method_callee");
150     let tcx = ccx.tcx();
151
152     debug!("trans_static_method_callee(method_id={:?}, trait_id={}, \
153             expr_id={})",
154            method_id,
155            tcx.item_path_str(trait_id),
156            expr_id);
157
158     let mname = tcx.item_name(method_id);
159
160     debug!("trans_static_method_callee: method_id={:?}, expr_id={}, \
161             name={}", method_id, expr_id, mname);
162
163     // Find the substitutions for the fn itself. This includes
164     // type parameters that belong to the trait but also some that
165     // belong to the method:
166     let rcvr_substs = node_id_substs(ccx, ExprId(expr_id), param_substs);
167     let subst::SeparateVecsPerParamSpace {
168         types: rcvr_type,
169         selfs: rcvr_self,
170         fns: rcvr_method
171     } = rcvr_substs.types.split();
172
173     // Lookup the precise impl being called. To do that, we need to
174     // create a trait reference identifying the self type and other
175     // input type parameters. To create that trait reference, we have
176     // to pick apart the type parameters to identify just those that
177     // pertain to the trait. This is easiest to explain by example:
178     //
179     //     trait Convert {
180     //         fn from<U:Foo>(n: U) -> Option<Self>;
181     //     }
182     //     ...
183     //     let f = <Vec<i32> as Convert>::from::<String>(...)
184     //
185     // Here, in this call, which I've written with explicit UFCS
186     // notation, the set of type parameters will be:
187     //
188     //     rcvr_type: [] <-- nothing declared on the trait itself
189     //     rcvr_self: [Vec<i32>] <-- the self type
190     //     rcvr_method: [String] <-- method type parameter
191     //
192     // So we create a trait reference using the first two,
193     // basically corresponding to `<Vec<i32> as Convert>`.
194     // The remaining type parameters (`rcvr_method`) will be used below.
195     let trait_substs =
196         Substs::erased(VecPerParamSpace::new(rcvr_type,
197                                              rcvr_self,
198                                              Vec::new()));
199     let trait_substs = tcx.mk_substs(trait_substs);
200     debug!("trait_substs={:?}", trait_substs);
201     let trait_ref = ty::Binder(ty::TraitRef::new(trait_id, trait_substs));
202     let vtbl = fulfill_obligation(ccx,
203                                   DUMMY_SP,
204                                   trait_ref);
205
206     // Now that we know which impl is being used, we can dispatch to
207     // the actual function:
208     match vtbl {
209         traits::VtableImpl(traits::VtableImplData {
210             impl_def_id: impl_did,
211             substs: impl_substs,
212             nested: _ }) =>
213         {
214             assert!(!impl_substs.types.needs_infer());
215
216             // Create the substitutions that are in scope. This combines
217             // the type parameters from the impl with those declared earlier.
218             // To see what I mean, consider a possible impl:
219             //
220             //    impl<T> Convert for Vec<T> {
221             //        fn from<U:Foo>(n: U) { ... }
222             //    }
223             //
224             // Recall that we matched `<Vec<i32> as Convert>`. Trait
225             // resolution will have given us a substitution
226             // containing `impl_substs=[[T=i32],[],[]]` (the type
227             // parameters defined on the impl). We combine
228             // that with the `rcvr_method` from before, which tells us
229             // the type parameters from the *method*, to yield
230             // `callee_substs=[[T=i32],[],[U=String]]`.
231             let subst::SeparateVecsPerParamSpace {
232                 types: impl_type,
233                 selfs: impl_self,
234                 fns: _
235             } = impl_substs.types.split();
236             let callee_substs =
237                 Substs::erased(VecPerParamSpace::new(impl_type,
238                                                      impl_self,
239                                                      rcvr_method));
240
241             let mth = tcx.get_impl_method(impl_did, callee_substs, mname);
242             trans_fn_ref_with_substs(ccx, mth.method.def_id, ExprId(expr_id),
243                                      param_substs,
244                                      mth.substs)
245         }
246         traits::VtableObject(ref data) => {
247             let idx = traits::get_vtable_index_of_object_method(tcx, data, method_id);
248             trans_object_shim(ccx,
249                               data.upcast_trait_ref.clone(),
250                               method_id,
251                               idx)
252         }
253         _ => {
254             tcx.sess.bug(&format!("static call to invalid vtable: {:?}",
255                                  vtbl));
256         }
257     }
258 }
259
260 fn trans_monomorphized_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
261                                           method_call: MethodCall,
262                                           self_expr: Option<&hir::Expr>,
263                                           trait_id: DefId,
264                                           method_id: DefId,
265                                           method_ty: Ty<'tcx>,
266                                           vtable: traits::Vtable<'tcx, ()>,
267                                           arg_cleanup_scope: cleanup::ScopeId)
268                                           -> Callee<'blk, 'tcx> {
269     let _icx = push_ctxt("meth::trans_monomorphized_callee");
270     match vtable {
271         traits::VtableImpl(vtable_impl) => {
272             let ccx = bcx.ccx();
273             let impl_did = vtable_impl.impl_def_id;
274             let mname = match ccx.tcx().impl_or_trait_item(method_id) {
275                 ty::MethodTraitItem(method) => method.name,
276                 _ => {
277                     bcx.tcx().sess.bug("can't monomorphize a non-method trait \
278                                         item")
279                 }
280             };
281             // create a concatenated set of substitutions which includes
282             // those from the impl and those from the method:
283             let callee_substs =
284                 combine_impl_and_methods_tps(
285                     bcx, MethodCallKey(method_call), vtable_impl.substs);
286
287             let mth = bcx.tcx().get_impl_method(impl_did, callee_substs, mname);
288             // translate the function
289             let datum = trans_fn_ref_with_substs(bcx.ccx(),
290                                                  mth.method.def_id,
291                                                  MethodCallKey(method_call),
292                                                  bcx.fcx.param_substs,
293                                                  mth.substs);
294
295             Callee { bcx: bcx, data: Fn(datum.val), ty: datum.ty }
296         }
297         traits::VtableClosure(vtable_closure) => {
298             // The substitutions should have no type parameters remaining
299             // after passing through fulfill_obligation
300             let trait_closure_kind = bcx.tcx().lang_items.fn_trait_kind(trait_id).unwrap();
301             let llfn = closure::trans_closure_method(bcx.ccx(),
302                                                      vtable_closure.closure_def_id,
303                                                      vtable_closure.substs,
304                                                      trait_closure_kind);
305             Callee {
306                 bcx: bcx,
307                 data: Fn(llfn),
308                 ty: monomorphize_type(bcx, method_ty)
309             }
310         }
311         traits::VtableFnPointer(fn_ty) => {
312             let trait_closure_kind = bcx.tcx().lang_items.fn_trait_kind(trait_id).unwrap();
313             let llfn = trans_fn_pointer_shim(bcx.ccx(), trait_closure_kind, fn_ty);
314             Callee {
315                 bcx: bcx,
316                 data: Fn(llfn),
317                 ty: monomorphize_type(bcx, method_ty)
318             }
319         }
320         traits::VtableObject(ref data) => {
321             let idx = traits::get_vtable_index_of_object_method(bcx.tcx(), data, method_id);
322             if let Some(self_expr) = self_expr {
323                 if let ty::TyBareFn(_, ref fty) = monomorphize_type(bcx, method_ty).sty {
324                     let ty = bcx.tcx().mk_fn(None, opaque_method_ty(bcx.tcx(), fty));
325                     return trans_trait_callee(bcx, ty, idx, self_expr, arg_cleanup_scope);
326                 }
327             }
328             let datum = trans_object_shim(bcx.ccx(),
329                                           data.upcast_trait_ref.clone(),
330                                           method_id,
331                                           idx);
332             Callee { bcx: bcx, data: Fn(datum.val), ty: datum.ty }
333         }
334         traits::VtableBuiltin(..) |
335         traits::VtableDefaultImpl(..) |
336         traits::VtableParam(..) => {
337             bcx.sess().bug(
338                 &format!("resolved vtable bad vtable {:?} in trans",
339                         vtable));
340         }
341     }
342 }
343
344  /// Creates a concatenated set of substitutions which includes those from the impl and those from
345  /// the method.  This are some subtle complications here.  Statically, we have a list of type
346  /// parameters like `[T0, T1, T2, M1, M2, M3]` where `Tn` are type parameters that appear on the
347  /// receiver.  For example, if the receiver is a method parameter `A` with a bound like
348  /// `trait<B,C,D>` then `Tn` would be `[B,C,D]`.
349  ///
350  /// The weird part is that the type `A` might now be bound to any other type, such as `foo<X>`.
351  /// In that case, the vector we want is: `[X, M1, M2, M3]`.  Therefore, what we do now is to slice
352  /// off the method type parameters and append them to the type parameters from the type that the
353  /// receiver is mapped to.
354 fn combine_impl_and_methods_tps<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
355                                             node: ExprOrMethodCall,
356                                             rcvr_substs: subst::Substs<'tcx>)
357                                             -> subst::Substs<'tcx>
358 {
359     let ccx = bcx.ccx();
360
361     let node_substs = node_id_substs(ccx, node, bcx.fcx.param_substs);
362
363     debug!("rcvr_substs={:?}", rcvr_substs);
364     debug!("node_substs={:?}", node_substs);
365
366     // Break apart the type parameters from the node and type
367     // parameters from the receiver.
368     let node_method = node_substs.types.split().fns;
369     let subst::SeparateVecsPerParamSpace {
370         types: rcvr_type,
371         selfs: rcvr_self,
372         fns: rcvr_method
373     } = rcvr_substs.types.clone().split();
374     assert!(rcvr_method.is_empty());
375     subst::Substs {
376         regions: subst::ErasedRegions,
377         types: subst::VecPerParamSpace::new(rcvr_type, rcvr_self, node_method)
378     }
379 }
380
381 /// Create a method callee where the method is coming from a trait object (e.g., Box<Trait> type).
382 /// In this case, we must pull the fn pointer out of the vtable that is packaged up with the
383 /// object. Objects are represented as a pair, so we first evaluate the self expression and then
384 /// extract the self data and vtable out of the pair.
385 fn trans_trait_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
386                                   opaque_fn_ty: Ty<'tcx>,
387                                   vtable_index: usize,
388                                   self_expr: &hir::Expr,
389                                   arg_cleanup_scope: cleanup::ScopeId)
390                                   -> Callee<'blk, 'tcx> {
391     let _icx = push_ctxt("meth::trans_trait_callee");
392     let mut bcx = bcx;
393
394     // Translate self_datum and take ownership of the value by
395     // converting to an rvalue.
396     let self_datum = unpack_datum!(
397         bcx, expr::trans(bcx, self_expr));
398
399     let llval = if bcx.fcx.type_needs_drop(self_datum.ty) {
400         let self_datum = unpack_datum!(
401             bcx, self_datum.to_rvalue_datum(bcx, "trait_callee"));
402
403         // Convert to by-ref since `trans_trait_callee_from_llval` wants it
404         // that way.
405         let self_datum = unpack_datum!(
406             bcx, self_datum.to_ref_datum(bcx));
407
408         // Arrange cleanup in case something should go wrong before the
409         // actual call occurs.
410         self_datum.add_clean(bcx.fcx, arg_cleanup_scope)
411     } else {
412         // We don't have to do anything about cleanups for &Trait and &mut Trait.
413         assert!(self_datum.kind.is_by_ref());
414         self_datum.val
415     };
416
417     let llself = Load(bcx, expr::get_dataptr(bcx, llval));
418     let llvtable = Load(bcx, expr::get_meta(bcx, llval));
419     trans_trait_callee_from_llval(bcx, opaque_fn_ty, vtable_index, llself, llvtable)
420 }
421
422 /// Same as `trans_trait_callee()` above, except that it is given a by-ref pointer to the object
423 /// pair.
424 fn trans_trait_callee_from_llval<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
425                                              opaque_fn_ty: Ty<'tcx>,
426                                              vtable_index: usize,
427                                              llself: ValueRef,
428                                              llvtable: ValueRef)
429                                              -> Callee<'blk, 'tcx> {
430     let _icx = push_ctxt("meth::trans_trait_callee");
431     let ccx = bcx.ccx();
432
433     // Load the data pointer from the object.
434     debug!("trans_trait_callee_from_llval(callee_ty={}, vtable_index={}, llself={}, llvtable={})",
435            opaque_fn_ty,
436            vtable_index,
437            bcx.val_to_string(llself),
438            bcx.val_to_string(llvtable));
439
440     // Replace the self type (&Self or Box<Self>) with an opaque pointer.
441     let mptr = Load(bcx, GEPi(bcx, llvtable, &[vtable_index + VTABLE_OFFSET]));
442     let llcallee_ty = type_of_fn_from_ty(ccx, opaque_fn_ty);
443
444     Callee {
445         bcx: bcx,
446         data: TraitItem(MethodData {
447             llfn: PointerCast(bcx, mptr, llcallee_ty.ptr_to()),
448             llself: PointerCast(bcx, llself, Type::i8p(ccx)),
449         }),
450         ty: opaque_fn_ty
451     }
452 }
453
454 /// Generate a shim function that allows an object type like `SomeTrait` to
455 /// implement the type `SomeTrait`. Imagine a trait definition:
456 ///
457 ///    trait SomeTrait { fn get(&self) -> i32; ... }
458 ///
459 /// And a generic bit of code:
460 ///
461 ///    fn foo<T:SomeTrait>(t: &T) {
462 ///        let x = SomeTrait::get;
463 ///        x(t)
464 ///    }
465 ///
466 /// What is the value of `x` when `foo` is invoked with `T=SomeTrait`?
467 /// The answer is that it is a shim function generated by this routine:
468 ///
469 ///    fn shim(t: &SomeTrait) -> i32 {
470 ///        // ... call t.get() virtually ...
471 ///    }
472 ///
473 /// In fact, all virtual calls can be thought of as normal trait calls
474 /// that go through this shim function.
475 fn trans_object_shim<'a, 'tcx>(
476     ccx: &'a CrateContext<'a, 'tcx>,
477     upcast_trait_ref: ty::PolyTraitRef<'tcx>,
478     method_id: DefId,
479     vtable_index: usize)
480     -> Datum<'tcx, Rvalue>
481 {
482     let _icx = push_ctxt("trans_object_shim");
483     let tcx = ccx.tcx();
484
485     debug!("trans_object_shim(upcast_trait_ref={:?}, method_id={:?})",
486            upcast_trait_ref,
487            method_id);
488
489     // Upcast to the trait in question and extract out the substitutions.
490     let upcast_trait_ref = tcx.erase_late_bound_regions(&upcast_trait_ref);
491     let object_substs = upcast_trait_ref.substs.clone().erase_regions();
492     debug!("trans_object_shim: object_substs={:?}", object_substs);
493
494     // Lookup the type of this method as declared in the trait and apply substitutions.
495     let method_ty = match tcx.impl_or_trait_item(method_id) {
496         ty::MethodTraitItem(method) => method,
497         _ => {
498             tcx.sess.bug("can't create a method shim for a non-method item")
499         }
500     };
501     let fty = monomorphize::apply_param_substs(tcx, &object_substs, &method_ty.fty);
502     let fty = tcx.mk_bare_fn(fty);
503     let method_ty = opaque_method_ty(tcx, fty);
504     debug!("trans_object_shim: fty={:?} method_ty={:?}", fty, method_ty);
505
506     //
507     let shim_fn_ty = tcx.mk_fn(None, fty);
508     let method_bare_fn_ty = tcx.mk_fn(None, method_ty);
509     let function_name = link::mangle_internal_name_by_type_and_seq(ccx, shim_fn_ty, "object_shim");
510     let llfn = declare::define_internal_rust_fn(ccx, &function_name, shim_fn_ty);
511
512     let sig = ccx.tcx().erase_late_bound_regions(&fty.sig);
513     let sig = infer::normalize_associated_type(ccx.tcx(), &sig);
514
515     let empty_substs = tcx.mk_substs(Substs::trans_empty());
516     let (block_arena, fcx): (TypedArena<_>, FunctionContext);
517     block_arena = TypedArena::new();
518     fcx = new_fn_ctxt(ccx,
519                       llfn,
520                       ast::DUMMY_NODE_ID,
521                       false,
522                       sig.output,
523                       empty_substs,
524                       None,
525                       &block_arena);
526     let mut bcx = init_function(&fcx, false, sig.output);
527
528     let llargs = get_params(fcx.llfn);
529
530     let self_idx = fcx.arg_offset();
531     let llself = llargs[self_idx];
532     let llvtable = llargs[self_idx + 1];
533
534     debug!("trans_object_shim: llself={}, llvtable={}",
535            bcx.val_to_string(llself), bcx.val_to_string(llvtable));
536
537     assert!(!fcx.needs_ret_allocas);
538
539     let dest =
540         fcx.llretslotptr.get().map(
541             |_| expr::SaveIn(fcx.get_ret_slot(bcx, sig.output, "ret_slot")));
542
543     debug!("trans_object_shim: method_offset_in_vtable={}",
544            vtable_index);
545
546     bcx = trans_call_inner(bcx,
547                            DebugLoc::None,
548                            |bcx, _| trans_trait_callee_from_llval(bcx,
549                                                                   method_bare_fn_ty,
550                                                                   vtable_index,
551                                                                   llself, llvtable),
552                            ArgVals(&llargs[(self_idx + 2)..]),
553                            dest).bcx;
554
555     finish_fn(&fcx, bcx, sig.output, DebugLoc::None);
556
557     immediate_rvalue(llfn, shim_fn_ty)
558 }
559
560 /// Creates a returns a dynamic vtable for the given type and vtable origin.
561 /// This is used only for objects.
562 ///
563 /// The `trait_ref` encodes the erased self type. Hence if we are
564 /// making an object `Foo<Trait>` from a value of type `Foo<T>`, then
565 /// `trait_ref` would map `T:Trait`.
566 pub fn get_vtable<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
567                             trait_ref: ty::PolyTraitRef<'tcx>,
568                             param_substs: &'tcx subst::Substs<'tcx>)
569                             -> ValueRef
570 {
571     let tcx = ccx.tcx();
572     let _icx = push_ctxt("meth::get_vtable");
573
574     debug!("get_vtable(trait_ref={:?})", trait_ref);
575
576     // Check the cache.
577     match ccx.vtables().borrow().get(&trait_ref) {
578         Some(&val) => { return val }
579         None => { }
580     }
581
582     // Not in the cache. Build it.
583     let methods = traits::supertraits(tcx, trait_ref.clone()).flat_map(|trait_ref| {
584         let vtable = fulfill_obligation(ccx, DUMMY_SP, trait_ref.clone());
585         match vtable {
586             // Should default trait error here?
587             traits::VtableDefaultImpl(_) |
588             traits::VtableBuiltin(_) => {
589                 Vec::new().into_iter()
590             }
591             traits::VtableImpl(
592                 traits::VtableImplData {
593                     impl_def_id: id,
594                     substs,
595                     nested: _ }) => {
596                 emit_vtable_methods(ccx, id, substs, param_substs).into_iter()
597             }
598             traits::VtableClosure(
599                 traits::VtableClosureData {
600                     closure_def_id,
601                     substs,
602                     nested: _ }) => {
603                 let trait_closure_kind = tcx.lang_items.fn_trait_kind(trait_ref.def_id()).unwrap();
604                 let llfn = closure::trans_closure_method(ccx,
605                                                          closure_def_id,
606                                                          substs,
607                                                          trait_closure_kind);
608                 vec![llfn].into_iter()
609             }
610             traits::VtableFnPointer(bare_fn_ty) => {
611                 let trait_closure_kind = tcx.lang_items.fn_trait_kind(trait_ref.def_id()).unwrap();
612                 vec![trans_fn_pointer_shim(ccx, trait_closure_kind, bare_fn_ty)].into_iter()
613             }
614             traits::VtableObject(ref data) => {
615                 // this would imply that the Self type being erased is
616                 // an object type; this cannot happen because we
617                 // cannot cast an unsized type into a trait object
618                 tcx.sess.bug(
619                     &format!("cannot get vtable for an object type: {:?}",
620                             data));
621             }
622             traits::VtableParam(..) => {
623                 tcx.sess.bug(
624                     &format!("resolved vtable for {:?} to bad vtable {:?} in trans",
625                             trait_ref,
626                             vtable));
627             }
628         }
629     });
630
631     let size_ty = sizing_type_of(ccx, trait_ref.self_ty());
632     let size = machine::llsize_of_alloc(ccx, size_ty);
633     let align = align_of(ccx, trait_ref.self_ty());
634
635     let components: Vec<_> = vec![
636         // Generate a destructor for the vtable.
637         glue::get_drop_glue(ccx, trait_ref.self_ty()),
638         C_uint(ccx, size),
639         C_uint(ccx, align)
640     ].into_iter().chain(methods).collect();
641
642     let vtable_const = C_struct(ccx, &components, false);
643     let align = machine::llalign_of_pref(ccx, val_ty(vtable_const));
644     let vtable = consts::addr_of(ccx, vtable_const, align, "vtable");
645
646     ccx.vtables().borrow_mut().insert(trait_ref, vtable);
647     vtable
648 }
649
650 fn emit_vtable_methods<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
651                                  impl_id: DefId,
652                                  substs: subst::Substs<'tcx>,
653                                  param_substs: &'tcx subst::Substs<'tcx>)
654                                  -> Vec<ValueRef>
655 {
656     let tcx = ccx.tcx();
657
658     debug!("emit_vtable_methods(impl_id={:?}, substs={:?}, param_substs={:?})",
659            impl_id,
660            substs,
661            param_substs);
662
663     let trt_id = match tcx.impl_trait_ref(impl_id) {
664         Some(t_id) => t_id.def_id,
665         None       => ccx.sess().bug("make_impl_vtable: don't know how to \
666                                       make a vtable for a type impl!")
667     };
668
669     tcx.populate_implementations_for_trait_if_necessary(trt_id);
670
671     let nullptr = C_null(Type::nil(ccx).ptr_to());
672     let trait_item_def_ids = tcx.trait_item_def_ids(trt_id);
673     trait_item_def_ids
674         .iter()
675
676         // Filter out non-method items.
677         .filter_map(|item_def_id| {
678             match *item_def_id {
679                 ty::MethodTraitItemId(def_id) => Some(def_id),
680                 _ => None,
681             }
682         })
683
684         // Now produce pointers for each remaining method. If the
685         // method could never be called from this object, just supply
686         // null.
687         .map(|trait_method_def_id| {
688             debug!("emit_vtable_methods: trait_method_def_id={:?}",
689                    trait_method_def_id);
690
691             let trait_method_type = match tcx.impl_or_trait_item(trait_method_def_id) {
692                 ty::MethodTraitItem(m) => m,
693                 _ => ccx.sess().bug("should be a method, not other assoc item"),
694             };
695             let name = trait_method_type.name;
696
697             // Some methods cannot be called on an object; skip those.
698             if !traits::is_vtable_safe_method(tcx, trt_id, &trait_method_type) {
699                 debug!("emit_vtable_methods: not vtable safe");
700                 return nullptr;
701             }
702
703             debug!("emit_vtable_methods: trait_method_type={:?}",
704                    trait_method_type);
705
706             // The substitutions we have are on the impl, so we grab
707             // the method type from the impl to substitute into.
708             let mth = tcx.get_impl_method(impl_id, substs.clone(), name);
709
710             debug!("emit_vtable_methods: mth={:?}", mth);
711
712             // If this is a default method, it's possible that it
713             // relies on where clauses that do not hold for this
714             // particular set of type parameters. Note that this
715             // method could then never be called, so we do not want to
716             // try and trans it, in that case. Issue #23435.
717             if mth.is_provided {
718                 let predicates = mth.method.predicates.predicates.subst(tcx, &mth.substs);
719                 if !normalize_and_test_predicates(ccx, predicates.into_vec()) {
720                     debug!("emit_vtable_methods: predicates do not hold");
721                     return nullptr;
722                 }
723             }
724
725             trans_fn_ref_with_substs(ccx,
726                                      mth.method.def_id,
727                                      ExprId(0),
728                                      param_substs,
729                                      mth.substs).val
730         })
731         .collect()
732 }
733
734 /// Replace the self type (&Self or Box<Self>) with an opaque pointer.
735 fn opaque_method_ty<'tcx>(tcx: &ty::ctxt<'tcx>, method_ty: &ty::BareFnTy<'tcx>)
736                           -> &'tcx ty::BareFnTy<'tcx> {
737     let mut inputs = method_ty.sig.0.inputs.clone();
738     inputs[0] = tcx.mk_mut_ptr(tcx.mk_mach_int(ast::TyI8));
739
740     tcx.mk_bare_fn(ty::BareFnTy {
741         unsafety: method_ty.unsafety,
742         abi: method_ty.abi,
743         sig: ty::Binder(ty::FnSig {
744             inputs: inputs,
745             output: method_ty.sig.0.output,
746             variadic: method_ty.sig.0.variadic,
747         }),
748     })
749 }