]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/meth.rs
Adapted `trans::common::{block, fn_ctxt, scope_info}` to new naming convention.
[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 lib::llvm::llvm;
14 use lib::llvm::ValueRef;
15 use lib;
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::*;
28 use middle::ty;
29 use middle::typeck;
30 use util::common::indenter;
31 use util::ppaux::Repr;
32
33 use middle::trans::type_::Type;
34
35 use std::vec;
36 use syntax::ast_map::{path, path_mod, path_name};
37 use syntax::ast_util;
38 use syntax::{ast, ast_map};
39
40 /**
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()`.
45 */
46 pub fn trans_impl(ccx: @mut CrateContext,
47                   path: path,
48                   name: ast::ident,
49                   methods: &[@ast::method],
50                   generics: &ast::Generics,
51                   id: ast::node_id) {
52     let _icx = push_ctxt("impl::trans_impl");
53     let tcx = ccx.tcx;
54
55     debug!("trans_impl(path=%s, name=%s, id=%?)",
56            path.repr(tcx), name.repr(tcx), id);
57
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));
65
66             trans_method(ccx,
67                          path,
68                          *method,
69                          None,
70                          llfn);
71         }
72     }
73 }
74
75 /// Translates a (possibly monomorphized) method body.
76 ///
77 /// Parameters:
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
84 ///
85 /// XXX(pcwalton) Can we take `path` by reference?
86 pub fn trans_method(ccx: @mut CrateContext,
87                     path: path,
88                     method: &ast::method,
89                     param_substs: Option<@param_substs>,
90                     llfn: ValueRef) {
91     // figure out how self is being passed
92     let self_arg = match method.explicit_self.node {
93       ast::sty_static => {
94         no_self
95       }
96       _ => {
97         // determine the (monomorphized) type that `self` maps to for
98         // this method
99         let self_ty = ty::node_id_to_type(ccx.tcx, method.self_id);
100         let self_ty = match param_substs {
101             None => self_ty,
102             Some(@param_substs {tys: ref tys, self_ty: ref self_sub, _}) => {
103                 ty::subst_tps(ccx.tcx, *tys, *self_sub, self_ty)
104             }
105         };
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),
111         }
112       }
113     };
114
115     // generate the actual code
116     trans_fn(ccx,
117              path,
118              &method.decl,
119              &method.body,
120              llfn,
121              self_arg,
122              param_substs,
123              method.id,
124              []);
125 }
126
127 pub fn trans_self_arg(bcx: @mut Block,
128                       base: @ast::expr,
129                       temp_cleanups: &mut ~[ValueRef],
130                       mentry: typeck::method_map_entry) -> Result {
131     let _icx = push_ctxt("impl::trans_self_arg");
132
133     // self is passed as an opaque box in the environment slot
134     let self_ty = ty::mk_opaque_box(bcx.tcx());
135     trans_arg_expr(bcx,
136                    self_ty,
137                    mentry.self_mode,
138                    base,
139                    temp_cleanups,
140                    None,
141                    DontAutorefArg)
142 }
143
144 pub fn trans_method_callee(bcx: @mut Block,
145                            callee_id: ast::node_id,
146                            this: @ast::expr,
147                            mentry: typeck::method_map_entry)
148                            -> Callee {
149     let _icx = push_ctxt("impl::trans_method_callee");
150     let tcx = bcx.tcx();
151
152     debug!("trans_method_callee(callee_id=%?, this=%s, mentry=%s)",
153            callee_id,
154            bcx.expr_to_str(this),
155            mentry.repr(bcx.tcx()));
156
157     // Replace method_self with method_static here.
158     let mut origin = mentry.origin;
159     match 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");
173             }
174             // Get the method name using the method index in the origin
175             let method_name =
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
178             // ID from its name
179             origin = typeck::method_static(
180                 method_with_name(bcx.ccx(), impl_id, method_name));
181         }
182         typeck::method_self(*) |
183         typeck::method_static(*) | typeck::method_param(*) |
184         typeck::method_trait(*) => {}
185     }
186
187     debug!("origin=%?", origin);
188
189     match 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);
194             Callee {
195                 bcx: bcx,
196                 data: Method(MethodData {
197                     llfn: callee_fn.llfn,
198                     llself: val,
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,
202                 })
203             }
204         }
205         typeck::method_param(typeck::method_param {
206             trait_id: trait_id,
207             method_num: off,
208             param_num: p,
209             bound_num: b
210         }) => {
211             match bcx.fcx.param_substs {
212                 Some(substs) => {
213                     let vtbl = find_vtable(bcx.tcx(), substs, p, b);
214                     trans_monomorphized_callee(bcx, callee_id, this, mentry,
215                                                trait_id, off, vtbl)
216                 }
217                 // how to get rid of this?
218                 None => fail!("trans_method_callee: missing param_substs")
219             }
220         }
221
222         typeck::method_self(trait_id, method_index) => {
223             match bcx.fcx.param_substs {
224                 Some(@param_substs
225                      {self_vtable: Some(ref vtbl), _}) => {
226                     trans_monomorphized_callee(bcx,
227                                                callee_id,
228                                                this,
229                                                mentry,
230                                                trait_id,
231                                                method_index,
232                                                (*vtbl).clone())
233                 }
234                 _ => {
235                     fail!("trans_method_callee: missing self_vtable")
236                 }
237             }
238         }
239
240         typeck::method_trait(_, off, store) => {
241             trans_trait_callee(bcx,
242                                callee_id,
243                                off,
244                                this,
245                                store,
246                                mentry.explicit_self)
247         }
248         typeck::method_super(*) => {
249             fail!("method_super should have been handled above")
250         }
251     }
252 }
253
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)
258                                -> FnData {
259     let _icx = push_ctxt("impl::trans_static_method_callee");
260     let ccx = bcx.ccx();
261
262     debug!("trans_static_method_callee(method_id=%?, trait_id=%s, \
263             callee_id=%?)",
264            method_id,
265            ty::item_path_str(bcx.tcx(), trait_id),
266            callee_id);
267     let _indenter = indenter();
268
269     // When we translate a static fn defined in a trait like:
270     //
271     //   trait<T1...Tn> Trait {
272     //       fn foo<M1...Mn>(...) {...}
273     //   }
274     //
275     // this winds up being translated as something like:
276     //
277     //   fn foo<T1...Tn,self: Trait<T1...Tn>,M1...Mn>(...) {...}
278     //
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
281     // bound to.
282     let bound_index = ty::lookup_trait_def(bcx.tcx(), trait_id).
283         generics.type_param_defs.len();
284
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
289             }
290             _ => fail!("callee is not a trait method")
291         }
292     } else {
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?") }
297         }
298     };
299     debug!("trans_static_method_callee: method_id=%?, callee_id=%?, \
300             name=%s", method_id, callee_id, ccx.sess.str_of(mname));
301
302     let vtbls = resolve_vtables_in_fn_ctxt(
303         bcx.fcx, ccx.maps.vtable_map.get_copy(&callee_id));
304
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)));
308
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);
314
315             let FnData {llfn: lval} =
316                 trans_fn_ref_with_vtables(bcx,
317                                           mth_id,
318                                           callee_id,
319                                           callee_substs,
320                                           Some(callee_origins));
321
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)}
325         }
326         _ => {
327             fail!("vtable_param left in monomorphized \
328                    function's vtable substs");
329         }
330     }
331 }
332
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));
337     match meth_id_opt {
338         Some(m) => return m,
339         None => {}
340     }
341
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");
346
347     ccx.impl_method_cache.insert((impl_id, name), meth.def_id);
348     meth.def_id
349 }
350
351 pub fn trans_monomorphized_callee(bcx: @mut Block,
352                                   callee_id: ast::node_id,
353                                   base: @ast::expr,
354                                   mentry: typeck::method_map_entry,
355                                   trait_id: ast::def_id,
356                                   n_method: uint,
357                                   vtbl: typeck::vtable_origin)
358                                   -> Callee {
359     let _icx = push_ctxt("impl::trans_monomorphized_callee");
360     return match vtbl {
361       typeck::vtable_static(impl_did, ref rcvr_substs, rcvr_origins) => {
362           let ccx = bcx.ccx();
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);
365
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);
370
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);
377
378           // translate the function
379           let callee = trans_fn_ref_with_vtables(bcx,
380                                                  mth_id,
381                                                  callee_id,
382                                                  callee_substs,
383                                                  Some(callee_origins));
384
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);
389
390           // combine the self environment with the rest
391           Callee {
392               bcx: bcx,
393               data: Method(MethodData {
394                   llfn: llfn_val,
395                   llself: llself_val,
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,
399               })
400           }
401       }
402       typeck::vtable_param(*) => {
403           fail!("vtable_param left in monomorphized function's vtable substs");
404       }
405       typeck::vtable_self(*) => {
406           fail!("vtable_self left in monomorphized function's vtable substs");
407       }
408     };
409
410 }
411
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) {
418     /*!
419     *
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]`.
427     *
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
433     * mapped to. */
434
435     let ccx = bcx.ccx();
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));
440     let ty_substs
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));
446
447
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) {
451         Some(vt) => vt,
452         None => @vec::from_elem(node_substs.len(), @~[])
453     };
454     let vtables
455         = @vec::append(rcvr_origins.to_owned(),
456                        r_m_origins.tailn(r_m_origins.len() - n_m_tps));
457
458     return (ty_substs, vtables);
459 }
460
461
462 pub fn trans_trait_callee(bcx: @mut Block,
463                           callee_id: ast::node_id,
464                           n_method: uint,
465                           self_expr: @ast::expr,
466                           store: ty::TraitStore,
467                           explicit_self: ast::explicit_self_)
468                           -> Callee {
469     //!
470     //
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.
477
478     let _icx = push_ctxt("impl::trans_trait_callee");
479     let mut bcx = bcx;
480     let self_datum = unpack_datum!(bcx,
481         expr::trans_to_datum(bcx, self_expr));
482     let llpair = self_datum.to_ref_llval(bcx);
483
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
488     };
489
490     let callee_ty = node_id_type(bcx, callee_id);
491     trans_trait_callee_from_llval(bcx,
492                                   callee_ty,
493                                   n_method,
494                                   llpair,
495                                   store,
496                                   explicit_self)
497 }
498
499 pub fn trans_trait_callee_from_llval(bcx: @mut Block,
500                                      callee_ty: ty::t,
501                                      n_method: uint,
502                                      llpair: ValueRef,
503                                      store: ty::TraitStore,
504                                      explicit_self: ast::explicit_self_)
505                                   -> Callee {
506     //!
507     //
508     // Same as `trans_trait_callee()` above, except that it is given
509     // a by-ref pointer to the @Trait pair.
510
511     let _icx = push_ctxt("impl::trans_trait_callee");
512     let ccx = bcx.ccx();
513
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,
518                       PointerCast(bcx,
519                                   GEPi(bcx, llpair,
520                                        [0u, abi::trt_field_vtable]),
521                                   Type::vtable().ptr_to().ptr_to()));
522
523     // Load the box from the @Trait pair and GEP over the box header if
524     // necessary:
525     let mut llself;
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);
529
530     // Munge `llself` appropriately for the type of `self` in the method.
531     match explicit_self {
532         ast::sty_static => {
533             bcx.tcx().sess.bug("shouldn't see static method here");
534         }
535         ast::sty_value => {
536             bcx.tcx().sess.bug("methods with by-value self should not be \
537                                 called on objects");
538         }
539         ast::sty_region(*) => {
540             match store {
541                 ty::UniqTraitStore
542                     if !ty::type_contents(bcx.tcx(), callee_ty).contains_managed() => {
543                     llself = llbox;
544                 }
545                 ty::BoxTraitStore |
546                 ty::UniqTraitStore => {
547                     llself = GEPi(bcx, llbox, [0u, abi::box_field_body]);
548                 }
549                 ty::RegionTraitStore(_) => {
550                     llself = llbox;
551                 }
552             }
553         }
554         ast::sty_box(_) => {
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);
559
560             // Pass a pointer to the box.
561             match store {
562                 ty::BoxTraitStore => llself = llbox,
563                 _ => bcx.tcx().sess.bug("@self receiver with non-@Trait")
564             }
565         }
566         ast::sty_uniq => {
567             // Pass the unique pointer.
568             match store {
569                 ty::UniqTraitStore => llself = llbox,
570                 _ => bcx.tcx().sess.bug("~self receiver with non-~Trait")
571             }
572
573             zero_mem(bcx, llboxptr, ty::mk_opaque_box(bcx.tcx()));
574         }
575     }
576
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);
582
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);
586
587     // Plus one in order to skip past the type descriptor.
588     let mptr = Load(bcx, GEPi(bcx, llvtable, [0u, n_method + 1]));
589
590     let mptr = PointerCast(bcx, mptr, llcallee_ty.ptr_to());
591
592     return Callee {
593         bcx: bcx,
594         data: Method(MethodData {
595             llfn: mptr,
596             llself: scratch.to_value_llval(bcx),
597             temp_cleanup: Some(scratch.val),
598             self_ty: scratch.ty,
599             self_mode: ty::ByCopy,
600             /* XXX: Some(llbox) */
601         })
602     };
603 }
604
605 pub fn vtable_id(ccx: @mut CrateContext,
606                  origin: &typeck::vtable_origin)
607               -> mono_id {
608     match 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),
613                 self_ty: None,
614                 self_vtable: None
615             };
616
617             monomorphize::make_mono_id(
618                 ccx,
619                 impl_id,
620                 &psubsts,
621                 None)
622         }
623
624         // can't this be checked at the callee?
625         _ => fail!("vtable_id")
626     }
627 }
628
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,
632                   self_ty: ty::t,
633                   origin: typeck::vtable_origin)
634                   -> ValueRef {
635     let hash_id = vtable_id(bcx.ccx(), &origin);
636     match bcx.ccx().vtables.find(&hash_id) {
637         Some(&val) => val,
638         None => {
639             match origin {
640                 typeck::vtable_static(id, substs, sub_vtables) => {
641                     make_impl_vtable(bcx, id, self_ty, substs, sub_vtables)
642                 }
643                 _ => fail!("get_vtable: expected a static origin"),
644             }
645         }
646     }
647 }
648
649 /// Helper function to declare and initialize the vtable.
650 pub fn make_vtable(ccx: &mut CrateContext,
651                    tydesc: &tydesc_info,
652                    ptrs: &[ValueRef])
653                    -> ValueRef {
654     unsafe {
655         let _icx = push_ctxt("impl::make_vtable");
656
657         let mut components = ~[ tydesc.tydesc ];
658         for ptrs.iter().advance |&ptr| {
659             components.push(ptr)
660         }
661
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)
666         };
667         llvm::LLVMSetInitializer(vt_gvar, tbl);
668         llvm::LLVMSetGlobalConstant(vt_gvar, lib::llvm::True);
669         lib::llvm::SetLinkage(vt_gvar, lib::llvm::InternalLinkage);
670         vt_gvar
671     }
672 }
673
674 /// Generates a dynamic vtable for objects.
675 pub fn make_impl_vtable(bcx: @mut Block,
676                         impl_id: ast::def_id,
677                         self_ty: ty::t,
678                         substs: &[ty::t],
679                         vtables: typeck::vtable_res)
680                         -> ValueRef {
681     let ccx = bcx.ccx();
682     let _icx = push_ctxt("impl::make_impl_vtable");
683     let tcx = ccx.tcx;
684
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!")
689     };
690
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,
695                                 substs,
696                                 None,
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())
702         } else {
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);
706
707             trans_fn_ref_with_vtables(bcx, m_id, 0,
708                                       substs, Some(vtables)).llfn
709         }
710     };
711
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);
715
716     make_vtable(ccx, tydesc, methods)
717 }
718
719 pub fn trans_trait_cast(bcx: @mut Block,
720                         val: @ast::expr,
721                         id: ast::node_id,
722                         dest: expr::Dest,
723                         _store: ty::TraitStore)
724                      -> @mut Block {
725     let mut bcx = bcx;
726     let _icx = push_ctxt("impl::trans_cast");
727
728     let lldest = match dest {
729         Ignore => {
730             return expr::trans_into(bcx, val, Ignore);
731         }
732         SaveIn(dest) => dest
733     };
734
735     let ccx = bcx.ccx();
736     let v_ty = expr_ty(bcx, val);
737
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,
743                             llboxdest,
744                             type_of(bcx.ccx(), v_ty).ptr_to());
745     bcx = expr::trans_into(bcx, val, SaveIn(llboxdest));
746
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()));
754
755     bcx
756 }