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