]> git.lizzy.rs Git - rust.git/blob - src/comp/middle/trans_closure.rs
modify last use to take into account cap clause, add new test
[rust.git] / src / comp / middle / trans_closure.rs
1 import syntax::ast;
2 import syntax::ast_util;
3 import lib::llvm::llvm;
4 import llvm::{ValueRef, TypeRef};
5 import trans_common::*;
6 import trans_build::*;
7 import trans::*;
8 import middle::freevars::{get_freevars, freevar_info};
9 import option::{some, none};
10 import back::abi;
11 import syntax::codemap::span;
12 import syntax::print::pprust::expr_to_str;
13 import back::link::{
14     mangle_internal_name_by_path,
15     mangle_internal_name_by_path_and_seq};
16 import util::ppaux::ty_to_str;
17 import trans::{
18     trans_shared_malloc,
19     type_of_inner,
20     size_of,
21     node_id_type,
22     INIT,
23     trans_shared_free,
24     drop_ty,
25     new_sub_block_ctxt,
26     load_if_immediate,
27     dest
28 };
29
30 // ___Good to know (tm)__________________________________________________
31 //
32 // The layout of a closure environment in memory is
33 // roughly as follows:
34 //
35 // struct closure_box {
36 //   unsigned ref_count; // only used for shared environments
37 //   type_desc *tydesc;  // descriptor for the "struct closure_box" type
38 //   type_desc *bound_tdescs[]; // bound descriptors
39 //   struct {
40 //     upvar1_t upvar1;
41 //     ...
42 //     upvarN_t upvarN;
43 //   } bound_data;
44 // };
45 //
46 // Note that the closure carries a type descriptor that describes the
47 // closure itself.  Trippy.  This is needed because the precise types
48 // of the closed over data are lost in the closure type (`fn(T)->U`),
49 // so if we need to take/drop, we must know what data is in the upvars
50 // and so forth.  This struct is defined in the code in mk_closure_tys()
51 // below.
52 //
53 // The allocation strategy for this closure depends on the closure
54 // type.  For a sendfn, the closure (and the referenced type
55 // descriptors) will be allocated in the exchange heap.  For a fn, the
56 // closure is allocated in the task heap and is reference counted.
57 // For a block, the closure is allocated on the stack.  Note that in
58 // all cases we allocate space for a ref count just to make our lives
59 // easier when upcasting to block(T)->U, in the shape code, and so
60 // forth.
61 //
62 // ## Opaque Closures ##
63 //
64 // One interesting part of closures is that they encapsulate the data
65 // that they close over.  So when I have a ptr to a closure, I do not
66 // know how many type descriptors it contains nor what upvars are
67 // captured within.  That means I do not know precisely how big it is
68 // nor where its fields are located.  This is called an "opaque
69 // closure".
70 //
71 // Typically an opaque closure suffices because I only manipulate it
72 // by ptr.  The routine trans_common::T_opaque_cbox_ptr() returns an
73 // appropriate type for such an opaque closure; it allows access to the
74 // first two fields, but not the others.
75 //
76 // But sometimes, such as when cloning or freeing a closure, we need
77 // to know the full information.  That is where the type descriptor
78 // that defines the closure comes in handy.  We can use its take and
79 // drop glue functions to allocate/free data as needed.
80 //
81 // ## Subtleties concerning alignment ##
82 //
83 // You'll note that the closure_box structure is a flat structure with
84 // four fields.  In some ways, it would be more convenient to use a nested
85 // structure like so:
86 //
87 // struct {
88 //   int;
89 //   struct {
90 //     type_desc*;
91 //     type_desc*[];
92 //     bound_data;
93 // } }
94 //
95 // This would be more convenient because it would allow us to use more
96 // of the existing infrastructure: we could treat the inner struct as
97 // a type and then hvae a boxed variant (which would add the int) etc.
98 // However, there is one subtle problem with this: grouping the latter
99 // 3 fields into an inner struct causes the alignment of the entire
100 // struct to be the max alignment of the bound_data.  This will
101 // therefore vary from closure to closure.  That would mean that we
102 // cannot reliably locate the initial type_desc* in an opaque closure!
103 // That's definitely a bad thing.  Therefore, I have elected to create
104 // a flat structure, even though it means some mild amount of code
105 // duplication (however, we used to do it the other way, and we were
106 // jumping through about as many hoops just trying to wedge a ref
107 // count into a unique pointer, so it's kind of a wash in the end).
108 //
109 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
110
111 tag environment_value {
112     // Evaluate expr and store result in env (used for bind).
113     env_expr(@ast::expr);
114
115     // Copy the value from this llvm ValueRef into the environment.
116     env_copy(ValueRef, ty::t, lval_kind);
117
118     // Move the value from this llvm ValueRef into the environment.
119     env_move(ValueRef, ty::t, lval_kind);
120
121     // Access by reference (used for blocks).
122     env_ref(ValueRef, ty::t, lval_kind);
123 }
124
125 fn ev_to_str(ccx: @crate_ctxt, ev: environment_value) -> str {
126     alt ev {
127       env_expr(ex) { expr_to_str(ex) }
128       env_copy(v, t, lk) { #fmt("copy(%s,%s)", val_str(ccx.tn, v),
129                                 ty_to_str(ccx.tcx, t)) }
130       env_move(v, t, lk) { #fmt("move(%s,%s)", val_str(ccx.tn, v),
131                                 ty_to_str(ccx.tcx, t)) }
132       env_ref(v, t, lk) { #fmt("ref(%s,%s)", val_str(ccx.tn, v),
133                                 ty_to_str(ccx.tcx, t)) }
134     }
135 }
136
137 fn mk_tydesc_ty(tcx: ty::ctxt, ck: ty::closure_kind) -> ty::t {
138     ret alt ck {
139       ty::closure_block. | ty::closure_shared. { ty::mk_type(tcx) }
140       ty::closure_send. { ty::mk_send_type(tcx) }
141     };
142 }
143
144 // Given a closure ty, emits a corresponding tuple ty
145 fn mk_closure_tys(tcx: ty::ctxt,
146                   ck: ty::closure_kind,
147                   ty_params: [fn_ty_param],
148                   bound_values: [environment_value])
149     -> (ty::t, ty::t, [ty::t]) {
150     let bound_tys = [];
151
152     let tydesc_ty =
153         mk_tydesc_ty(tcx, ck);
154
155     // Compute the closed over tydescs
156     let param_ptrs = [];
157     for tp in ty_params {
158         param_ptrs += [tydesc_ty];
159         option::may(tp.dicts) {|dicts|
160             for dict in dicts { param_ptrs += [tydesc_ty]; }
161         }
162     }
163
164     // Compute the closed over data
165     for bv in bound_values {
166         bound_tys += [alt bv {
167             env_copy(_, t, _) { t }
168             env_move(_, t, _) { t }
169             env_ref(_, t, _) { t }
170             env_expr(e) { ty::expr_ty(tcx, e) }
171         }];
172     }
173     let bound_data_ty = ty::mk_tup(tcx, bound_tys);
174
175     let norc_tys = [tydesc_ty, ty::mk_tup(tcx, param_ptrs), bound_data_ty];
176
177     // closure_norc_ty == everything but ref count
178     //
179     // This is a hack to integrate with the cycle coll.  When you
180     // allocate memory in the task-local space, you are expected to
181     // provide a descriptor for that memory which excludes the ref
182     // count. That's what this represents.  However, this really
183     // assumes a type setup like [uint, data] where data can be a
184     // struct.  We don't use that structure here because we don't want
185     // to alignment of the first few fields being bound up in the
186     // alignment of the bound data, as would happen if we laid out
187     // that way.  For now this should be fine but ultimately we need
188     // to modify CC code or else modify box allocation interface to be
189     // a bit more flexible, perhaps taking a vec of tys in the box
190     // (which for normal rust code is always of length 1).
191     let closure_norc_ty = ty::mk_tup(tcx, norc_tys);
192
193     #debug["closure_norc_ty=%s", ty_to_str(tcx, closure_norc_ty)];
194
195     // closure_ty == ref count, data tydesc, typarams, bound data
196     let closure_ty = ty::mk_tup(tcx, [ty::mk_int(tcx)] + norc_tys);
197
198     #debug["closure_ty=%s", ty_to_str(tcx, closure_norc_ty)];
199
200     ret (closure_ty, closure_norc_ty, bound_tys);
201 }
202
203 fn allocate_cbox(bcx: @block_ctxt,
204                  ck: ty::closure_kind,
205                  cbox_ty: ty::t,
206                  cbox_norc_ty: ty::t)
207     -> (@block_ctxt, ValueRef, [ValueRef]) {
208
209     let ccx = bcx_ccx(bcx);
210
211     let alloc_in_heap = lambda(bcx: @block_ctxt,
212                                xchgheap: bool,
213                                &temp_cleanups: [ValueRef])
214         -> (@block_ctxt, ValueRef) {
215
216         // n.b. If you are wondering why we don't use
217         // trans_malloc_boxed() or alloc_uniq(), see the section about
218         // "Subtleties concerning alignment" in the big comment at the
219         // top of the file.
220
221         let {bcx, val:llsz} = size_of(bcx, cbox_ty);
222         let ti = none;
223         let tydesc_ty = if xchgheap { cbox_ty } else { cbox_norc_ty };
224         let {bcx, val:lltydesc} =
225             get_tydesc(bcx, tydesc_ty, true, tps_normal, ti).result;
226         let malloc = {
227             if xchgheap { ccx.upcalls.shared_malloc}
228             else { ccx.upcalls.malloc }
229         };
230         let box = Call(bcx, malloc, [llsz, lltydesc]);
231         add_clean_free(bcx, box, xchgheap);
232         temp_cleanups += [box];
233         (bcx, box)
234     };
235
236     // Allocate the box:
237     let temp_cleanups = [];
238     let (bcx, box, rc) = alt ck {
239       ty::closure_shared. {
240         let (bcx, box) = alloc_in_heap(bcx, false, temp_cleanups);
241         (bcx, box, 1)
242       }
243       ty::closure_send. {
244         let (bcx, box) = alloc_in_heap(bcx, true, temp_cleanups);
245         (bcx, box, 0x12345678) // use arbitrary value for debugging
246       }
247       ty::closure_block. {
248         let {bcx, val: box} = trans::alloc_ty(bcx, cbox_ty);
249         (bcx, box, 0x12345678) // use arbitrary value for debugging
250       }
251     };
252
253     // Initialize ref count
254     let box = PointerCast(bcx, box, T_opaque_cbox_ptr(ccx));
255     let ref_cnt = GEPi(bcx, box, [0, abi::box_rc_field_refcnt]);
256     Store(bcx, C_int(ccx, rc), ref_cnt);
257
258     ret (bcx, box, temp_cleanups);
259 }
260
261 type closure_result = {
262     llbox: ValueRef,     // llvalue of ptr to closure
263     cboxptr_ty: ty::t,   // type of ptr to closure
264     bcx: @block_ctxt     // final bcx
265 };
266
267 fn cast_if_we_can(bcx: @block_ctxt, llbox: ValueRef, t: ty::t) -> ValueRef {
268     let ccx = bcx_ccx(bcx);
269     if check type_has_static_size(ccx, t) {
270         let llty = type_of(ccx, bcx.sp, t);
271         ret PointerCast(bcx, llbox, llty);
272     } else {
273         ret llbox;
274     }
275 }
276
277 // Given a block context and a list of tydescs and values to bind
278 // construct a closure out of them. If copying is true, it is a
279 // heap allocated closure that copies the upvars into environment.
280 // Otherwise, it is stack allocated and copies pointers to the upvars.
281 fn store_environment(
282     bcx: @block_ctxt, lltyparams: [fn_ty_param],
283     bound_values: [environment_value],
284     ck: ty::closure_kind)
285     -> closure_result {
286
287     fn maybe_clone_tydesc(bcx: @block_ctxt,
288                           ck: ty::closure_kind,
289                           td: ValueRef) -> ValueRef {
290         ret alt ck {
291           ty::closure_block. | ty::closure_shared. {
292             td
293           }
294           ty::closure_send. {
295             Call(bcx, bcx_ccx(bcx).upcalls.create_shared_type_desc, [td])
296           }
297         };
298     }
299
300     let ccx = bcx_ccx(bcx);
301     let tcx = bcx_tcx(bcx);
302
303     // compute the shape of the closure
304     let (cbox_ty, cbox_norc_ty, bound_tys) =
305         mk_closure_tys(tcx, ck, lltyparams, bound_values);
306
307     // allocate closure in the heap
308     let (bcx, llbox, temp_cleanups) =
309         allocate_cbox(bcx, ck, cbox_ty, cbox_norc_ty);
310
311     // store data tydesc.
312     alt ck {
313       ty::closure_shared. | ty::closure_send. {
314         let bound_tydesc = GEPi(bcx, llbox, [0, abi::cbox_elt_tydesc]);
315         let ti = none;
316
317         // NDM I believe this is the correct value,
318         // but using it exposes bugs and limitations
319         // in the shape code.  Therefore, I am using
320         // tps_normal, which is what we used before.
321         //
322         // let tps = tps_fn(vec::len(lltyparams));
323
324         let tps = tps_normal;
325         let {result:closure_td, _} =
326             trans::get_tydesc(bcx, cbox_ty, true, tps, ti);
327         trans::lazily_emit_tydesc_glue(bcx, abi::tydesc_field_take_glue, ti);
328         trans::lazily_emit_tydesc_glue(bcx, abi::tydesc_field_drop_glue, ti);
329         trans::lazily_emit_tydesc_glue(bcx, abi::tydesc_field_free_glue, ti);
330         bcx = closure_td.bcx;
331         let td = maybe_clone_tydesc(bcx, ck, closure_td.val);
332         Store(bcx, td, bound_tydesc);
333       }
334       ty::closure_block. { /* skip this for blocks, not really relevant */ }
335     }
336
337     // cbox_ty has the form of a tuple: (a, b, c) we want a ptr to a
338     // tuple.  This could be a ptr in uniq or a box or on stack,
339     // whatever.
340     let cboxptr_ty = ty::mk_ptr(tcx, {ty:cbox_ty, mut:ast::imm});
341     let llbox = cast_if_we_can(bcx, llbox, cboxptr_ty);
342     check type_is_tup_like(bcx, cboxptr_ty);
343
344     // If necessary, copy tydescs describing type parameters into the
345     // appropriate slot in the closure.
346     let {bcx:bcx, val:ty_params_slot} =
347         GEP_tup_like_1(bcx, cboxptr_ty, llbox, [0, abi::cbox_elt_ty_params]);
348     let off = 0;
349     for tp in lltyparams {
350         let cloned_td = maybe_clone_tydesc(bcx, ck, tp.desc);
351         Store(bcx, cloned_td, GEPi(bcx, ty_params_slot, [0, off]));
352         off += 1;
353         option::may(tp.dicts, {|dicts|
354             for dict in dicts {
355                 let cast = PointerCast(bcx, dict, val_ty(cloned_td));
356                 Store(bcx, cast, GEPi(bcx, ty_params_slot, [0, off]));
357                 off += 1;
358             }
359         });
360     }
361
362     // Copy expr values into boxed bindings.
363     // Silly check
364     let {bcx: bcx, val:bindings_slot} =
365         GEP_tup_like_1(bcx, cboxptr_ty, llbox, [0, abi::cbox_elt_bindings]);
366     vec::iteri(bound_values) { |i, bv|
367         if (!ccx.sess.get_opts().no_asm_comments) {
368             add_comment(bcx, #fmt("Copy %s into closure",
369                                   ev_to_str(ccx, bv)));
370         }
371
372         let bound_data = GEPi(bcx, bindings_slot, [0, i as int]);
373         alt bv {
374           env_expr(e) {
375             bcx = trans::trans_expr_save_in(bcx, e, bound_data);
376             add_clean_temp_mem(bcx, bound_data, bound_tys[i]);
377             temp_cleanups += [bound_data];
378           }
379           env_copy(val, ty, owned.) {
380             let val1 = load_if_immediate(bcx, val, ty);
381             bcx = trans::copy_val(bcx, INIT, bound_data, val1, ty);
382           }
383           env_copy(val, ty, owned_imm.) {
384             bcx = trans::copy_val(bcx, INIT, bound_data, val, ty);
385           }
386           env_copy(_, _, temporary.) {
387             fail "Cannot capture temporary upvar";
388           }
389           env_move(val, ty, kind) {
390             let src = {bcx:bcx, val:val, kind:kind};
391             bcx = move_val(bcx, INIT, bound_data, src, ty);
392           }
393           env_ref(val, ty, owned.) {
394             Store(bcx, val, bound_data);
395           }
396           env_ref(val, ty, owned_imm.) {
397             let addr = do_spill_noroot(bcx, val);
398             Store(bcx, addr, bound_data);
399           }
400           env_ref(_, _, temporary.) {
401             fail "Cannot capture temporary upvar";
402           }
403         }
404     }
405     for cleanup in temp_cleanups { revoke_clean(bcx, cleanup); }
406
407     ret {llbox: llbox, cboxptr_ty: cboxptr_ty, bcx: bcx};
408 }
409
410 // Given a context and a list of upvars, build a closure. This just
411 // collects the upvars and packages them up for store_environment.
412 fn build_closure(bcx0: @block_ctxt,
413                  cap_vars: [capture::capture_var],
414                  ck: ty::closure_kind)
415     -> closure_result {
416     // If we need to, package up the iterator body to call
417     let env_vals = [];
418     let bcx = bcx0;
419     let tcx = bcx_tcx(bcx);
420
421     // Package up the captured upvars
422     vec::iter(cap_vars) { |cap_var|
423         let lv = trans_local_var(bcx, cap_var.def);
424         let nid = ast_util::def_id_of_def(cap_var.def).node;
425         let ty = ty::node_id_to_monotype(tcx, nid);
426         alt cap_var.mode {
427           capture::cap_ref. {
428             assert ck == ty::closure_block;
429             ty = ty::mk_mut_ptr(tcx, ty);
430             env_vals += [env_ref(lv.val, ty, lv.kind)];
431           }
432           capture::cap_copy. {
433             env_vals += [env_copy(lv.val, ty, lv.kind)];
434           }
435           capture::cap_move. {
436             env_vals += [env_move(lv.val, ty, lv.kind)];
437           }
438           capture::cap_drop. {
439             bcx = drop_ty(bcx, lv.val, ty);
440           }
441         }
442     }
443     ret store_environment(bcx, copy bcx.fcx.lltyparams, env_vals, ck);
444 }
445
446 // Given an enclosing block context, a new function context, a closure type,
447 // and a list of upvars, generate code to load and populate the environment
448 // with the upvars and type descriptors.
449 fn load_environment(enclosing_cx: @block_ctxt,
450                     fcx: @fn_ctxt,
451                     cboxptr_ty: ty::t,
452                     cap_vars: [capture::capture_var],
453                     ck: ty::closure_kind) {
454     let bcx = new_raw_block_ctxt(fcx, fcx.llloadenv);
455     let ccx = bcx_ccx(bcx);
456
457     let sp = bcx.sp;
458     check (type_has_static_size(ccx, cboxptr_ty));
459     let llty = type_of(ccx, sp, cboxptr_ty);
460     let llclosure = PointerCast(bcx, fcx.llenv, llty);
461
462     // Populate the type parameters from the environment. We need to
463     // do this first because the tydescs are needed to index into
464     // the bindings if they are dynamically sized.
465     let lltydescs = GEPi(bcx, llclosure, [0, abi::cbox_elt_ty_params]);
466     let off = 0;
467     for tp in copy enclosing_cx.fcx.lltyparams {
468         let tydesc = Load(bcx, GEPi(bcx, lltydescs, [0, off]));
469         off += 1;
470         let dicts = option::map(tp.dicts, {|dicts|
471             let rslt = [];
472             for dict in dicts {
473                 let dict = Load(bcx, GEPi(bcx, lltydescs, [0, off]));
474                 rslt += [PointerCast(bcx, dict, T_ptr(T_dict()))];
475                 off += 1;
476             }
477             rslt
478         });
479         fcx.lltyparams += [{desc: tydesc, dicts: dicts}];
480     }
481
482     // Populate the upvars from the environment.
483     let path = [0, abi::cbox_elt_bindings];
484     let i = 0u;
485     vec::iter(cap_vars) { |cap_var|
486         alt cap_var.mode {
487           capture::cap_drop. { /* ignore */ }
488           _ {
489             check type_is_tup_like(bcx, cboxptr_ty);
490             let upvarptr = GEP_tup_like(
491                 bcx, cboxptr_ty, llclosure, path + [i as int]);
492             bcx = upvarptr.bcx;
493             let llupvarptr = upvarptr.val;
494             alt ck {
495               ty::closure_block. { llupvarptr = Load(bcx, llupvarptr); }
496               ty::closure_send. | ty::closure_shared. { }
497             }
498             let def_id = ast_util::def_id_of_def(cap_var.def);
499             fcx.llupvars.insert(def_id.node, llupvarptr);
500             i += 1u;
501           }
502         }
503     }
504 }
505
506 fn trans_expr_fn(bcx: @block_ctxt,
507                  proto: ast::proto,
508                  decl: ast::fn_decl,
509                  body: ast::blk,
510                  sp: span,
511                  id: ast::node_id,
512                  cap_clause: ast::capture_clause,
513                  dest: dest) -> @block_ctxt {
514     if dest == ignore { ret bcx; }
515     let ccx = bcx_ccx(bcx), bcx = bcx;
516     let fty = node_id_type(ccx, id);
517     let llfnty = type_of_fn_from_ty(ccx, sp, fty, []);
518     let sub_cx = extend_path(bcx.fcx.lcx, ccx.names.next("anon"));
519     let s = mangle_internal_name_by_path(ccx, sub_cx.path);
520     let llfn = decl_internal_cdecl_fn(ccx.llmod, s, llfnty);
521     register_fn(ccx, sp, sub_cx.path, "anon fn", [], id);
522
523     let trans_closure_env = lambda(ck: ty::closure_kind) -> ValueRef {
524         let cap_vars = capture::compute_capture_vars(
525             ccx.tcx, id, proto, cap_clause);
526         let {llbox, cboxptr_ty, bcx} = build_closure(bcx, cap_vars, ck);
527         trans_closure(sub_cx, sp, decl, body, llfn, no_self, [], id, {|fcx|
528             load_environment(bcx, fcx, cboxptr_ty, cap_vars, ck);
529         });
530         llbox
531     };
532
533     let closure = alt proto {
534       ast::proto_block. { trans_closure_env(ty::closure_block) }
535       ast::proto_shared(_) { trans_closure_env(ty::closure_shared) }
536       ast::proto_send. { trans_closure_env(ty::closure_send) }
537       ast::proto_bare. {
538         let closure = C_null(T_opaque_cbox_ptr(ccx));
539         trans_closure(sub_cx, sp, decl, body, llfn, no_self, [],
540                       id, {|_fcx|});
541         closure
542       }
543     };
544     fill_fn_pair(bcx, get_dest_addr(dest), llfn, closure);
545     ret bcx;
546 }
547
548 fn trans_bind(cx: @block_ctxt, f: @ast::expr, args: [option::t<@ast::expr>],
549               id: ast::node_id, dest: dest) -> @block_ctxt {
550     let f_res = trans_callee(cx, f);
551     ret trans_bind_1(cx, ty::expr_ty(bcx_tcx(cx), f), f_res, args,
552                      ty::node_id_to_type(bcx_tcx(cx), id), dest);
553 }
554
555 fn trans_bind_1(cx: @block_ctxt, outgoing_fty: ty::t,
556                 f_res: lval_maybe_callee,
557                 args: [option::t<@ast::expr>], pair_ty: ty::t,
558                 dest: dest) -> @block_ctxt {
559     let bound: [@ast::expr] = [];
560     for argopt: option::t<@ast::expr> in args {
561         alt argopt { none. { } some(e) { bound += [e]; } }
562     }
563     let bcx = f_res.bcx;
564     if dest == ignore {
565         for ex in bound { bcx = trans_expr(bcx, ex, ignore); }
566         ret bcx;
567     }
568
569     // Figure out which tydescs we need to pass, if any.
570     let (outgoing_fty_real, lltydescs, param_bounds) = alt f_res.generic {
571       none. { (outgoing_fty, [], @[]) }
572       some(ginfo) {
573         let tds = [], orig = 0u;
574         vec::iter2(ginfo.tydescs, *ginfo.param_bounds) {|td, bounds|
575             tds += [td];
576             for bound in *bounds {
577                 alt bound {
578                   ty::bound_iface(_) {
579                     let dict = trans_impl::get_dict(
580                         bcx, option::get(ginfo.origins)[orig]);
581                     tds += [PointerCast(bcx, dict.val, val_ty(td))];
582                     orig += 1u;
583                     bcx = dict.bcx;
584                   }
585                   _ {}
586                 }
587             }
588         }
589         lazily_emit_all_generic_info_tydesc_glues(cx, ginfo);
590         (ginfo.item_type, tds, ginfo.param_bounds)
591       }
592     };
593
594     if vec::len(bound) == 0u && vec::len(lltydescs) == 0u {
595         // Trivial 'binding': just return the closure
596         let lv = lval_maybe_callee_to_lval(f_res, pair_ty);
597         bcx = lv.bcx;
598         ret memmove_ty(bcx, get_dest_addr(dest), lv.val, pair_ty);
599     }
600     let closure = alt f_res.env {
601       null_env. { none }
602       _ { let (_, cl) = maybe_add_env(cx, f_res); some(cl) }
603     };
604
605     // FIXME: should follow from a precondition on trans_bind_1
606     let ccx = bcx_ccx(cx);
607     check (type_has_static_size(ccx, outgoing_fty));
608
609     // Arrange for the bound function to live in the first binding spot
610     // if the function is not statically known.
611     let (env_vals, target_res) = alt closure {
612       some(cl) {
613         // Cast the function we are binding to be the type that the
614         // closure will expect it to have. The type the closure knows
615         // about has the type parameters substituted with the real types.
616         let sp = cx.sp;
617         let llclosurety = T_ptr(type_of(ccx, sp, outgoing_fty));
618         let src_loc = PointerCast(bcx, cl, llclosurety);
619         ([env_copy(src_loc, pair_ty, owned)], none)
620       }
621       none. { ([], some(f_res.val)) }
622     };
623
624     // Actually construct the closure
625     let {llbox, cboxptr_ty, bcx} = store_environment(
626         bcx, vec::map(lltydescs, {|d| {desc: d, dicts: none}}),
627         env_vals + vec::map(bound, {|x| env_expr(x)}),
628         ty::closure_shared);
629
630     // Make thunk
631     let llthunk =
632         trans_bind_thunk(cx.fcx.lcx, cx.sp, pair_ty, outgoing_fty_real, args,
633                          cboxptr_ty, *param_bounds, target_res);
634
635     // Fill the function pair
636     fill_fn_pair(bcx, get_dest_addr(dest), llthunk.val, llbox);
637     ret bcx;
638 }
639
640 fn make_null_test(
641     in_bcx: @block_ctxt,
642     ptr: ValueRef,
643     blk: block(@block_ctxt) -> @block_ctxt)
644     -> @block_ctxt {
645     let not_null_bcx = new_sub_block_ctxt(in_bcx, "not null");
646     let next_bcx = new_sub_block_ctxt(in_bcx, "next");
647     let null_test = IsNull(in_bcx, ptr);
648     CondBr(in_bcx, null_test, next_bcx.llbb, not_null_bcx.llbb);
649     let not_null_bcx = blk(not_null_bcx);
650     Br(not_null_bcx, next_bcx.llbb);
651     ret next_bcx;
652 }
653
654 fn make_fn_glue(
655     cx: @block_ctxt,
656     v: ValueRef,
657     t: ty::t,
658     glue_fn: fn(@block_ctxt, v: ValueRef, t: ty::t) -> @block_ctxt)
659     -> @block_ctxt {
660     let bcx = cx;
661     let tcx = bcx_tcx(cx);
662
663     let fn_env = lambda(ck: ty::closure_kind) -> @block_ctxt {
664         let box_cell_v = GEPi(cx, v, [0, abi::fn_field_box]);
665         let box_ptr_v = Load(cx, box_cell_v);
666         make_null_test(cx, box_ptr_v) {|bcx|
667             let closure_ty = ty::mk_opaque_closure_ptr(tcx, ck);
668             glue_fn(bcx, box_cell_v, closure_ty)
669         }
670     };
671
672     ret alt ty::struct(tcx, t) {
673       ty::ty_native_fn(_, _) | ty::ty_fn({proto: ast::proto_bare., _}) { bcx }
674       ty::ty_fn({proto: ast::proto_block., _}) { bcx }
675       ty::ty_fn({proto: ast::proto_send., _}) {
676         fn_env(ty::closure_send)
677       }
678       ty::ty_fn({proto: ast::proto_shared(_), _}) {
679         fn_env(ty::closure_shared)
680       }
681       _ { fail "make_fn_glue invoked on non-function type" }
682     };
683 }
684
685 fn make_opaque_cbox_take_glue(
686     bcx: @block_ctxt,
687     ck: ty::closure_kind,
688     cboxptr: ValueRef)     // ptr to ptr to the opaque closure
689     -> @block_ctxt {
690     // Easy cases:
691     alt ck {
692       ty::closure_block. {
693         ret bcx;
694       }
695       ty::closure_shared. {
696         ret incr_refcnt_of_boxed(bcx, Load(bcx, cboxptr));
697       }
698       ty::closure_send. { /* hard case: */ }
699     }
700
701     // Hard case, a deep copy:
702     let ccx = bcx_ccx(bcx);
703     let llopaquecboxty = T_opaque_cbox_ptr(ccx);
704     let cbox_in = Load(bcx, cboxptr);
705     make_null_test(bcx, cbox_in) {|bcx|
706         // Load the size from the type descr found in the cbox
707         let cbox_in = PointerCast(bcx, cbox_in, llopaquecboxty);
708         let tydescptr = GEPi(bcx, cbox_in, [0, abi::cbox_elt_tydesc]);
709         let tydesc = Load(bcx, tydescptr);
710         let tydesc = PointerCast(bcx, tydesc, T_ptr(ccx.tydesc_type));
711         let sz = Load(bcx, GEPi(bcx, tydesc, [0, abi::tydesc_field_size]));
712
713         // Allocate memory, update original ptr, and copy existing data
714         let malloc = ccx.upcalls.shared_malloc;
715         let cbox_out = Call(bcx, malloc, [sz, tydesc]);
716         let cbox_out = PointerCast(bcx, cbox_out, llopaquecboxty);
717         let {bcx, val: _} = call_memmove(bcx, cbox_out, cbox_in, sz);
718         Store(bcx, cbox_out, cboxptr);
719
720         // Take the data in the tuple
721         let ti = none;
722         call_tydesc_glue_full(bcx, cbox_out, tydesc,
723                               abi::tydesc_field_take_glue, ti);
724         bcx
725     }
726 }
727
728 fn make_opaque_cbox_drop_glue(
729     bcx: @block_ctxt,
730     ck: ty::closure_kind,
731     cboxptr: ValueRef)     // ptr to the opaque closure
732     -> @block_ctxt {
733     alt ck {
734       ty::closure_block. { bcx }
735       ty::closure_shared. {
736         decr_refcnt_maybe_free(bcx, Load(bcx, cboxptr),
737                                ty::mk_opaque_closure_ptr(bcx_tcx(bcx), ck))
738       }
739       ty::closure_send. {
740         free_ty(bcx, Load(bcx, cboxptr),
741                 ty::mk_opaque_closure_ptr(bcx_tcx(bcx), ck))
742       }
743     }
744 }
745
746 fn make_opaque_cbox_free_glue(
747     bcx: @block_ctxt,
748     ck: ty::closure_kind,
749     cbox: ValueRef)     // ptr to the opaque closure
750     -> @block_ctxt {
751     alt ck {
752       ty::closure_block. { ret bcx; }
753       ty::closure_shared. | ty::closure_send. { /* hard cases: */ }
754     }
755
756     let ccx = bcx_ccx(bcx);
757     let tcx = bcx_tcx(bcx);
758     make_null_test(bcx, cbox) {|bcx|
759         // Load the type descr found in the cbox
760         let lltydescty = T_ptr(ccx.tydesc_type);
761         let cbox = PointerCast(bcx, cbox, T_opaque_cbox_ptr(ccx));
762         let tydescptr = GEPi(bcx, cbox, [0, abi::cbox_elt_tydesc]);
763         let tydesc = Load(bcx, tydescptr);
764         let tydesc = PointerCast(bcx, tydesc, lltydescty);
765
766         // Null out the type descr in the cbox.  This is subtle:
767         // we will be freeing the data in the cbox, and we may need the
768         // information in the type descr to guide the GEP_tup_like process
769         // etc if generic types are involved.  So we null it out at first
770         // then free it manually below.
771         Store(bcx, C_null(lltydescty), tydescptr);
772
773         // Drop the tuple data then free the descriptor
774         let ti = none;
775         call_tydesc_glue_full(bcx, cbox, tydesc,
776                               abi::tydesc_field_drop_glue, ti);
777
778         // Free the ty descr (if necc) and the box itself
779         alt ck {
780           ty::closure_block. { fail "Impossible."; }
781           ty::closure_shared. {
782             trans_free_if_not_gc(bcx, cbox)
783           }
784           ty::closure_send. {
785             let bcx = free_ty(bcx, tydesc, mk_tydesc_ty(tcx, ck));
786             trans_shared_free(bcx, cbox)
787           }
788         }
789     }
790 }
791
792 // pth is cx.path
793 fn trans_bind_thunk(cx: @local_ctxt,
794                     sp: span,
795                     incoming_fty: ty::t,
796                     outgoing_fty: ty::t,
797                     args: [option::t<@ast::expr>],
798                     cboxptr_ty: ty::t,
799                     param_bounds: [ty::param_bounds],
800                     target_fn: option::t<ValueRef>)
801     -> {val: ValueRef, ty: TypeRef} {
802     // If we supported constraints on record fields, we could make the
803     // constraints for this function:
804     /*
805     : returns_non_ty_var(ccx, outgoing_fty),
806       type_has_static_size(ccx, incoming_fty) ->
807     */
808     // but since we don't, we have to do the checks at the beginning.
809     let ccx = cx.ccx;
810     check type_has_static_size(ccx, incoming_fty);
811
812     // Here we're not necessarily constructing a thunk in the sense of
813     // "function with no arguments".  The result of compiling 'bind f(foo,
814     // bar, baz)' would be a thunk that, when called, applies f to those
815     // arguments and returns the result.  But we're stretching the meaning of
816     // the word "thunk" here to also mean the result of compiling, say, 'bind
817     // f(foo, _, baz)', or any other bind expression that binds f and leaves
818     // some (or all) of the arguments unbound.
819
820     // Here, 'incoming_fty' is the type of the entire bind expression, while
821     // 'outgoing_fty' is the type of the function that is having some of its
822     // arguments bound.  If f is a function that takes three arguments of type
823     // int and returns int, and we're translating, say, 'bind f(3, _, 5)',
824     // then outgoing_fty is the type of f, which is (int, int, int) -> int,
825     // and incoming_fty is the type of 'bind f(3, _, 5)', which is int -> int.
826
827     // Once translated, the entire bind expression will be the call f(foo,
828     // bar, baz) wrapped in a (so-called) thunk that takes 'bar' as its
829     // argument and that has bindings of 'foo' to 3 and 'baz' to 5 and a
830     // pointer to 'f' all saved in its environment.  So, our job is to
831     // construct and return that thunk.
832
833     // Give the thunk a name, type, and value.
834     let s: str = mangle_internal_name_by_path_and_seq(ccx, cx.path, "thunk");
835     let llthunk_ty: TypeRef = get_pair_fn_ty(type_of(ccx, sp, incoming_fty));
836     let llthunk: ValueRef = decl_internal_cdecl_fn(ccx.llmod, s, llthunk_ty);
837
838     // Create a new function context and block context for the thunk, and hold
839     // onto a pointer to the first block in the function for later use.
840     let fcx = new_fn_ctxt(cx, sp, llthunk);
841     let bcx = new_top_block_ctxt(fcx);
842     let lltop = bcx.llbb;
843     // Since we might need to construct derived tydescs that depend on
844     // our bound tydescs, we need to load tydescs out of the environment
845     // before derived tydescs are constructed. To do this, we load them
846     // in the load_env block.
847     let l_bcx = new_raw_block_ctxt(fcx, fcx.llloadenv);
848
849     // The 'llenv' that will arrive in the thunk we're creating is an
850     // environment that will contain the values of its arguments and a pointer
851     // to the original function.  So, let's create one of those:
852
853     // The llenv pointer needs to be the correct size.  That size is
854     // 'cboxptr_ty', which was determined by trans_bind.
855     check type_has_static_size(ccx, cboxptr_ty);
856     let llclosure_ptr_ty = type_of(ccx, sp, cboxptr_ty);
857     let llclosure = PointerCast(l_bcx, fcx.llenv, llclosure_ptr_ty);
858
859     // "target", in this context, means the function that's having some of its
860     // arguments bound and that will be called inside the thunk we're
861     // creating.  (In our running example, target is the function f.)  Pick
862     // out the pointer to the target function from the environment. The
863     // target function lives in the first binding spot.
864     let (lltargetfn, lltargetenv, starting_idx) = alt target_fn {
865       some(fptr) {
866         (fptr, llvm::LLVMGetUndef(T_opaque_cbox_ptr(ccx)), 0)
867       }
868       none. {
869         // Silly check
870         check type_is_tup_like(bcx, cboxptr_ty);
871         let {bcx: cx, val: pair} =
872             GEP_tup_like(bcx, cboxptr_ty, llclosure,
873                          [0, abi::cbox_elt_bindings, 0]);
874         let lltargetenv =
875             Load(cx, GEPi(cx, pair, [0, abi::fn_field_box]));
876         let lltargetfn = Load
877             (cx, GEPi(cx, pair, [0, abi::fn_field_code]));
878         bcx = cx;
879         (lltargetfn, lltargetenv, 1)
880       }
881     };
882
883     // And then, pick out the target function's own environment.  That's what
884     // we'll use as the environment the thunk gets.
885
886     // Get f's return type, which will also be the return type of the entire
887     // bind expression.
888     let outgoing_ret_ty = ty::ty_fn_ret(cx.ccx.tcx, outgoing_fty);
889
890     // Get the types of the arguments to f.
891     let outgoing_args = ty::ty_fn_args(cx.ccx.tcx, outgoing_fty);
892
893     // The 'llretptr' that will arrive in the thunk we're creating also needs
894     // to be the correct type.  Cast it to f's return type, if necessary.
895     let llretptr = fcx.llretptr;
896     let ccx = cx.ccx;
897     if ty::type_contains_params(ccx.tcx, outgoing_ret_ty) {
898         check non_ty_var(ccx, outgoing_ret_ty);
899         let llretty = type_of_inner(ccx, sp, outgoing_ret_ty);
900         llretptr = PointerCast(bcx, llretptr, T_ptr(llretty));
901     }
902
903     // Set up the three implicit arguments to the thunk.
904     let llargs: [ValueRef] = [llretptr, lltargetenv];
905
906     // Copy in the type parameters.
907     check type_is_tup_like(l_bcx, cboxptr_ty);
908     let {bcx: l_bcx, val: param_record} =
909         GEP_tup_like(l_bcx, cboxptr_ty, llclosure,
910                      [0, abi::cbox_elt_ty_params]);
911     let off = 0;
912     for param in param_bounds {
913         let dsc = Load(l_bcx, GEPi(l_bcx, param_record, [0, off])),
914             dicts = none;
915         llargs += [dsc];
916         off += 1;
917         for bound in *param {
918             alt bound {
919               ty::bound_iface(_) {
920                 let dict = Load(l_bcx, GEPi(l_bcx, param_record, [0, off]));
921                 dict = PointerCast(l_bcx, dict, T_ptr(T_dict()));
922                 llargs += [dict];
923                 off += 1;
924                 dicts = some(alt dicts {
925                   none. { [dict] }
926                   some(ds) { ds + [dict] }
927                 });
928               }
929               _ {}
930             }
931         }
932         fcx.lltyparams += [{desc: dsc, dicts: dicts}];
933     }
934
935     let a: uint = 2u; // retptr, env come first
936     let b: int = starting_idx;
937     let outgoing_arg_index: uint = 0u;
938     let llout_arg_tys: [TypeRef] =
939         type_of_explicit_args(cx.ccx, sp, outgoing_args);
940     for arg: option::t<@ast::expr> in args {
941         let out_arg = outgoing_args[outgoing_arg_index];
942         let llout_arg_ty = llout_arg_tys[outgoing_arg_index];
943         alt arg {
944           // Arg provided at binding time; thunk copies it from
945           // closure.
946           some(e) {
947             // Silly check
948             check type_is_tup_like(bcx, cboxptr_ty);
949             let bound_arg =
950                 GEP_tup_like(bcx, cboxptr_ty, llclosure,
951                              [0, abi::cbox_elt_bindings, b]);
952             bcx = bound_arg.bcx;
953             let val = bound_arg.val;
954             if out_arg.mode == ast::by_val { val = Load(bcx, val); }
955             if out_arg.mode == ast::by_copy {
956                 let {bcx: cx, val: alloc} = alloc_ty(bcx, out_arg.ty);
957                 bcx = memmove_ty(cx, alloc, val, out_arg.ty);
958                 bcx = take_ty(bcx, alloc, out_arg.ty);
959                 val = alloc;
960             }
961             // If the type is parameterized, then we need to cast the
962             // type we actually have to the parameterized out type.
963             if ty::type_contains_params(cx.ccx.tcx, out_arg.ty) {
964                 val = PointerCast(bcx, val, llout_arg_ty);
965             }
966             llargs += [val];
967             b += 1;
968           }
969
970           // Arg will be provided when the thunk is invoked.
971           none. {
972             let arg: ValueRef = llvm::LLVMGetParam(llthunk, a);
973             if ty::type_contains_params(cx.ccx.tcx, out_arg.ty) {
974                 arg = PointerCast(bcx, arg, llout_arg_ty);
975             }
976             llargs += [arg];
977             a += 1u;
978           }
979         }
980         outgoing_arg_index += 1u;
981     }
982
983     // Cast the outgoing function to the appropriate type.
984     // This is necessary because the type of the function that we have
985     // in the closure does not know how many type descriptors the function
986     // needs to take.
987     let ccx = bcx_ccx(bcx);
988
989     let lltargetty =
990         type_of_fn_from_ty(ccx, sp, outgoing_fty, param_bounds);
991     lltargetfn = PointerCast(bcx, lltargetfn, T_ptr(lltargetty));
992     Call(bcx, lltargetfn, llargs);
993     build_return(bcx);
994     finish_fn(fcx, lltop);
995     ret {val: llthunk, ty: llthunk_ty};
996 }