]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/meth.rs
Merge remote-tracking branch 'remotes/origin/master' into str-remove-null
[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::c_str::ToCStr;
36 use std::vec;
37 use syntax::ast_map::{path, path_mod, path_name};
38 use syntax::ast_util;
39 use syntax::{ast, ast_map};
40
41 /**
42 The main "translation" pass for methods.  Generates code
43 for non-monomorphized methods only.  Other methods will
44 be generated once they are invoked with specific type parameters,
45 see `trans::base::lval_static_fn()` or `trans::base::monomorphic_fn()`.
46 */
47 pub fn trans_impl(ccx: @mut CrateContext,
48                   path: path,
49                   name: ast::ident,
50                   methods: &[@ast::method],
51                   generics: &ast::Generics,
52                   id: ast::NodeId) {
53     let _icx = push_ctxt("impl::trans_impl");
54     let tcx = ccx.tcx;
55
56     debug!("trans_impl(path=%s, name=%s, id=%?)",
57            path.repr(tcx), name.repr(tcx), id);
58
59     if !generics.ty_params.is_empty() { return; }
60     let sub_path = vec::append_one(path, path_name(name));
61     for method in methods.iter() {
62         if method.generics.ty_params.len() == 0u {
63             let llfn = get_item_val(ccx, method.id);
64             let path = vec::append_one(sub_path.clone(),
65                                        path_name(method.ident));
66
67             trans_method(ccx,
68                          path,
69                          *method,
70                          None,
71                          llfn);
72         }
73     }
74 }
75
76 /// Translates a (possibly monomorphized) method body.
77 ///
78 /// Parameters:
79 /// * `path`: the path to the method
80 /// * `method`: the AST node for the method
81 /// * `param_substs`: if this is a generic method, the current values for
82 ///   type parameters and so forth, else none
83 /// * `llfn`: the LLVM ValueRef for the method
84 /// * `impl_id`: the node ID of the impl this method is inside
85 ///
86 /// XXX(pcwalton) Can we take `path` by reference?
87 pub fn trans_method(ccx: @mut CrateContext,
88                     path: path,
89                     method: &ast::method,
90                     param_substs: Option<@param_substs>,
91                     llfn: ValueRef) {
92     // figure out how self is being passed
93     let self_arg = match method.explicit_self.node {
94       ast::sty_static => {
95         no_self
96       }
97       _ => {
98         // determine the (monomorphized) type that `self` maps to for
99         // this method
100         let self_ty = ty::node_id_to_type(ccx.tcx, method.self_id);
101         let self_ty = match param_substs {
102             None => self_ty,
103             Some(@param_substs {tys: ref tys, self_ty: ref self_sub, _}) => {
104                 ty::subst_tps(ccx.tcx, *tys, *self_sub, self_ty)
105             }
106         };
107         debug!("calling trans_fn with self_ty %s",
108                self_ty.repr(ccx.tcx));
109         match method.explicit_self.node {
110           ast::sty_value => impl_self(self_ty, ty::ByRef),
111           _ => impl_self(self_ty, ty::ByCopy),
112         }
113       }
114     };
115
116     // generate the actual code
117     trans_fn(ccx,
118              path,
119              &method.decl,
120              &method.body,
121              llfn,
122              self_arg,
123              param_substs,
124              method.id,
125              []);
126 }
127
128 pub fn trans_self_arg(bcx: @mut Block,
129                       base: @ast::expr,
130                       temp_cleanups: &mut ~[ValueRef],
131                       mentry: typeck::method_map_entry) -> Result {
132     let _icx = push_ctxt("impl::trans_self_arg");
133
134     // self is passed as an opaque box in the environment slot
135     let self_ty = ty::mk_opaque_box(bcx.tcx());
136     trans_arg_expr(bcx,
137                    self_ty,
138                    mentry.self_mode,
139                    base,
140                    temp_cleanups,
141                    DontAutorefArg)
142 }
143
144 pub fn trans_method_callee(bcx: @mut Block,
145                            callee_id: ast::NodeId,
146                            this: @ast::expr,
147                            mentry: typeck::method_map_entry)
148                            -> Callee {
149     let _icx = push_ctxt("impl::trans_method_callee");
150
151     debug!("trans_method_callee(callee_id=%?, this=%s, mentry=%s)",
152            callee_id,
153            bcx.expr_to_str(this),
154            mentry.repr(bcx.tcx()));
155
156     match mentry.origin {
157         typeck::method_static(did) => {
158             let callee_fn = callee::trans_fn_ref(bcx, did, callee_id);
159             let mut temp_cleanups = ~[];
160             let Result {bcx, val} = trans_self_arg(bcx, this, &mut temp_cleanups, mentry);
161             Callee {
162                 bcx: bcx,
163                 data: Method(MethodData {
164                     llfn: callee_fn.llfn,
165                     llself: val,
166                     temp_cleanup: temp_cleanups.head_opt().map(|&v| *v),
167                     self_ty: node_id_type(bcx, this.id),
168                     self_mode: mentry.self_mode,
169                 })
170             }
171         }
172         typeck::method_param(typeck::method_param {
173             trait_id: trait_id,
174             method_num: off,
175             param_num: p,
176             bound_num: b
177         }) => {
178             match bcx.fcx.param_substs {
179                 Some(substs) => {
180                     let vtbl = find_vtable(bcx.tcx(), substs,
181                                            p, b);
182                     trans_monomorphized_callee(bcx, callee_id, this, mentry,
183                                                trait_id, off, vtbl)
184                 }
185                 // how to get rid of this?
186                 None => fail!("trans_method_callee: missing param_substs")
187             }
188         }
189
190         typeck::method_trait(_, off, store) => {
191             trans_trait_callee(bcx,
192                                callee_id,
193                                off,
194                                this,
195                                store,
196                                mentry.explicit_self)
197         }
198     }
199 }
200
201 pub fn trans_static_method_callee(bcx: @mut Block,
202                                   method_id: ast::def_id,
203                                   trait_id: ast::def_id,
204                                   callee_id: ast::NodeId)
205                                -> FnData {
206     let _icx = push_ctxt("impl::trans_static_method_callee");
207     let ccx = bcx.ccx();
208
209     debug!("trans_static_method_callee(method_id=%?, trait_id=%s, \
210             callee_id=%?)",
211            method_id,
212            ty::item_path_str(bcx.tcx(), trait_id),
213            callee_id);
214     let _indenter = indenter();
215
216     // When we translate a static fn defined in a trait like:
217     //
218     //   trait<T1...Tn> Trait {
219     //       fn foo<M1...Mn>(...) {...}
220     //   }
221     //
222     // this winds up being translated as something like:
223     //
224     //   fn foo<T1...Tn,self: Trait<T1...Tn>,M1...Mn>(...) {...}
225     //
226     // So when we see a call to this function foo, we have to figure
227     // out which impl the `Trait<T1...Tn>` bound on the type `self` was
228     // bound to.
229     let bound_index = ty::lookup_trait_def(bcx.tcx(), trait_id).
230         generics.type_param_defs.len();
231
232     let mname = if method_id.crate == ast::LOCAL_CRATE {
233         match bcx.tcx().items.get_copy(&method_id.node) {
234             ast_map::node_trait_method(trait_method, _, _) => {
235                 ast_util::trait_method_to_ty_method(trait_method).ident
236             }
237             _ => fail!("callee is not a trait method")
238         }
239     } else {
240         let path = csearch::get_item_path(bcx.tcx(), method_id);
241         match path[path.len()-1] {
242             path_name(s) => { s }
243             path_mod(_) => { fail!("path doesn't have a name?") }
244         }
245     };
246     debug!("trans_static_method_callee: method_id=%?, callee_id=%?, \
247             name=%s", method_id, callee_id, ccx.sess.str_of(mname));
248
249     let vtbls = resolve_vtables_in_fn_ctxt(
250         bcx.fcx, ccx.maps.vtable_map.get_copy(&callee_id));
251
252     match vtbls[bound_index][0] {
253         typeck::vtable_static(impl_did, ref rcvr_substs, rcvr_origins) => {
254             assert!(rcvr_substs.iter().all(|t| !ty::type_needs_infer(*t)));
255
256             let mth_id = method_with_name(bcx.ccx(), impl_did, mname);
257             let (callee_substs, callee_origins) =
258                 combine_impl_and_methods_tps(
259                     bcx, mth_id, callee_id,
260                     *rcvr_substs, rcvr_origins);
261
262             let FnData {llfn: lval} =
263                 trans_fn_ref_with_vtables(bcx,
264                                           mth_id,
265                                           callee_id,
266                                           callee_substs,
267                                           Some(callee_origins));
268
269             let callee_ty = node_id_type(bcx, callee_id);
270             let llty = type_of_fn_from_ty(ccx, callee_ty).ptr_to();
271             FnData {llfn: PointerCast(bcx, lval, llty)}
272         }
273         _ => {
274             fail!("vtable_param left in monomorphized \
275                    function's vtable substs");
276         }
277     }
278 }
279
280 pub fn method_with_name(ccx: &mut CrateContext,
281                         impl_id: ast::def_id,
282                         name: ast::ident) -> ast::def_id {
283     let meth_id_opt = ccx.impl_method_cache.find_copy(&(impl_id, name));
284     match meth_id_opt {
285         Some(m) => return m,
286         None => {}
287     }
288
289     let imp = ccx.tcx.impls.find(&impl_id)
290         .expect("could not find impl while translating");
291     let meth = imp.methods.iter().find_(|m| m.ident == name)
292         .expect("could not find method while translating");
293
294     ccx.impl_method_cache.insert((impl_id, name), meth.def_id);
295     meth.def_id
296 }
297
298 pub fn trans_monomorphized_callee(bcx: @mut Block,
299                                   callee_id: ast::NodeId,
300                                   base: @ast::expr,
301                                   mentry: typeck::method_map_entry,
302                                   trait_id: ast::def_id,
303                                   n_method: uint,
304                                   vtbl: typeck::vtable_origin)
305                                   -> Callee {
306     let _icx = push_ctxt("impl::trans_monomorphized_callee");
307     return match vtbl {
308       typeck::vtable_static(impl_did, ref rcvr_substs, rcvr_origins) => {
309           let ccx = bcx.ccx();
310           let mname = ty::trait_method(ccx.tcx, trait_id, n_method).ident;
311           let mth_id = method_with_name(bcx.ccx(), impl_did, mname);
312
313           // obtain the `self` value:
314           let mut temp_cleanups = ~[];
315           let Result {bcx, val: llself_val} =
316               trans_self_arg(bcx, base, &mut temp_cleanups, mentry);
317
318           // create a concatenated set of substitutions which includes
319           // those from the impl and those from the method:
320           let (callee_substs, callee_origins) =
321               combine_impl_and_methods_tps(
322                   bcx, mth_id, callee_id,
323                   *rcvr_substs, rcvr_origins);
324
325           // translate the function
326           let callee = trans_fn_ref_with_vtables(bcx,
327                                                  mth_id,
328                                                  callee_id,
329                                                  callee_substs,
330                                                  Some(callee_origins));
331
332           // create a llvalue that represents the fn ptr
333           let fn_ty = node_id_type(bcx, callee_id);
334           let llfn_ty = type_of_fn_from_ty(ccx, fn_ty).ptr_to();
335           let llfn_val = PointerCast(bcx, callee.llfn, llfn_ty);
336
337           // combine the self environment with the rest
338           Callee {
339               bcx: bcx,
340               data: Method(MethodData {
341                   llfn: llfn_val,
342                   llself: llself_val,
343                   temp_cleanup: temp_cleanups.head_opt().map(|&v| *v),
344                   self_ty: node_id_type(bcx, base.id),
345                   self_mode: mentry.self_mode,
346               })
347           }
348       }
349       typeck::vtable_param(*) => {
350           fail!("vtable_param left in monomorphized function's vtable substs");
351       }
352     };
353
354 }
355
356 pub fn combine_impl_and_methods_tps(bcx: @mut Block,
357                                     mth_did: ast::def_id,
358                                     callee_id: ast::NodeId,
359                                     rcvr_substs: &[ty::t],
360                                     rcvr_origins: typeck::vtable_res)
361                                     -> (~[ty::t], typeck::vtable_res) {
362     /*!
363     *
364     * Creates a concatenated set of substitutions which includes
365     * those from the impl and those from the method.  This are
366     * some subtle complications here.  Statically, we have a list
367     * of type parameters like `[T0, T1, T2, M1, M2, M3]` where
368     * `Tn` are type parameters that appear on the receiver.  For
369     * example, if the receiver is a method parameter `A` with a
370     * bound like `trait<B,C,D>` then `Tn` would be `[B,C,D]`.
371     *
372     * The weird part is that the type `A` might now be bound to
373     * any other type, such as `foo<X>`.  In that case, the vector
374     * we want is: `[X, M1, M2, M3]`.  Therefore, what we do now is
375     * to slice off the method type parameters and append them to
376     * the type parameters from the type that the receiver is
377     * mapped to. */
378
379     let ccx = bcx.ccx();
380     let method = ty::method(ccx.tcx, mth_did);
381     let n_m_tps = method.generics.type_param_defs.len();
382     let node_substs = node_id_type_params(bcx, callee_id);
383     debug!("rcvr_substs=%?", rcvr_substs.repr(ccx.tcx));
384     let ty_substs
385         = vec::append(rcvr_substs.to_owned(),
386                       node_substs.tailn(node_substs.len() - n_m_tps));
387     debug!("n_m_tps=%?", n_m_tps);
388     debug!("node_substs=%?", node_substs.repr(ccx.tcx));
389     debug!("ty_substs=%?", ty_substs.repr(ccx.tcx));
390
391
392     // Now, do the same work for the vtables.  The vtables might not
393     // exist, in which case we need to make them.
394     let r_m_origins = match node_vtables(bcx, callee_id) {
395         Some(vt) => vt,
396         None => @vec::from_elem(node_substs.len(), @~[])
397     };
398     let vtables
399         = @vec::append(rcvr_origins.to_owned(),
400                        r_m_origins.tailn(r_m_origins.len() - n_m_tps));
401
402     return (ty_substs, vtables);
403 }
404
405
406 pub fn trans_trait_callee(bcx: @mut Block,
407                           callee_id: ast::NodeId,
408                           n_method: uint,
409                           self_expr: @ast::expr,
410                           store: ty::TraitStore,
411                           explicit_self: ast::explicit_self_)
412                           -> Callee {
413     //!
414     //
415     // Create a method callee where the method is coming from a trait
416     // instance (e.g., @Trait type).  In this case, we must pull the
417     // fn pointer out of the vtable that is packaged up with the
418     // @/~/&Trait instance.  @/~/&Traits are represented as a pair, so we
419     // first evaluate the self expression (expected a by-ref result) and then
420     // extract the self data and vtable out of the pair.
421
422     let _icx = push_ctxt("impl::trans_trait_callee");
423     let mut bcx = bcx;
424     let self_datum = unpack_datum!(bcx,
425         expr::trans_to_datum(bcx, self_expr));
426     let llpair = self_datum.to_ref_llval(bcx);
427
428     let llpair = match explicit_self {
429         ast::sty_region(*) => Load(bcx, llpair),
430         ast::sty_static | ast::sty_value |
431         ast::sty_box(_) | ast::sty_uniq => llpair
432     };
433
434     let callee_ty = node_id_type(bcx, callee_id);
435     trans_trait_callee_from_llval(bcx,
436                                   callee_ty,
437                                   n_method,
438                                   llpair,
439                                   store,
440                                   explicit_self)
441 }
442
443 pub fn trans_trait_callee_from_llval(bcx: @mut Block,
444                                      callee_ty: ty::t,
445                                      n_method: uint,
446                                      llpair: ValueRef,
447                                      store: ty::TraitStore,
448                                      explicit_self: ast::explicit_self_)
449                                   -> Callee {
450     //!
451     //
452     // Same as `trans_trait_callee()` above, except that it is given
453     // a by-ref pointer to the @Trait pair.
454
455     let _icx = push_ctxt("impl::trans_trait_callee");
456     let ccx = bcx.ccx();
457
458     // Load the vtable from the @Trait pair
459     debug!("(translating trait callee) loading vtable from pair %s",
460            bcx.val_to_str(llpair));
461     let llvtable = Load(bcx,
462                       PointerCast(bcx,
463                                   GEPi(bcx, llpair,
464                                        [0u, abi::trt_field_vtable]),
465                                   Type::vtable().ptr_to().ptr_to()));
466
467     // Load the box from the @Trait pair and GEP over the box header if
468     // necessary:
469     let mut llself;
470     debug!("(translating trait callee) loading second index from pair");
471     let llboxptr = GEPi(bcx, llpair, [0u, abi::trt_field_box]);
472     let llbox = Load(bcx, llboxptr);
473
474     // Munge `llself` appropriately for the type of `self` in the method.
475     match explicit_self {
476         ast::sty_static => {
477             bcx.tcx().sess.bug("shouldn't see static method here");
478         }
479         ast::sty_value => {
480             bcx.tcx().sess.bug("methods with by-value self should not be \
481                                 called on objects");
482         }
483         ast::sty_region(*) => {
484             match store {
485                 ty::UniqTraitStore
486                     if !ty::type_contents(bcx.tcx(), callee_ty).contains_managed() => {
487                     llself = llbox;
488                 }
489                 ty::BoxTraitStore |
490                 ty::UniqTraitStore => {
491                     llself = GEPi(bcx, llbox, [0u, abi::box_field_body]);
492                 }
493                 ty::RegionTraitStore(_) => {
494                     llself = llbox;
495                 }
496             }
497         }
498         ast::sty_box(_) => {
499             // Bump the reference count on the box.
500             debug!("(translating trait callee) callee type is `%s`",
501                    bcx.ty_to_str(callee_ty));
502             glue::incr_refcnt_of_boxed(bcx, llbox);
503
504             // Pass a pointer to the box.
505             match store {
506                 ty::BoxTraitStore => llself = llbox,
507                 _ => bcx.tcx().sess.bug("@self receiver with non-@Trait")
508             }
509         }
510         ast::sty_uniq => {
511             // Pass the unique pointer.
512             match store {
513                 ty::UniqTraitStore => llself = llbox,
514                 _ => bcx.tcx().sess.bug("~self receiver with non-~Trait")
515             }
516
517             zero_mem(bcx, llboxptr, ty::mk_opaque_box(bcx.tcx()));
518         }
519     }
520
521     llself = PointerCast(bcx, llself, Type::opaque_box(ccx).ptr_to());
522     let scratch = scratch_datum(bcx, ty::mk_opaque_box(bcx.tcx()),
523                                 "__trait_callee", false);
524     Store(bcx, llself, scratch.val);
525     scratch.add_clean(bcx);
526
527     // Load the function from the vtable and cast it to the expected type.
528     debug!("(translating trait callee) loading method");
529     let llcallee_ty = type_of_fn_from_ty(ccx, callee_ty);
530
531     // Plus one in order to skip past the type descriptor.
532     let mptr = Load(bcx, GEPi(bcx, llvtable, [0u, n_method + 1]));
533
534     let mptr = PointerCast(bcx, mptr, llcallee_ty.ptr_to());
535
536     return Callee {
537         bcx: bcx,
538         data: Method(MethodData {
539             llfn: mptr,
540             llself: scratch.to_value_llval(bcx),
541             temp_cleanup: Some(scratch.val),
542             self_ty: scratch.ty,
543             self_mode: ty::ByCopy,
544             /* XXX: Some(llbox) */
545         })
546     };
547 }
548
549 pub fn vtable_id(ccx: @mut CrateContext,
550                  origin: &typeck::vtable_origin)
551               -> mono_id {
552     match origin {
553         &typeck::vtable_static(impl_id, ref substs, sub_vtables) => {
554             let psubsts = param_substs {
555                 tys: (*substs).clone(),
556                 vtables: Some(sub_vtables),
557                 self_ty: None,
558                 self_vtables: None
559             };
560
561             monomorphize::make_mono_id(
562                 ccx,
563                 impl_id,
564                 &psubsts,
565                 None)
566         }
567
568         // can't this be checked at the callee?
569         _ => fail!("vtable_id")
570     }
571 }
572
573 /// Creates a returns a dynamic vtable for the given type and vtable origin.
574 /// This is used only for objects.
575 pub fn get_vtable(bcx: @mut Block,
576                   self_ty: ty::t,
577                   origin: typeck::vtable_origin)
578                   -> ValueRef {
579     let hash_id = vtable_id(bcx.ccx(), &origin);
580     match bcx.ccx().vtables.find(&hash_id) {
581         Some(&val) => val,
582         None => {
583             match origin {
584                 typeck::vtable_static(id, substs, sub_vtables) => {
585                     make_impl_vtable(bcx, id, self_ty, substs, sub_vtables)
586                 }
587                 _ => fail!("get_vtable: expected a static origin"),
588             }
589         }
590     }
591 }
592
593 /// Helper function to declare and initialize the vtable.
594 pub fn make_vtable(ccx: &mut CrateContext,
595                    tydesc: &tydesc_info,
596                    ptrs: &[ValueRef])
597                    -> ValueRef {
598     unsafe {
599         let _icx = push_ctxt("impl::make_vtable");
600
601         let mut components = ~[ tydesc.tydesc ];
602         for &ptr in ptrs.iter() {
603             components.push(ptr)
604         }
605
606         let tbl = C_struct(components);
607         let vtable = ccx.sess.str_of(gensym_name("vtable"));
608         let vt_gvar = do vtable.to_c_str().with_ref |buf| {
609             llvm::LLVMAddGlobal(ccx.llmod, val_ty(tbl).to_ref(), buf)
610         };
611         llvm::LLVMSetInitializer(vt_gvar, tbl);
612         llvm::LLVMSetGlobalConstant(vt_gvar, lib::llvm::True);
613         lib::llvm::SetLinkage(vt_gvar, lib::llvm::InternalLinkage);
614         vt_gvar
615     }
616 }
617
618 /// Generates a dynamic vtable for objects.
619 pub fn make_impl_vtable(bcx: @mut Block,
620                         impl_id: ast::def_id,
621                         self_ty: ty::t,
622                         substs: &[ty::t],
623                         vtables: typeck::vtable_res)
624                         -> ValueRef {
625     let ccx = bcx.ccx();
626     let _icx = push_ctxt("impl::make_impl_vtable");
627     let tcx = ccx.tcx;
628
629     let trt_id = match ty::impl_trait_ref(tcx, impl_id) {
630         Some(t_id) => t_id.def_id,
631         None       => ccx.sess.bug("make_impl_vtable: don't know how to \
632                                     make a vtable for a type impl!")
633     };
634
635     let trait_method_def_ids = ty::trait_method_def_ids(tcx, trt_id);
636     let methods = do trait_method_def_ids.map |method_def_id| {
637         let im = ty::method(tcx, *method_def_id);
638         let fty = ty::subst_tps(tcx,
639                                 substs,
640                                 None,
641                                 ty::mk_bare_fn(tcx, im.fty.clone()));
642         if im.generics.has_type_params() || ty::type_has_self(fty) {
643             debug!("(making impl vtable) method has self or type params: %s",
644                    tcx.sess.str_of(im.ident));
645             C_null(Type::nil().ptr_to())
646         } else {
647             debug!("(making impl vtable) adding method to vtable: %s",
648                    tcx.sess.str_of(im.ident));
649             let m_id = method_with_name(ccx, impl_id, im.ident);
650
651             trans_fn_ref_with_vtables(bcx, m_id, 0,
652                                       substs, Some(vtables)).llfn
653         }
654     };
655
656     // Generate a type descriptor for the vtable.
657     let tydesc = get_tydesc(ccx, self_ty);
658     glue::lazily_emit_all_tydesc_glue(ccx, tydesc);
659
660     make_vtable(ccx, tydesc, methods)
661 }
662
663 pub fn trans_trait_cast(bcx: @mut Block,
664                         val: @ast::expr,
665                         id: ast::NodeId,
666                         dest: expr::Dest,
667                         _store: ty::TraitStore)
668                      -> @mut Block {
669     let mut bcx = bcx;
670     let _icx = push_ctxt("impl::trans_cast");
671
672     let lldest = match dest {
673         Ignore => {
674             return expr::trans_into(bcx, val, Ignore);
675         }
676         SaveIn(dest) => dest
677     };
678
679     let ccx = bcx.ccx();
680     let v_ty = expr_ty(bcx, val);
681
682     let mut llboxdest = GEPi(bcx, lldest, [0u, abi::trt_field_box]);
683     // Just store the pointer into the pair. (Region/borrowed
684     // and boxed trait objects are represented as pairs, and
685     // have no type descriptor field.)
686     llboxdest = PointerCast(bcx,
687                             llboxdest,
688                             type_of(bcx.ccx(), v_ty).ptr_to());
689     bcx = expr::trans_into(bcx, val, SaveIn(llboxdest));
690
691     // Store the vtable into the pair or triple.
692     let orig = ccx.maps.vtable_map.get(&id)[0][0].clone();
693     let orig = resolve_vtable_in_fn_ctxt(bcx.fcx, &orig);
694     let vtable = get_vtable(bcx, v_ty, orig);
695     Store(bcx, vtable, PointerCast(bcx,
696                                    GEPi(bcx, lldest, [0u, abi::trt_field_vtable]),
697                                    val_ty(vtable).ptr_to()));
698
699     bcx
700 }