]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/glue.rs
doc: remove incomplete sentence
[rust.git] / src / librustc_trans / trans / glue.rs
1 // Copyright 2012-2013 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 //
13 // Code relating to taking, dropping, etc as well as type descriptors.
14
15
16 use back::abi;
17 use back::link::*;
18 use llvm::{ValueRef, True, get_param};
19 use llvm;
20 use middle::lang_items::ExchangeFreeFnLangItem;
21 use middle::subst;
22 use middle::subst::{Subst, Substs};
23 use trans::adt;
24 use trans::base::*;
25 use trans::build::*;
26 use trans::callee;
27 use trans::cleanup;
28 use trans::cleanup::CleanupMethods;
29 use trans::common::*;
30 use trans::datum;
31 use trans::debuginfo;
32 use trans::expr;
33 use trans::machine::*;
34 use trans::tvec;
35 use trans::type_::Type;
36 use trans::type_of::{type_of, sizing_type_of, align_of};
37 use middle::ty::{mod, Ty};
38 use util::ppaux::{ty_to_short_str, Repr};
39 use util::ppaux;
40
41 use arena::TypedArena;
42 use std::c_str::ToCStr;
43 use libc::c_uint;
44 use syntax::ast;
45 use syntax::parse::token;
46
47 pub fn trans_exchange_free_dyn<'blk, 'tcx>(cx: Block<'blk, 'tcx>, v: ValueRef,
48                                            size: ValueRef, align: ValueRef)
49                                            -> Block<'blk, 'tcx> {
50     let _icx = push_ctxt("trans_exchange_free");
51     let ccx = cx.ccx();
52     callee::trans_lang_call(cx,
53         langcall(cx, None, "", ExchangeFreeFnLangItem),
54         &[PointerCast(cx, v, Type::i8p(ccx)), size, align],
55         Some(expr::Ignore)).bcx
56 }
57
58 pub fn trans_exchange_free<'blk, 'tcx>(cx: Block<'blk, 'tcx>, v: ValueRef,
59                                        size: u64, align: u32) -> Block<'blk, 'tcx> {
60     trans_exchange_free_dyn(cx, v, C_uint(cx.ccx(), size),
61                                    C_uint(cx.ccx(), align))
62 }
63
64 pub fn trans_exchange_free_ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ptr: ValueRef,
65                                           content_ty: Ty<'tcx>) -> Block<'blk, 'tcx> {
66     assert!(type_is_sized(bcx.ccx().tcx(), content_ty));
67     let sizing_type = sizing_type_of(bcx.ccx(), content_ty);
68     let content_size = llsize_of_alloc(bcx.ccx(), sizing_type);
69
70     // `Box<ZeroSizeType>` does not allocate.
71     if content_size != 0 {
72         let content_align = align_of(bcx.ccx(), content_ty);
73         trans_exchange_free(bcx, ptr, content_size, content_align)
74     } else {
75         bcx
76     }
77 }
78
79 pub fn get_drop_glue_type<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
80                                     t: Ty<'tcx>) -> Ty<'tcx> {
81     let tcx = ccx.tcx();
82     // Even if there is no dtor for t, there might be one deeper down and we
83     // might need to pass in the vtable ptr.
84     if !type_is_sized(tcx, t) {
85         return t
86     }
87     if !type_needs_drop(tcx, t) {
88         return tcx.types.i8;
89     }
90     match t.sty {
91         ty::ty_uniq(typ) if !type_needs_drop(tcx, typ)
92                          && type_is_sized(tcx, typ) => {
93             let llty = sizing_type_of(ccx, typ);
94             // `Box<ZeroSizeType>` does not allocate.
95             if llsize_of_alloc(ccx, llty) == 0 {
96                 tcx.types.i8
97             } else {
98                 t
99             }
100         }
101         _ => t
102     }
103 }
104
105 pub fn drop_ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
106                            v: ValueRef,
107                            t: Ty<'tcx>,
108                            source_location: Option<NodeInfo>)
109                            -> Block<'blk, 'tcx> {
110     // NB: v is an *alias* of type t here, not a direct value.
111     debug!("drop_ty(t={})", t.repr(bcx.tcx()));
112     let _icx = push_ctxt("drop_ty");
113     if type_needs_drop(bcx.tcx(), t) {
114         let ccx = bcx.ccx();
115         let glue = get_drop_glue(ccx, t);
116         let glue_type = get_drop_glue_type(ccx, t);
117         let ptr = if glue_type != t {
118             PointerCast(bcx, v, type_of(ccx, glue_type).ptr_to())
119         } else {
120             v
121         };
122
123         match source_location {
124             Some(sl) => debuginfo::set_source_location(bcx.fcx, sl.id, sl.span),
125             None => debuginfo::clear_source_location(bcx.fcx)
126         };
127
128         Call(bcx, glue, &[ptr], None);
129     }
130     bcx
131 }
132
133 pub fn drop_ty_immediate<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
134                                      v: ValueRef,
135                                      t: Ty<'tcx>,
136                                      source_location: Option<NodeInfo>)
137                                      -> Block<'blk, 'tcx> {
138     let _icx = push_ctxt("drop_ty_immediate");
139     let vp = alloca(bcx, type_of(bcx.ccx(), t), "");
140     Store(bcx, v, vp);
141     drop_ty(bcx, vp, t, source_location)
142 }
143
144 pub fn get_drop_glue<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> ValueRef {
145     debug!("make drop glue for {}", ppaux::ty_to_string(ccx.tcx(), t));
146     let t = get_drop_glue_type(ccx, t);
147     debug!("drop glue type {}", ppaux::ty_to_string(ccx.tcx(), t));
148     match ccx.drop_glues().borrow().get(&t) {
149         Some(&glue) => return glue,
150         _ => { }
151     }
152
153     let llty = if type_is_sized(ccx.tcx(), t) {
154         type_of(ccx, t).ptr_to()
155     } else {
156         type_of(ccx, ty::mk_uniq(ccx.tcx(), t)).ptr_to()
157     };
158
159     let llfnty = Type::glue_fn(ccx, llty);
160
161     let (glue, new_sym) = match ccx.available_drop_glues().borrow().get(&t) {
162         Some(old_sym) => {
163             let glue = decl_cdecl_fn(ccx, old_sym[], llfnty, ty::mk_nil(ccx.tcx()));
164             (glue, None)
165         },
166         None => {
167             let (sym, glue) = declare_generic_glue(ccx, t, llfnty, "drop");
168             (glue, Some(sym))
169         },
170     };
171
172     ccx.drop_glues().borrow_mut().insert(t, glue);
173
174     // To avoid infinite recursion, don't `make_drop_glue` until after we've
175     // added the entry to the `drop_glues` cache.
176     match new_sym {
177         Some(sym) => {
178             ccx.available_drop_glues().borrow_mut().insert(t, sym);
179             // We're creating a new drop glue, so also generate a body.
180             make_generic_glue(ccx, t, glue, make_drop_glue, "drop");
181         },
182         None => {},
183     }
184
185     glue
186 }
187
188 fn trans_struct_drop_flag<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
189                                       t: Ty<'tcx>,
190                                       v0: ValueRef,
191                                       dtor_did: ast::DefId,
192                                       class_did: ast::DefId,
193                                       substs: &subst::Substs<'tcx>)
194                                       -> Block<'blk, 'tcx> {
195     let repr = adt::represent_type(bcx.ccx(), t);
196     let struct_data = if type_is_sized(bcx.tcx(), t) {
197         v0
198     } else {
199         let llval = GEPi(bcx, v0, &[0, abi::FAT_PTR_ADDR]);
200         Load(bcx, llval)
201     };
202     let drop_flag = unpack_datum!(bcx, adt::trans_drop_flag_ptr(bcx, &*repr, struct_data));
203     with_cond(bcx, load_ty(bcx, drop_flag.val, bcx.tcx().types.bool), |cx| {
204         trans_struct_drop(cx, t, v0, dtor_did, class_did, substs)
205     })
206 }
207
208 fn trans_struct_drop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
209                                  t: Ty<'tcx>,
210                                  v0: ValueRef,
211                                  dtor_did: ast::DefId,
212                                  class_did: ast::DefId,
213                                  substs: &subst::Substs<'tcx>)
214                                  -> Block<'blk, 'tcx> {
215     let repr = adt::represent_type(bcx.ccx(), t);
216
217     // Find and call the actual destructor
218     let dtor_addr = get_res_dtor(bcx.ccx(), dtor_did, t,
219                                  class_did, substs);
220
221     // The first argument is the "self" argument for drop
222     let params = unsafe {
223         let ty = Type::from_ref(llvm::LLVMTypeOf(dtor_addr));
224         ty.element_type().func_params()
225     };
226
227     let fty = ty::lookup_item_type(bcx.tcx(), dtor_did).ty.subst(bcx.tcx(), substs);
228     let self_ty = match fty.sty {
229         ty::ty_bare_fn(_, ref f) => {
230             assert!(f.sig.0.inputs.len() == 1);
231             f.sig.0.inputs[0]
232         }
233         _ => bcx.sess().bug(format!("Expected function type, found {}",
234                                     bcx.ty_to_string(fty))[])
235     };
236
237     let (struct_data, info) = if type_is_sized(bcx.tcx(), t) {
238         (v0, None)
239     } else {
240         let data = GEPi(bcx, v0, &[0, abi::FAT_PTR_ADDR]);
241         let info = GEPi(bcx, v0, &[0, abi::FAT_PTR_EXTRA]);
242         (Load(bcx, data), Some(Load(bcx, info)))
243     };
244
245     adt::fold_variants(bcx, &*repr, struct_data, |variant_cx, st, value| {
246         // Be sure to put all of the fields into a scope so we can use an invoke
247         // instruction to call the user destructor but still call the field
248         // destructors if the user destructor panics.
249         let field_scope = variant_cx.fcx.push_custom_cleanup_scope();
250
251         // Class dtors have no explicit args, so the params should
252         // just consist of the environment (self).
253         assert_eq!(params.len(), 1);
254         let self_arg = if type_is_fat_ptr(bcx.tcx(), self_ty) {
255             // The dtor expects a fat pointer, so make one, even if we have to fake it.
256             let boxed_ty = ty::mk_open(bcx.tcx(), t);
257             let scratch = datum::rvalue_scratch_datum(bcx, boxed_ty, "__fat_ptr_drop_self");
258             Store(bcx, value, GEPi(bcx, scratch.val, &[0, abi::FAT_PTR_ADDR]));
259             Store(bcx,
260                   // If we just had a thin pointer, make a fat pointer by sticking
261                   // null where we put the unsizing info. This works because t
262                   // is a sized type, so we will only unpack the fat pointer, never
263                   // use the fake info.
264                   info.unwrap_or(C_null(Type::i8p(bcx.ccx()))),
265                   GEPi(bcx, scratch.val, &[0, abi::FAT_PTR_EXTRA]));
266             PointerCast(variant_cx, scratch.val, params[0])
267         } else {
268             PointerCast(variant_cx, value, params[0])
269         };
270         let args = vec!(self_arg);
271
272         // Add all the fields as a value which needs to be cleaned at the end of
273         // this scope. Iterate in reverse order so a Drop impl doesn't reverse
274         // the order in which fields get dropped.
275         for (i, ty) in st.fields.iter().enumerate().rev() {
276             let llfld_a = adt::struct_field_ptr(variant_cx, &*st, value, i, false);
277
278             let val = if type_is_sized(bcx.tcx(), *ty) {
279                 llfld_a
280             } else {
281                 let boxed_ty = ty::mk_open(bcx.tcx(), *ty);
282                 let scratch = datum::rvalue_scratch_datum(bcx, boxed_ty, "__fat_ptr_drop_field");
283                 Store(bcx, llfld_a, GEPi(bcx, scratch.val, &[0, abi::FAT_PTR_ADDR]));
284                 Store(bcx, info.unwrap(), GEPi(bcx, scratch.val, &[0, abi::FAT_PTR_EXTRA]));
285                 scratch.val
286             };
287             variant_cx.fcx.schedule_drop_mem(cleanup::CustomScope(field_scope),
288                                              val, *ty);
289         }
290
291         let dtor_ty = ty::mk_ctor_fn(bcx.tcx(),
292                                      class_did,
293                                      &[get_drop_glue_type(bcx.ccx(), t)],
294                                      ty::mk_nil(bcx.tcx()));
295         let (_, variant_cx) = invoke(variant_cx, dtor_addr, args[], dtor_ty, None);
296
297         variant_cx.fcx.pop_and_trans_custom_cleanup_scope(variant_cx, field_scope);
298         variant_cx
299     })
300 }
301
302 fn size_and_align_of_dst<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, t: Ty<'tcx>, info: ValueRef)
303                                      -> (ValueRef, ValueRef) {
304     debug!("calculate size of DST: {}; with lost info: {}",
305            bcx.ty_to_string(t), bcx.val_to_string(info));
306     if type_is_sized(bcx.tcx(), t) {
307         let sizing_type = sizing_type_of(bcx.ccx(), t);
308         let size = C_uint(bcx.ccx(), llsize_of_alloc(bcx.ccx(), sizing_type));
309         let align = C_uint(bcx.ccx(), align_of(bcx.ccx(), t));
310         return (size, align);
311     }
312     match t.sty {
313         ty::ty_struct(id, substs) => {
314             let ccx = bcx.ccx();
315             // First get the size of all statically known fields.
316             // Don't use type_of::sizing_type_of because that expects t to be sized.
317             assert!(!ty::type_is_simd(bcx.tcx(), t));
318             let repr = adt::represent_type(ccx, t);
319             let sizing_type = adt::sizing_type_of(ccx, &*repr, true);
320             let sized_size = C_uint(ccx, llsize_of_alloc(ccx, sizing_type));
321             let sized_align = C_uint(ccx, llalign_of_min(ccx, sizing_type));
322
323             // Recurse to get the size of the dynamically sized field (must be
324             // the last field).
325             let fields = ty::struct_fields(bcx.tcx(), id, substs);
326             let last_field = fields[fields.len()-1];
327             let field_ty = last_field.mt.ty;
328             let (unsized_size, unsized_align) = size_and_align_of_dst(bcx, field_ty, info);
329
330             // Return the sum of sizes and max of aligns.
331             let size = Add(bcx, sized_size, unsized_size);
332             let align = Select(bcx,
333                                ICmp(bcx, llvm::IntULT, sized_align, unsized_align),
334                                sized_align,
335                                unsized_align);
336             (size, align)
337         }
338         ty::ty_trait(..) => {
339             // info points to the vtable and the second entry in the vtable is the
340             // dynamic size of the object.
341             let info = PointerCast(bcx, info, Type::int(bcx.ccx()).ptr_to());
342             let size_ptr = GEPi(bcx, info, &[1u]);
343             let align_ptr = GEPi(bcx, info, &[2u]);
344             (Load(bcx, size_ptr), Load(bcx, align_ptr))
345         }
346         ty::ty_vec(unit_ty, None) => {
347             // The info in this case is the length of the vec, so the size is that
348             // times the unit size.
349             let llunit_ty = sizing_type_of(bcx.ccx(), unit_ty);
350             let unit_size = llsize_of_alloc(bcx.ccx(), llunit_ty);
351             (Mul(bcx, info, C_uint(bcx.ccx(), unit_size)), C_uint(bcx.ccx(), 8u))
352         }
353         _ => bcx.sess().bug(format!("Unexpected unsized type, found {}",
354                                     bcx.ty_to_string(t))[])
355     }
356 }
357
358 fn make_drop_glue<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, v0: ValueRef, t: Ty<'tcx>)
359                               -> Block<'blk, 'tcx> {
360     // NB: v0 is an *alias* of type t here, not a direct value.
361     let _icx = push_ctxt("make_drop_glue");
362     match t.sty {
363         ty::ty_uniq(content_ty) => {
364             match content_ty.sty {
365                 ty::ty_vec(ty, None) => {
366                     tvec::make_drop_glue_unboxed(bcx, v0, ty, true)
367                 }
368                 ty::ty_str => {
369                     let unit_ty = ty::sequence_element_type(bcx.tcx(), content_ty);
370                     tvec::make_drop_glue_unboxed(bcx, v0, unit_ty, true)
371                 }
372                 ty::ty_trait(..) => {
373                     let lluniquevalue = GEPi(bcx, v0, &[0, abi::FAT_PTR_ADDR]);
374                     // Only drop the value when it is non-null
375                     let concrete_ptr = Load(bcx, lluniquevalue);
376                     with_cond(bcx, IsNotNull(bcx, concrete_ptr), |bcx| {
377                         let dtor_ptr = Load(bcx, GEPi(bcx, v0, &[0, abi::FAT_PTR_EXTRA]));
378                         let dtor = Load(bcx, dtor_ptr);
379                         Call(bcx,
380                              dtor,
381                              &[PointerCast(bcx, lluniquevalue, Type::i8p(bcx.ccx()))],
382                              None);
383                         bcx
384                     })
385                 }
386                 ty::ty_struct(..) if !type_is_sized(bcx.tcx(), content_ty) => {
387                     let llval = GEPi(bcx, v0, &[0, abi::FAT_PTR_ADDR]);
388                     let llbox = Load(bcx, llval);
389                     let not_null = IsNotNull(bcx, llbox);
390                     with_cond(bcx, not_null, |bcx| {
391                         let bcx = drop_ty(bcx, v0, content_ty, None);
392                         let info = GEPi(bcx, v0, &[0, abi::FAT_PTR_EXTRA]);
393                         let info = Load(bcx, info);
394                         let (llsize, llalign) = size_and_align_of_dst(bcx, content_ty, info);
395                         trans_exchange_free_dyn(bcx, llbox, llsize, llalign)
396                     })
397                 }
398                 _ => {
399                     assert!(type_is_sized(bcx.tcx(), content_ty));
400                     let llval = v0;
401                     let llbox = Load(bcx, llval);
402                     let not_null = IsNotNull(bcx, llbox);
403                     with_cond(bcx, not_null, |bcx| {
404                         let bcx = drop_ty(bcx, llbox, content_ty, None);
405                         trans_exchange_free_ty(bcx, llbox, content_ty)
406                     })
407                 }
408             }
409         }
410         ty::ty_struct(did, substs) | ty::ty_enum(did, substs) => {
411             let tcx = bcx.tcx();
412             match ty::ty_dtor(tcx, did) {
413                 ty::TraitDtor(dtor, true) => {
414                     // FIXME(16758) Since the struct is unsized, it is hard to
415                     // find the drop flag (which is at the end of the struct).
416                     // Lets just ignore the flag and pretend everything will be
417                     // OK.
418                     if type_is_sized(bcx.tcx(), t) {
419                         trans_struct_drop_flag(bcx, t, v0, dtor, did, substs)
420                     } else {
421                         // Give the user a heads up that we are doing something
422                         // stupid and dangerous.
423                         bcx.sess().warn(format!("Ignoring drop flag in destructor for {}\
424                                                  because the struct is unsized. See issue\
425                                                  #16758",
426                                                 bcx.ty_to_string(t))[]);
427                         trans_struct_drop(bcx, t, v0, dtor, did, substs)
428                     }
429                 }
430                 ty::TraitDtor(dtor, false) => {
431                     trans_struct_drop(bcx, t, v0, dtor, did, substs)
432                 }
433                 ty::NoDtor => {
434                     // No dtor? Just the default case
435                     iter_structural_ty(bcx, v0, t, |bb, vv, tt| drop_ty(bb, vv, tt, None))
436                 }
437             }
438         }
439         ty::ty_unboxed_closure(..) => iter_structural_ty(bcx,
440                                                          v0,
441                                                          t,
442                                                          |bb, vv, tt| drop_ty(bb, vv, tt, None)),
443         ty::ty_closure(ref f) if f.store == ty::UniqTraitStore => {
444             let box_cell_v = GEPi(bcx, v0, &[0u, abi::FAT_PTR_EXTRA]);
445             let env = Load(bcx, box_cell_v);
446             let env_ptr_ty = Type::at_box(bcx.ccx(), Type::i8(bcx.ccx())).ptr_to();
447             let env = PointerCast(bcx, env, env_ptr_ty);
448             with_cond(bcx, IsNotNull(bcx, env), |bcx| {
449                 let dtor_ptr = GEPi(bcx, env, &[0u, abi::BOX_FIELD_DROP_GLUE]);
450                 let dtor = Load(bcx, dtor_ptr);
451                 Call(bcx, dtor, &[PointerCast(bcx, box_cell_v, Type::i8p(bcx.ccx()))], None);
452                 bcx
453             })
454         }
455         ty::ty_trait(..) => {
456             // No need to do a null check here (as opposed to the Box<trait case
457             // above), because this happens for a trait field in an unsized
458             // struct. If anything is null, it is the whole struct and we won't
459             // get here.
460             let lluniquevalue = GEPi(bcx, v0, &[0, abi::FAT_PTR_ADDR]);
461             let dtor_ptr = Load(bcx, GEPi(bcx, v0, &[0, abi::FAT_PTR_EXTRA]));
462             let dtor = Load(bcx, dtor_ptr);
463             Call(bcx,
464                  dtor,
465                  &[PointerCast(bcx, Load(bcx, lluniquevalue), Type::i8p(bcx.ccx()))],
466                  None);
467             bcx
468         }
469         ty::ty_vec(ty, None) => tvec::make_drop_glue_unboxed(bcx, v0, ty, false),
470         _ => {
471             assert!(type_is_sized(bcx.tcx(), t));
472             if type_needs_drop(bcx.tcx(), t) &&
473                 ty::type_is_structural(t) {
474                 iter_structural_ty(bcx, v0, t, |bb, vv, tt| drop_ty(bb, vv, tt, None))
475             } else {
476                 bcx
477             }
478         }
479     }
480 }
481
482 // Generates the declaration for (but doesn't emit) a type descriptor.
483 pub fn declare_tydesc<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>)
484                                 -> tydesc_info<'tcx> {
485     // If emit_tydescs already ran, then we shouldn't be creating any new
486     // tydescs.
487     assert!(!ccx.finished_tydescs().get());
488
489     let llty = type_of(ccx, t);
490
491     if ccx.sess().count_type_sizes() {
492         println!("{}\t{}", llsize_of_real(ccx, llty),
493                  ppaux::ty_to_string(ccx.tcx(), t));
494     }
495
496     let llsize = llsize_of(ccx, llty);
497     let llalign = llalign_of(ccx, llty);
498     let name = mangle_internal_name_by_type_and_seq(ccx, t, "tydesc");
499     debug!("+++ declare_tydesc {} {}", ppaux::ty_to_string(ccx.tcx(), t), name);
500     let gvar = name.with_c_str(|buf| {
501         unsafe {
502             llvm::LLVMAddGlobal(ccx.llmod(), ccx.tydesc_type().to_ref(), buf)
503         }
504     });
505     note_unique_llvm_symbol(ccx, name);
506
507     let ty_name = token::intern_and_get_ident(
508         ppaux::ty_to_string(ccx.tcx(), t)[]);
509     let ty_name = C_str_slice(ccx, ty_name);
510
511     debug!("--- declare_tydesc {}", ppaux::ty_to_string(ccx.tcx(), t));
512     tydesc_info {
513         ty: t,
514         tydesc: gvar,
515         size: llsize,
516         align: llalign,
517         name: ty_name,
518     }
519 }
520
521 fn declare_generic_glue<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>,
522                                   llfnty: Type, name: &str) -> (String, ValueRef) {
523     let _icx = push_ctxt("declare_generic_glue");
524     let fn_nm = mangle_internal_name_by_type_and_seq(
525         ccx,
526         t,
527         format!("glue_{}", name)[]);
528     let llfn = decl_cdecl_fn(ccx, fn_nm[], llfnty, ty::mk_nil(ccx.tcx()));
529     note_unique_llvm_symbol(ccx, fn_nm.clone());
530     return (fn_nm, llfn);
531 }
532
533 fn make_generic_glue<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
534                                t: Ty<'tcx>,
535                                llfn: ValueRef,
536                                helper: for<'blk> |Block<'blk, 'tcx>, ValueRef, Ty<'tcx>|
537                                                   -> Block<'blk, 'tcx>,
538                                name: &str)
539                                -> ValueRef {
540     let _icx = push_ctxt("make_generic_glue");
541     let glue_name = format!("glue {} {}", name, ty_to_short_str(ccx.tcx(), t));
542     let _s = StatRecorder::new(ccx, glue_name);
543
544     let arena = TypedArena::new();
545     let empty_param_substs = Substs::trans_empty();
546     let fcx = new_fn_ctxt(ccx, llfn, ast::DUMMY_NODE_ID, false,
547                           ty::FnConverging(ty::mk_nil(ccx.tcx())),
548                           &empty_param_substs, None, &arena);
549
550     let bcx = init_function(&fcx, false, ty::FnConverging(ty::mk_nil(ccx.tcx())));
551
552     update_linkage(ccx, llfn, None, OriginalTranslation);
553
554     ccx.stats().n_glues_created.set(ccx.stats().n_glues_created.get() + 1u);
555     // All glue functions take values passed *by alias*; this is a
556     // requirement since in many contexts glue is invoked indirectly and
557     // the caller has no idea if it's dealing with something that can be
558     // passed by value.
559     //
560     // llfn is expected be declared to take a parameter of the appropriate
561     // type, so we don't need to explicitly cast the function parameter.
562
563     let llrawptr0 = get_param(llfn, fcx.arg_pos(0) as c_uint);
564     let bcx = helper(bcx, llrawptr0, t);
565     finish_fn(&fcx, bcx, ty::FnConverging(ty::mk_nil(ccx.tcx())));
566
567     llfn
568 }
569
570 pub fn emit_tydescs(ccx: &CrateContext) {
571     let _icx = push_ctxt("emit_tydescs");
572     // As of this point, allow no more tydescs to be created.
573     ccx.finished_tydescs().set(true);
574     let glue_fn_ty = Type::generic_glue_fn(ccx).ptr_to();
575     for (_, ti) in ccx.tydescs().borrow().iter() {
576         // Each of the glue functions needs to be cast to a generic type
577         // before being put into the tydesc because we only have a singleton
578         // tydesc type. Then we'll recast each function to its real type when
579         // calling it.
580         let drop_glue = unsafe {
581             llvm::LLVMConstPointerCast(get_drop_glue(ccx, ti.ty), glue_fn_ty.to_ref())
582         };
583         ccx.stats().n_real_glues.set(ccx.stats().n_real_glues.get() + 1);
584
585         let tydesc = C_named_struct(ccx.tydesc_type(),
586                                     &[ti.size, // size
587                                       ti.align, // align
588                                       drop_glue, // drop_glue
589                                       ti.name]); // name
590
591         unsafe {
592             let gvar = ti.tydesc;
593             llvm::LLVMSetInitializer(gvar, tydesc);
594             llvm::LLVMSetGlobalConstant(gvar, True);
595             llvm::SetLinkage(gvar, llvm::InternalLinkage);
596         }
597     };
598 }