]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/closure.rs
aabe19deefccc6743a213dfd90dd6d387d3d284a
[rust.git] / src / librustc / middle / trans / closure.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 back::link::mangle_internal_name_by_path_and_seq;
14 use driver::session::FullDebugInfo;
15 use lib::llvm::ValueRef;
16 use middle::moves;
17 use middle::trans::base::*;
18 use middle::trans::build::*;
19 use middle::trans::common::*;
20 use middle::trans::datum::{Datum, DatumBlock, Expr, Lvalue, rvalue_scratch_datum};
21 use middle::trans::debuginfo;
22 use middle::trans::expr;
23 use middle::trans::type_of::*;
24 use middle::trans::type_::Type;
25 use middle::ty;
26 use util::ppaux::Repr;
27 use util::ppaux::ty_to_str;
28
29 use arena::TypedArena;
30 use syntax::ast;
31 use syntax::ast_util;
32
33 // ___Good to know (tm)__________________________________________________
34 //
35 // The layout of a closure environment in memory is
36 // roughly as follows:
37 //
38 // struct rust_opaque_box {         // see rust_internal.h
39 //   unsigned ref_count;            // only used for @fn()
40 //   type_desc *tydesc;             // describes closure_data struct
41 //   rust_opaque_box *prev;         // (used internally by memory alloc)
42 //   rust_opaque_box *next;         // (used internally by memory alloc)
43 //   struct closure_data {
44 //       type_desc *bound_tdescs[]; // bound descriptors
45 //       struct {
46 //         upvar1_t upvar1;
47 //         ...
48 //         upvarN_t upvarN;
49 //       } bound_data;
50 //    }
51 // };
52 //
53 // Note that the closure is itself a rust_opaque_box.  This is true
54 // even for ~fn and ||, because we wish to keep binary compatibility
55 // between all kinds of closures.  The allocation strategy for this
56 // closure depends on the closure type.  For a sendfn, the closure
57 // (and the referenced type descriptors) will be allocated in the
58 // exchange heap.  For a fn, the closure is allocated in the task heap
59 // and is reference counted.  For a block, the closure is allocated on
60 // the stack.
61 //
62 // ## Opaque closures and the embedded type descriptor ##
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 we only manipulate it
72 // by ptr.  The routine Type::at_box().ptr_to() returns an appropriate
73 // type for such an opaque closure; it allows access to the box fields,
74 // but not the closure_data itself.
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 // It is important that we be able to locate the closure data *without
84 // knowing the kind of data that is being bound*.  This can be tricky
85 // because the alignment requirements of the bound data affects the
86 // alignment requires of the closure_data struct as a whole.  However,
87 // right now this is a non-issue in any case, because the size of the
88 // rust_opaque_box header is always a mutiple of 16-bytes, which is
89 // the maximum alignment requirement we ever have to worry about.
90 //
91 // The only reason alignment matters is that, in order to learn what data
92 // is bound, we would normally first load the type descriptors: but their
93 // location is ultimately depend on their content!  There is, however, a
94 // workaround.  We can load the tydesc from the rust_opaque_box, which
95 // describes the closure_data struct and has self-contained derived type
96 // descriptors, and read the alignment from there.   It's just annoying to
97 // do.  Hopefully should this ever become an issue we'll have monomorphized
98 // and type descriptors will all be a bad dream.
99 //
100 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
101
102 pub enum EnvAction {
103     /// Copy the value from this llvm ValueRef into the environment.
104     EnvCopy,
105
106     /// Move the value from this llvm ValueRef into the environment.
107     EnvMove,
108
109     /// Access by reference (used for stack closures).
110     EnvRef
111 }
112
113 pub struct EnvValue {
114     action: EnvAction,
115     datum: Datum<Lvalue>
116 }
117
118 impl EnvAction {
119     pub fn to_str(&self) -> ~str {
120         match *self {
121             EnvCopy => ~"EnvCopy",
122             EnvMove => ~"EnvMove",
123             EnvRef => ~"EnvRef"
124         }
125     }
126 }
127
128 impl EnvValue {
129     pub fn to_str(&self, ccx: &CrateContext) -> ~str {
130         format!("{}({})", self.action.to_str(), self.datum.to_str(ccx))
131     }
132 }
133
134 // Given a closure ty, emits a corresponding tuple ty
135 pub fn mk_closure_tys(tcx: ty::ctxt,
136                       bound_values: &[EnvValue])
137                    -> ty::t {
138     // determine the types of the values in the env.  Note that this
139     // is the actual types that will be stored in the map, not the
140     // logical types as the user sees them, so by-ref upvars must be
141     // converted to ptrs.
142     let bound_tys = bound_values.map(|bv| {
143         match bv.action {
144             EnvCopy | EnvMove => bv.datum.ty,
145             EnvRef => ty::mk_mut_ptr(tcx, bv.datum.ty)
146         }
147     });
148     let cdata_ty = ty::mk_tup(tcx, bound_tys);
149     debug!("cdata_ty={}", ty_to_str(tcx, cdata_ty));
150     return cdata_ty;
151 }
152
153 fn tuplify_box_ty(tcx: ty::ctxt, t: ty::t) -> ty::t {
154     let ptr = ty::mk_imm_ptr(tcx, ty::mk_i8());
155     ty::mk_tup(tcx, ~[ty::mk_uint(), ty::mk_nil_ptr(tcx), ptr, ptr, t])
156 }
157
158 fn allocate_cbox<'a>(bcx: &'a Block<'a>,
159                      sigil: ast::Sigil,
160                      cdata_ty: ty::t)
161                      -> Result<'a> {
162     let _icx = push_ctxt("closure::allocate_cbox");
163     let ccx = bcx.ccx();
164     let tcx = ccx.tcx;
165
166     // Allocate and initialize the box:
167     match sigil {
168         ast::ManagedSigil => {
169             tcx.sess.bug("trying to trans allocation of @fn")
170         }
171         ast::OwnedSigil => {
172             malloc_raw(bcx, cdata_ty, heap_exchange_closure)
173         }
174         ast::BorrowedSigil => {
175             let cbox_ty = tuplify_box_ty(tcx, cdata_ty);
176             let llbox = alloc_ty(bcx, cbox_ty, "__closure");
177             rslt(bcx, llbox)
178         }
179     }
180 }
181
182 pub struct ClosureResult<'a> {
183     llbox: ValueRef,    // llvalue of ptr to closure
184     cdata_ty: ty::t,    // type of the closure data
185     bcx: &'a Block<'a>  // final bcx
186 }
187
188 // Given a block context and a list of tydescs and values to bind
189 // construct a closure out of them. If copying is true, it is a
190 // heap allocated closure that copies the upvars into environment.
191 // Otherwise, it is stack allocated and copies pointers to the upvars.
192 pub fn store_environment<'a>(
193                          bcx: &'a Block<'a>,
194                          bound_values: ~[EnvValue],
195                          sigil: ast::Sigil)
196                          -> ClosureResult<'a> {
197     let _icx = push_ctxt("closure::store_environment");
198     let ccx = bcx.ccx();
199     let tcx = ccx.tcx;
200
201     // compute the type of the closure
202     let cdata_ty = mk_closure_tys(tcx, bound_values);
203
204     // cbox_ty has the form of a tuple: (a, b, c) we want a ptr to a
205     // tuple.  This could be a ptr in uniq or a box or on stack,
206     // whatever.
207     let cbox_ty = tuplify_box_ty(tcx, cdata_ty);
208     let cboxptr_ty = ty::mk_ptr(tcx, ty::mt {ty:cbox_ty, mutbl:ast::MutImmutable});
209     let llboxptr_ty = type_of(ccx, cboxptr_ty);
210
211     // If there are no bound values, no point in allocating anything.
212     if bound_values.is_empty() {
213         return ClosureResult {llbox: C_null(llboxptr_ty),
214                               cdata_ty: cdata_ty,
215                               bcx: bcx};
216     }
217
218     // allocate closure in the heap
219     let Result {bcx: bcx, val: llbox} = allocate_cbox(bcx, sigil, cdata_ty);
220
221     let llbox = PointerCast(bcx, llbox, llboxptr_ty);
222     debug!("tuplify_box_ty = {}", ty_to_str(tcx, cbox_ty));
223
224     // Copy expr values into boxed bindings.
225     let mut bcx = bcx;
226     for (i, bv) in bound_values.move_iter().enumerate() {
227         debug!("Copy {} into closure", bv.to_str(ccx));
228
229         if ccx.sess.asm_comments() {
230             add_comment(bcx, format!("Copy {} into closure",
231                                   bv.to_str(ccx)));
232         }
233
234         let bound_data = GEPi(bcx, llbox, [0u, abi::box_field_body, i]);
235
236         match bv.action {
237             EnvCopy | EnvMove => {
238                 bcx = bv.datum.store_to(bcx, bound_data);
239             }
240             EnvRef => {
241                 Store(bcx, bv.datum.to_llref(), bound_data);
242             }
243         }
244     }
245
246     ClosureResult { llbox: llbox, cdata_ty: cdata_ty, bcx: bcx }
247 }
248
249 // Given a context and a list of upvars, build a closure. This just
250 // collects the upvars and packages them up for store_environment.
251 fn build_closure<'a>(bcx0: &'a Block<'a>,
252                      cap_vars: &[moves::CaptureVar],
253                      sigil: ast::Sigil)
254                      -> ClosureResult<'a> {
255     let _icx = push_ctxt("closure::build_closure");
256
257     // If we need to, package up the iterator body to call
258     let bcx = bcx0;
259
260     // Package up the captured upvars
261     let mut env_vals = ~[];
262     for cap_var in cap_vars.iter() {
263         debug!("Building closure: captured variable {:?}", *cap_var);
264         let datum = expr::trans_local_var(bcx, cap_var.def);
265         match cap_var.mode {
266             moves::CapRef => {
267                 assert_eq!(sigil, ast::BorrowedSigil);
268                 env_vals.push(EnvValue {action: EnvRef,
269                                         datum: datum});
270             }
271             moves::CapCopy => {
272                 env_vals.push(EnvValue {action: EnvCopy,
273                                         datum: datum});
274             }
275             moves::CapMove => {
276                 env_vals.push(EnvValue {action: EnvMove,
277                                         datum: datum});
278             }
279         }
280     }
281
282     return store_environment(bcx, env_vals, sigil);
283 }
284
285 // Given an enclosing block context, a new function context, a closure type,
286 // and a list of upvars, generate code to load and populate the environment
287 // with the upvars and type descriptors.
288 fn load_environment<'a>(bcx: &'a Block<'a>, cdata_ty: ty::t,
289                         cap_vars: &[moves::CaptureVar],
290                         sigil: ast::Sigil) -> &'a Block<'a> {
291     let _icx = push_ctxt("closure::load_environment");
292
293     // Don't bother to create the block if there's nothing to load
294     if cap_vars.len() == 0 {
295         return bcx;
296     }
297
298     // Load a pointer to the closure data, skipping over the box header:
299     let llcdata = at_box_body(bcx, cdata_ty, bcx.fcx.llenv.unwrap());
300
301     // Store the pointer to closure data in an alloca for debug info because that's what the
302     // llvm.dbg.declare intrinsic expects
303     let env_pointer_alloca = if bcx.ccx().sess.opts.debuginfo == FullDebugInfo {
304         let alloc = alloc_ty(bcx, ty::mk_mut_ptr(bcx.tcx(), cdata_ty), "__debuginfo_env_ptr");
305         Store(bcx, llcdata, alloc);
306         Some(alloc)
307     } else {
308         None
309     };
310
311     // Populate the upvars from the environment
312     let mut i = 0u;
313     for cap_var in cap_vars.iter() {
314         let mut upvarptr = GEPi(bcx, llcdata, [0u, i]);
315         match sigil {
316             ast::BorrowedSigil => { upvarptr = Load(bcx, upvarptr); }
317             ast::ManagedSigil | ast::OwnedSigil => {}
318         }
319         let def_id = ast_util::def_id_of_def(cap_var.def);
320
321         {
322             let mut llupvars = bcx.fcx.llupvars.borrow_mut();
323             llupvars.get().insert(def_id.node, upvarptr);
324         }
325
326         for &env_pointer_alloca in env_pointer_alloca.iter() {
327             debuginfo::create_captured_var_metadata(
328                 bcx,
329                 def_id.node,
330                 cdata_ty,
331                 env_pointer_alloca,
332                 i,
333                 sigil,
334                 cap_var.span);
335         }
336
337         i += 1u;
338     }
339
340     bcx
341 }
342
343 fn fill_fn_pair(bcx: &Block, pair: ValueRef, llfn: ValueRef, llenvptr: ValueRef) {
344     Store(bcx, llfn, GEPi(bcx, pair, [0u, abi::fn_field_code]));
345     let llenvptr = PointerCast(bcx, llenvptr, Type::i8p());
346     Store(bcx, llenvptr, GEPi(bcx, pair, [0u, abi::fn_field_box]));
347 }
348
349 pub fn trans_expr_fn<'a>(
350                      bcx: &'a Block<'a>,
351                      sigil: ast::Sigil,
352                      decl: &ast::FnDecl,
353                      body: &ast::Block,
354                      id: ast::NodeId,
355                      dest: expr::Dest)
356                      -> &'a Block<'a> {
357     /*!
358      *
359      * Translates the body of a closure expression.
360      *
361      * - `sigil`
362      * - `decl`
363      * - `body`
364      * - `id`: The id of the closure expression.
365      * - `cap_clause`: information about captured variables, if any.
366      * - `dest`: where to write the closure value, which must be a
367          (fn ptr, env) pair
368      */
369
370     let _icx = push_ctxt("closure::trans_expr_fn");
371
372     let dest_addr = match dest {
373         expr::SaveIn(p) => p,
374         expr::Ignore => {
375             return bcx; // closure construction is non-side-effecting
376         }
377     };
378
379     let ccx = bcx.ccx();
380     let fty = node_id_type(bcx, id);
381     let f = match ty::get(fty).sty {
382         ty::ty_closure(ref f) => f,
383         _ => fail!("expected closure")
384     };
385
386     let tcx = bcx.tcx();
387     let s = tcx.map.with_path(id, |path| {
388         mangle_internal_name_by_path_and_seq(path, "closure")
389     });
390     let llfn = decl_internal_rust_fn(ccx, true, f.sig.inputs, f.sig.output, s);
391
392     // set an inline hint for all closures
393     set_inline_hint(llfn);
394
395     let cap_vars = {
396         let capture_map = ccx.maps.capture_map.borrow();
397         capture_map.get().get_copy(&id)
398     };
399     let ClosureResult {llbox, cdata_ty, bcx} = build_closure(bcx, *cap_vars.borrow(), sigil);
400     trans_closure(ccx, decl, body, llfn,
401                   bcx.fcx.param_substs, id,
402                   [], ty::ty_fn_ret(fty),
403                   |bcx| load_environment(bcx, cdata_ty, *cap_vars.borrow(), sigil));
404     fill_fn_pair(bcx, dest_addr, llfn, llbox);
405
406     bcx
407 }
408
409 pub fn get_wrapper_for_bare_fn(ccx: @CrateContext,
410                                closure_ty: ty::t,
411                                def: ast::Def,
412                                fn_ptr: ValueRef,
413                                is_local: bool) -> ValueRef {
414
415     let def_id = match def {
416         ast::DefFn(did, _) | ast::DefStaticMethod(did, _, _) |
417         ast::DefVariant(_, did, _) | ast::DefStruct(did) => did,
418         _ => {
419             ccx.sess.bug(format!("get_wrapper_for_bare_fn: \
420                                   expected a statically resolved fn, got {:?}",
421                                   def));
422         }
423     };
424
425     {
426         let cache = ccx.closure_bare_wrapper_cache.borrow();
427         match cache.get().find(&fn_ptr) {
428             Some(&llval) => return llval,
429             None => {}
430         }
431     }
432
433     let tcx = ccx.tcx;
434
435     debug!("get_wrapper_for_bare_fn(closure_ty={})", closure_ty.repr(tcx));
436
437     let f = match ty::get(closure_ty).sty {
438         ty::ty_closure(ref f) => f,
439         _ => {
440             ccx.sess.bug(format!("get_wrapper_for_bare_fn: \
441                                   expected a closure ty, got {}",
442                                   closure_ty.repr(tcx)));
443         }
444     };
445
446     let name = ty::with_path(tcx, def_id, |path| {
447         mangle_internal_name_by_path_and_seq(path, "as_closure")
448     });
449     let llfn = if is_local {
450         decl_internal_rust_fn(ccx, true, f.sig.inputs, f.sig.output, name)
451     } else {
452         decl_rust_fn(ccx, true, f.sig.inputs, f.sig.output, name)
453     };
454
455     {
456         let mut cache = ccx.closure_bare_wrapper_cache.borrow_mut();
457         cache.get().insert(fn_ptr, llfn);
458     }
459
460     // This is only used by statics inlined from a different crate.
461     if !is_local {
462         // Don't regenerate the wrapper, just reuse the original one.
463         return llfn;
464     }
465
466     let _icx = push_ctxt("closure::get_wrapper_for_bare_fn");
467
468     let arena = TypedArena::new();
469     let fcx = new_fn_ctxt(ccx, llfn, -1, true, f.sig.output, None, None, &arena);
470     init_function(&fcx, true, f.sig.output, None);
471     let bcx = fcx.entry_bcx.get().unwrap();
472
473     let args = create_datums_for_fn_args(&fcx, ty::ty_fn_args(closure_ty));
474     let mut llargs = ~[];
475     match fcx.llretptr.get() {
476         Some(llretptr) => {
477             llargs.push(llretptr);
478         }
479         None => {}
480     }
481     llargs.extend(&mut args.iter().map(|arg| arg.val));
482
483     let retval = Call(bcx, fn_ptr, llargs, []);
484     if type_is_zero_size(ccx, f.sig.output) || fcx.llretptr.get().is_some() {
485         RetVoid(bcx);
486     } else {
487         Ret(bcx, retval);
488     }
489
490     // HACK(eddyb) finish_fn cannot be used here, we returned directly.
491     debuginfo::clear_source_location(&fcx);
492     fcx.cleanup();
493
494     llfn
495 }
496
497 pub fn make_closure_from_bare_fn<'a>(bcx: &'a Block<'a>,
498                                      closure_ty: ty::t,
499                                      def: ast::Def,
500                                      fn_ptr: ValueRef)
501                                      -> DatumBlock<'a, Expr>  {
502     let scratch = rvalue_scratch_datum(bcx, closure_ty, "__adjust");
503     let wrapper = get_wrapper_for_bare_fn(bcx.ccx(), closure_ty, def, fn_ptr, true);
504     fill_fn_pair(bcx, scratch.val, wrapper, C_null(Type::i8p()));
505
506     DatumBlock(bcx, scratch.to_expr_datum())
507 }