]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/closure.rs
Merge pull request #20510 from tshepang/patch-6
[rust.git] / src / librustc_trans / trans / closure.rs
1 // Copyright 2012-2014 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 pub use self::ClosureKind::*;
12
13 use back::abi;
14 use back::link::mangle_internal_name_by_path_and_seq;
15 use llvm::ValueRef;
16 use middle::mem_categorization::Typer;
17 use trans::adt;
18 use trans::base::*;
19 use trans::build::*;
20 use trans::cleanup::{CleanupMethods, ScopeId};
21 use trans::common::*;
22 use trans::datum::{Datum, DatumBlock, Expr, Lvalue, rvalue_scratch_datum};
23 use trans::datum::{Rvalue, ByValue};
24 use trans::debuginfo;
25 use trans::expr;
26 use trans::monomorphize::{self, MonoId};
27 use trans::type_of::*;
28 use trans::type_::Type;
29 use middle::ty::{self, Ty, UnboxedClosureTyper};
30 use middle::subst::{Substs};
31 use session::config::FullDebugInfo;
32 use util::ppaux::Repr;
33 use util::ppaux::ty_to_string;
34
35 use arena::TypedArena;
36 use syntax::ast;
37 use syntax::ast_util;
38
39 // ___Good to know (tm)__________________________________________________
40 //
41 // The layout of a closure environment in memory is
42 // roughly as follows:
43 //
44 // struct rust_opaque_box {         // see rust_internal.h
45 //   unsigned ref_count;            // obsolete (part of @T's header)
46 //   fn(void*) *drop_glue;          // destructor (for proc)
47 //   rust_opaque_box *prev;         // obsolete (part of @T's header)
48 //   rust_opaque_box *next;         // obsolete (part of @T's header)
49 //   struct closure_data {
50 //       upvar1_t upvar1;
51 //       ...
52 //       upvarN_t upvarN;
53 //    }
54 // };
55 //
56 // Note that the closure is itself a rust_opaque_box.  This is true
57 // even for ~fn and ||, because we wish to keep binary compatibility
58 // between all kinds of closures.  The allocation strategy for this
59 // closure depends on the closure type.  For a sendfn, the closure
60 // (and the referenced type descriptors) will be allocated in the
61 // exchange heap.  For a fn, the closure is allocated in the task heap
62 // and is reference counted.  For a block, the closure is allocated on
63 // the stack.
64 //
65 // ## Opaque closures and the embedded type descriptor ##
66 //
67 // One interesting part of closures is that they encapsulate the data
68 // that they close over.  So when I have a ptr to a closure, I do not
69 // know how many type descriptors it contains nor what upvars are
70 // captured within.  That means I do not know precisely how big it is
71 // nor where its fields are located.  This is called an "opaque
72 // closure".
73 //
74 // Typically an opaque closure suffices because we only manipulate it
75 // by ptr.  The routine Type::at_box().ptr_to() returns an appropriate
76 // type for such an opaque closure; it allows access to the box fields,
77 // but not the closure_data itself.
78 //
79 // But sometimes, such as when cloning or freeing a closure, we need
80 // to know the full information.  That is where the type descriptor
81 // that defines the closure comes in handy.  We can use its take and
82 // drop glue functions to allocate/free data as needed.
83 //
84 // ## Subtleties concerning alignment ##
85 //
86 // It is important that we be able to locate the closure data *without
87 // knowing the kind of data that is being bound*.  This can be tricky
88 // because the alignment requirements of the bound data affects the
89 // alignment requires of the closure_data struct as a whole.  However,
90 // right now this is a non-issue in any case, because the size of the
91 // rust_opaque_box header is always a multiple of 16-bytes, which is
92 // the maximum alignment requirement we ever have to worry about.
93 //
94 // The only reason alignment matters is that, in order to learn what data
95 // is bound, we would normally first load the type descriptors: but their
96 // location is ultimately depend on their content!  There is, however, a
97 // workaround.  We can load the tydesc from the rust_opaque_box, which
98 // describes the closure_data struct and has self-contained derived type
99 // descriptors, and read the alignment from there.   It's just annoying to
100 // do.  Hopefully should this ever become an issue we'll have monomorphized
101 // and type descriptors will all be a bad dream.
102 //
103 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
104
105 #[derive(Copy)]
106 pub struct EnvValue<'tcx> {
107     action: ast::CaptureClause,
108     datum: Datum<'tcx, Lvalue>
109 }
110
111 impl<'tcx> EnvValue<'tcx> {
112     pub fn to_string<'a>(&self, ccx: &CrateContext<'a, 'tcx>) -> String {
113         format!("{}({})", self.action, self.datum.to_string(ccx))
114     }
115 }
116
117 // Given a closure ty, emits a corresponding tuple ty
118 pub fn mk_closure_tys<'tcx>(tcx: &ty::ctxt<'tcx>,
119                             bound_values: &[EnvValue<'tcx>])
120                             -> Ty<'tcx> {
121     // determine the types of the values in the env.  Note that this
122     // is the actual types that will be stored in the map, not the
123     // logical types as the user sees them, so by-ref upvars must be
124     // converted to ptrs.
125     let bound_tys = bound_values.iter().map(|bv| {
126         match bv.action {
127             ast::CaptureByValue => bv.datum.ty,
128             ast::CaptureByRef => ty::mk_mut_ptr(tcx, bv.datum.ty)
129         }
130     }).collect();
131     let cdata_ty = ty::mk_tup(tcx, bound_tys);
132     debug!("cdata_ty={}", ty_to_string(tcx, cdata_ty));
133     return cdata_ty;
134 }
135
136 fn tuplify_box_ty<'tcx>(tcx: &ty::ctxt<'tcx>, t: Ty<'tcx>) -> Ty<'tcx> {
137     let ptr = ty::mk_imm_ptr(tcx, tcx.types.i8);
138     ty::mk_tup(tcx, vec!(tcx.types.uint, ty::mk_nil_ptr(tcx), ptr, ptr, t))
139 }
140
141 pub struct ClosureResult<'blk, 'tcx: 'blk> {
142     llbox: ValueRef,        // llvalue of ptr to closure
143     cdata_ty: Ty<'tcx>,     // type of the closure data
144     bcx: Block<'blk, 'tcx>  // final bcx
145 }
146
147 // Given a block context and a list of tydescs and values to bind
148 // construct a closure out of them. If copying is true, it is a
149 // heap allocated closure that copies the upvars into environment.
150 // Otherwise, it is stack allocated and copies pointers to the upvars.
151 pub fn store_environment<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
152                                      bound_values: Vec<EnvValue<'tcx>>)
153                                      -> ClosureResult<'blk, 'tcx> {
154     let _icx = push_ctxt("closure::store_environment");
155     let ccx = bcx.ccx();
156     let tcx = ccx.tcx();
157
158     // compute the type of the closure
159     let cdata_ty = mk_closure_tys(tcx, bound_values[]);
160
161     // cbox_ty has the form of a tuple: (a, b, c) we want a ptr to a
162     // tuple.  This could be a ptr in uniq or a box or on stack,
163     // whatever.
164     let cbox_ty = tuplify_box_ty(tcx, cdata_ty);
165     let cboxptr_ty = ty::mk_ptr(tcx, ty::mt {ty:cbox_ty, mutbl:ast::MutImmutable});
166     let llboxptr_ty = type_of(ccx, cboxptr_ty);
167
168     // If there are no bound values, no point in allocating anything.
169     if bound_values.is_empty() {
170         return ClosureResult {llbox: C_null(llboxptr_ty),
171                               cdata_ty: cdata_ty,
172                               bcx: bcx};
173     }
174
175     // allocate closure in the heap
176     let llbox = alloc_ty(bcx, cbox_ty, "__closure");
177
178     let llbox = PointerCast(bcx, llbox, llboxptr_ty);
179     debug!("tuplify_box_ty = {}", ty_to_string(tcx, cbox_ty));
180
181     // Copy expr values into boxed bindings.
182     let mut bcx = bcx;
183     for (i, bv) in bound_values.into_iter().enumerate() {
184         debug!("Copy {} into closure", bv.to_string(ccx));
185
186         if ccx.sess().asm_comments() {
187             add_comment(bcx, format!("Copy {} into closure",
188                                      bv.to_string(ccx))[]);
189         }
190
191         let bound_data = GEPi(bcx, llbox, &[0u, abi::BOX_FIELD_BODY, i]);
192
193         match bv.action {
194             ast::CaptureByValue => {
195                 bcx = bv.datum.store_to(bcx, bound_data);
196             }
197             ast::CaptureByRef => {
198                 Store(bcx, bv.datum.to_llref(), bound_data);
199             }
200         }
201     }
202
203     ClosureResult { llbox: llbox, cdata_ty: cdata_ty, bcx: bcx }
204 }
205
206 // Given a context and a list of upvars, build a closure. This just
207 // collects the upvars and packages them up for store_environment.
208 fn build_closure<'blk, 'tcx>(bcx0: Block<'blk, 'tcx>,
209                              freevar_mode: ast::CaptureClause,
210                              freevars: &Vec<ty::Freevar>)
211                              -> ClosureResult<'blk, 'tcx> {
212     let _icx = push_ctxt("closure::build_closure");
213
214     // If we need to, package up the iterator body to call
215     let bcx = bcx0;
216
217     // Package up the captured upvars
218     let mut env_vals = Vec::new();
219     for freevar in freevars.iter() {
220         let datum = expr::trans_local_var(bcx, freevar.def);
221         env_vals.push(EnvValue {action: freevar_mode, datum: datum});
222     }
223
224     store_environment(bcx, env_vals)
225 }
226
227 // Given an enclosing block context, a new function context, a closure type,
228 // and a list of upvars, generate code to load and populate the environment
229 // with the upvars and type descriptors.
230 fn load_environment<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
231                                 cdata_ty: Ty<'tcx>,
232                                 freevars: &[ty::Freevar],
233                                 store: ty::TraitStore)
234                                 -> Block<'blk, 'tcx> {
235     let _icx = push_ctxt("closure::load_environment");
236
237     // Load a pointer to the closure data, skipping over the box header:
238     let llcdata = at_box_body(bcx, cdata_ty, bcx.fcx.llenv.unwrap());
239
240     // Store the pointer to closure data in an alloca for debug info because that's what the
241     // llvm.dbg.declare intrinsic expects
242     let env_pointer_alloca = if bcx.sess().opts.debuginfo == FullDebugInfo {
243         let alloc = alloc_ty(bcx, ty::mk_mut_ptr(bcx.tcx(), cdata_ty), "__debuginfo_env_ptr");
244         Store(bcx, llcdata, alloc);
245         Some(alloc)
246     } else {
247         None
248     };
249
250     // Populate the upvars from the environment
251     let mut i = 0u;
252     for freevar in freevars.iter() {
253         let mut upvarptr = GEPi(bcx, llcdata, &[0u, i]);
254         let captured_by_ref = match store {
255             ty::RegionTraitStore(..) => {
256                 upvarptr = Load(bcx, upvarptr);
257                 true
258             }
259             ty::UniqTraitStore => false
260         };
261         let def_id = freevar.def.def_id();
262
263         bcx.fcx.llupvars.borrow_mut().insert(def_id.node, upvarptr);
264         if let Some(env_pointer_alloca) = env_pointer_alloca {
265             debuginfo::create_captured_var_metadata(
266                 bcx,
267                 def_id.node,
268                 env_pointer_alloca,
269                 i,
270                 captured_by_ref,
271                 freevar.span);
272         }
273
274         i += 1u;
275     }
276
277     bcx
278 }
279
280 fn load_unboxed_closure_environment<'blk, 'tcx>(
281                                     bcx: Block<'blk, 'tcx>,
282                                     arg_scope_id: ScopeId,
283                                     freevar_mode: ast::CaptureClause,
284                                     freevars: &[ty::Freevar])
285                                     -> Block<'blk, 'tcx> {
286     let _icx = push_ctxt("closure::load_environment");
287
288     // Special case for small by-value selfs.
289     let closure_id = ast_util::local_def(bcx.fcx.id);
290     let self_type = self_type_for_unboxed_closure(bcx.ccx(), closure_id,
291                                                   node_id_type(bcx, closure_id.node));
292     let kind = kind_for_unboxed_closure(bcx.ccx(), closure_id);
293     let llenv = if kind == ty::FnOnceUnboxedClosureKind &&
294             !arg_is_indirect(bcx.ccx(), self_type) {
295         let datum = rvalue_scratch_datum(bcx,
296                                          self_type,
297                                          "unboxed_closure_env");
298         store_ty(bcx, bcx.fcx.llenv.unwrap(), datum.val, self_type);
299         datum.val
300     } else {
301         bcx.fcx.llenv.unwrap()
302     };
303
304     // Store the pointer to closure data in an alloca for debug info because that's what the
305     // llvm.dbg.declare intrinsic expects
306     let env_pointer_alloca = if bcx.sess().opts.debuginfo == FullDebugInfo {
307         let alloc = alloca(bcx, val_ty(llenv), "__debuginfo_env_ptr");
308         Store(bcx, llenv, alloc);
309         Some(alloc)
310     } else {
311         None
312     };
313
314     for (i, freevar) in freevars.iter().enumerate() {
315         let mut upvar_ptr = GEPi(bcx, llenv, &[0, i]);
316         let captured_by_ref = match freevar_mode {
317             ast::CaptureByRef => {
318                 upvar_ptr = Load(bcx, upvar_ptr);
319                 true
320             }
321             ast::CaptureByValue => false
322         };
323         let def_id = freevar.def.def_id();
324         bcx.fcx.llupvars.borrow_mut().insert(def_id.node, upvar_ptr);
325
326         if kind == ty::FnOnceUnboxedClosureKind && freevar_mode == ast::CaptureByValue {
327             bcx.fcx.schedule_drop_mem(arg_scope_id,
328                                       upvar_ptr,
329                                       node_id_type(bcx, def_id.node))
330         }
331
332         if let Some(env_pointer_alloca) = env_pointer_alloca {
333             debuginfo::create_captured_var_metadata(
334                 bcx,
335                 def_id.node,
336                 env_pointer_alloca,
337                 i,
338                 captured_by_ref,
339                 freevar.span);
340         }
341     }
342
343     bcx
344 }
345
346 fn fill_fn_pair(bcx: Block, pair: ValueRef, llfn: ValueRef, llenvptr: ValueRef) {
347     Store(bcx, llfn, GEPi(bcx, pair, &[0u, abi::FAT_PTR_ADDR]));
348     let llenvptr = PointerCast(bcx, llenvptr, Type::i8p(bcx.ccx()));
349     Store(bcx, llenvptr, GEPi(bcx, pair, &[0u, abi::FAT_PTR_EXTRA]));
350 }
351
352 #[derive(PartialEq)]
353 pub enum ClosureKind<'tcx> {
354     NotClosure,
355     // See load_environment.
356     BoxedClosure(Ty<'tcx>, ty::TraitStore),
357     // See load_unboxed_closure_environment.
358     UnboxedClosure(ast::CaptureClause)
359 }
360
361 pub struct ClosureEnv<'a, 'tcx> {
362     freevars: &'a [ty::Freevar],
363     pub kind: ClosureKind<'tcx>
364 }
365
366 impl<'a, 'tcx> ClosureEnv<'a, 'tcx> {
367     pub fn new(freevars: &'a [ty::Freevar], kind: ClosureKind<'tcx>)
368                -> ClosureEnv<'a, 'tcx> {
369         ClosureEnv {
370             freevars: freevars,
371             kind: kind
372         }
373     }
374
375     pub fn load<'blk>(self, bcx: Block<'blk, 'tcx>, arg_scope: ScopeId)
376                       -> Block<'blk, 'tcx> {
377         // Don't bother to create the block if there's nothing to load
378         if self.freevars.is_empty() {
379             return bcx;
380         }
381
382         match self.kind {
383             NotClosure => bcx,
384             BoxedClosure(cdata_ty, store) => {
385                 load_environment(bcx, cdata_ty, self.freevars, store)
386             }
387             UnboxedClosure(freevar_mode) => {
388                 load_unboxed_closure_environment(bcx, arg_scope, freevar_mode, self.freevars)
389             }
390         }
391     }
392 }
393
394 /// Translates the body of a closure expression.
395 ///
396 /// - `store`
397 /// - `decl`
398 /// - `body`
399 /// - `id`: The id of the closure expression.
400 /// - `cap_clause`: information about captured variables, if any.
401 /// - `dest`: where to write the closure value, which must be a
402 ///   (fn ptr, env) pair
403 pub fn trans_expr_fn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
404                                  store: ty::TraitStore,
405                                  decl: &ast::FnDecl,
406                                  body: &ast::Block,
407                                  id: ast::NodeId,
408                                  dest: expr::Dest)
409                                  -> Block<'blk, 'tcx> {
410     let _icx = push_ctxt("closure::trans_expr_fn");
411
412     let dest_addr = match dest {
413         expr::SaveIn(p) => p,
414         expr::Ignore => {
415             return bcx; // closure construction is non-side-effecting
416         }
417     };
418
419     let ccx = bcx.ccx();
420     let tcx = bcx.tcx();
421     let fty = node_id_type(bcx, id);
422     let s = tcx.map.with_path(id, |path| {
423         mangle_internal_name_by_path_and_seq(path, "closure")
424     });
425     let llfn = decl_internal_rust_fn(ccx, fty, s[]);
426
427     // set an inline hint for all closures
428     set_inline_hint(llfn);
429
430     let freevar_mode = tcx.capture_mode(id);
431     let freevars: Vec<ty::Freevar> =
432         ty::with_freevars(tcx, id, |fv| fv.iter().map(|&fv| fv).collect());
433
434     let ClosureResult {
435         llbox,
436         cdata_ty,
437         bcx
438     } = build_closure(bcx, freevar_mode, &freevars);
439
440     trans_closure(ccx,
441                   decl,
442                   body,
443                   llfn,
444                   bcx.fcx.param_substs,
445                   id,
446                   &[],
447                   ty::ty_fn_ret(fty),
448                   ty::ty_fn_abi(fty),
449                   ClosureEnv::new(freevars[],
450                                   BoxedClosure(cdata_ty, store)));
451     fill_fn_pair(bcx, dest_addr, llfn, llbox);
452     bcx
453 }
454
455 /// Returns the LLVM function declaration for an unboxed closure, creating it
456 /// if necessary. If the ID does not correspond to a closure ID, returns None.
457 pub fn get_or_create_declaration_if_unboxed_closure<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
458                                                               closure_id: ast::DefId,
459                                                               substs: &Substs<'tcx>)
460                                                               -> Option<Datum<'tcx, Rvalue>> {
461     if !ccx.tcx().unboxed_closures.borrow().contains_key(&closure_id) {
462         // Not an unboxed closure.
463         return None
464     }
465
466     let function_type = ty::node_id_to_type(ccx.tcx(), closure_id.node);
467     let function_type = monomorphize::apply_param_substs(ccx.tcx(), substs, &function_type);
468
469     // Normalize type so differences in regions and typedefs don't cause
470     // duplicate declarations
471     let function_type = ty::normalize_ty(ccx.tcx(), function_type);
472     let params = match function_type.sty {
473         ty::ty_unboxed_closure(_, _, ref substs) => substs.types.clone(),
474         _ => unreachable!()
475     };
476     let mono_id = MonoId {
477         def: closure_id,
478         params: params
479     };
480
481     match ccx.unboxed_closure_vals().borrow().get(&mono_id) {
482         Some(&llfn) => {
483             debug!("get_or_create_declaration_if_unboxed_closure(): found \
484                     closure");
485             return Some(Datum::new(llfn, function_type, Rvalue::new(ByValue)))
486         }
487         None => {}
488     }
489
490     let symbol = ccx.tcx().map.with_path(closure_id.node, |path| {
491         mangle_internal_name_by_path_and_seq(path, "unboxed_closure")
492     });
493
494     let llfn = decl_internal_rust_fn(ccx, function_type, symbol[]);
495
496     // set an inline hint for all closures
497     set_inline_hint(llfn);
498
499     debug!("get_or_create_declaration_if_unboxed_closure(): inserting new \
500             closure {} (type {})",
501            mono_id,
502            ccx.tn().type_to_string(val_ty(llfn)));
503     ccx.unboxed_closure_vals().borrow_mut().insert(mono_id, llfn);
504
505     Some(Datum::new(llfn, function_type, Rvalue::new(ByValue)))
506 }
507
508 pub fn trans_unboxed_closure<'blk, 'tcx>(
509                              mut bcx: Block<'blk, 'tcx>,
510                              decl: &ast::FnDecl,
511                              body: &ast::Block,
512                              id: ast::NodeId,
513                              dest: expr::Dest)
514                              -> Block<'blk, 'tcx>
515 {
516     let _icx = push_ctxt("closure::trans_unboxed_closure");
517
518     debug!("trans_unboxed_closure()");
519
520     let closure_id = ast_util::local_def(id);
521     let llfn = get_or_create_declaration_if_unboxed_closure(
522         bcx.ccx(),
523         closure_id,
524         bcx.fcx.param_substs).unwrap();
525
526     // Get the type of this closure. Use the current `param_substs` as
527     // the closure substitutions. This makes sense because the closure
528     // takes the same set of type arguments as the enclosing fn, and
529     // this function (`trans_unboxed_closure`) is invoked at the point
530     // of the closure expression.
531     let typer = NormalizingUnboxedClosureTyper::new(bcx.tcx());
532     let function_type = typer.unboxed_closure_type(closure_id, bcx.fcx.param_substs);
533     let function_type = ty::mk_closure(bcx.tcx(), function_type);
534
535     let freevars: Vec<ty::Freevar> =
536         ty::with_freevars(bcx.tcx(), id, |fv| fv.iter().map(|&fv| fv).collect());
537     let freevar_mode = bcx.tcx().capture_mode(id);
538
539     trans_closure(bcx.ccx(),
540                   decl,
541                   body,
542                   llfn.val,
543                   bcx.fcx.param_substs,
544                   id,
545                   &[],
546                   ty::ty_fn_ret(function_type),
547                   ty::ty_fn_abi(function_type),
548                   ClosureEnv::new(freevars[],
549                                   UnboxedClosure(freevar_mode)));
550
551     // Don't hoist this to the top of the function. It's perfectly legitimate
552     // to have a zero-size unboxed closure (in which case dest will be
553     // `Ignore`) and we must still generate the closure body.
554     let dest_addr = match dest {
555         expr::SaveIn(p) => p,
556         expr::Ignore => {
557             debug!("trans_unboxed_closure() ignoring result");
558             return bcx
559         }
560     };
561
562     let repr = adt::represent_type(bcx.ccx(), node_id_type(bcx, id));
563
564     // Create the closure.
565     for (i, freevar) in freevars.iter().enumerate() {
566         let datum = expr::trans_local_var(bcx, freevar.def);
567         let upvar_slot_dest = adt::trans_field_ptr(bcx,
568                                                    &*repr,
569                                                    dest_addr,
570                                                    0,
571                                                    i);
572         match freevar_mode {
573             ast::CaptureByValue => {
574                 bcx = datum.store_to(bcx, upvar_slot_dest);
575             }
576             ast::CaptureByRef => {
577                 Store(bcx, datum.to_llref(), upvar_slot_dest);
578             }
579         }
580     }
581     adt::trans_set_discr(bcx, &*repr, dest_addr, 0);
582
583     bcx
584 }
585
586 pub fn get_wrapper_for_bare_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
587                                          closure_ty: Ty<'tcx>,
588                                          def_id: ast::DefId,
589                                          fn_ptr: ValueRef,
590                                          is_local: bool) -> ValueRef {
591
592     match ccx.closure_bare_wrapper_cache().borrow().get(&fn_ptr) {
593         Some(&llval) => return llval,
594         None => {}
595     }
596
597     let tcx = ccx.tcx();
598
599     debug!("get_wrapper_for_bare_fn(closure_ty={})", closure_ty.repr(tcx));
600
601     let f = match closure_ty.sty {
602         ty::ty_closure(ref f) => f,
603         _ => {
604             ccx.sess().bug(format!("get_wrapper_for_bare_fn: \
605                                     expected a closure ty, got {}",
606                                     closure_ty.repr(tcx))[]);
607         }
608     };
609
610     let name = ty::with_path(tcx, def_id, |path| {
611         mangle_internal_name_by_path_and_seq(path, "as_closure")
612     });
613     let llfn = if is_local {
614         decl_internal_rust_fn(ccx, closure_ty, name[])
615     } else {
616         decl_rust_fn(ccx, closure_ty, name[])
617     };
618
619     ccx.closure_bare_wrapper_cache().borrow_mut().insert(fn_ptr, llfn);
620
621     // This is only used by statics inlined from a different crate.
622     if !is_local {
623         // Don't regenerate the wrapper, just reuse the original one.
624         return llfn;
625     }
626
627     let _icx = push_ctxt("closure::get_wrapper_for_bare_fn");
628
629     let arena = TypedArena::new();
630     let empty_param_substs = Substs::trans_empty();
631     let fcx = new_fn_ctxt(ccx, llfn, ast::DUMMY_NODE_ID, true, f.sig.0.output,
632                           &empty_param_substs, None, &arena);
633     let bcx = init_function(&fcx, true, f.sig.0.output);
634
635     let args = create_datums_for_fn_args(&fcx,
636                                          ty::ty_fn_args(closure_ty)
637                                             []);
638     let mut llargs = Vec::new();
639     match fcx.llretslotptr.get() {
640         Some(llretptr) => {
641             assert!(!fcx.needs_ret_allocas);
642             llargs.push(llretptr);
643         }
644         None => {}
645     }
646     llargs.extend(args.iter().map(|arg| arg.val));
647
648     let retval = Call(bcx, fn_ptr, llargs.as_slice(), None);
649     match f.sig.0.output {
650         ty::FnConverging(output_type) => {
651             if return_type_is_void(ccx, output_type) || fcx.llretslotptr.get().is_some() {
652                 RetVoid(bcx);
653             } else {
654                 Ret(bcx, retval);
655             }
656         }
657         ty::FnDiverging => {
658             RetVoid(bcx);
659         }
660     }
661
662     // HACK(eddyb) finish_fn cannot be used here, we returned directly.
663     debuginfo::clear_source_location(&fcx);
664     fcx.cleanup();
665
666     llfn
667 }
668
669 pub fn make_closure_from_bare_fn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
670                                              closure_ty: Ty<'tcx>,
671                                              def_id: ast::DefId,
672                                              fn_ptr: ValueRef)
673                                              -> DatumBlock<'blk, 'tcx, Expr>  {
674     let scratch = rvalue_scratch_datum(bcx, closure_ty, "__adjust");
675     let wrapper = get_wrapper_for_bare_fn(bcx.ccx(), closure_ty, def_id, fn_ptr, true);
676     fill_fn_pair(bcx, scratch.val, wrapper, C_null(Type::i8p(bcx.ccx())));
677
678     DatumBlock::new(bcx, scratch.to_expr_datum())
679 }