]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/build/mod.rs
Add #[must_use] to a few standard library methods
[rust.git] / src / librustc_mir / build / mod.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 build;
13 use hair::cx::Cx;
14 use hair::{LintLevel, BindingMode, PatternKind};
15 use rustc::hir;
16 use rustc::hir::def_id::{DefId, LocalDefId};
17 use rustc::middle::region;
18 use rustc::mir::*;
19 use rustc::mir::visit::{MutVisitor, TyContext};
20 use rustc::ty::{self, Ty, TyCtxt};
21 use rustc::ty::subst::Substs;
22 use rustc::util::nodemap::NodeMap;
23 use rustc_back::PanicStrategy;
24 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
25 use shim;
26 use std::mem;
27 use std::u32;
28 use syntax::abi::Abi;
29 use syntax::ast;
30 use syntax::attr::{self, UnwindAttr};
31 use syntax::symbol::keywords;
32 use syntax_pos::Span;
33 use transform::MirSource;
34 use util as mir_util;
35
36 /// Construct the MIR for a given def-id.
37 pub fn mir_build<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Mir<'tcx> {
38     let id = tcx.hir.as_local_node_id(def_id).unwrap();
39     let unsupported = || {
40         span_bug!(tcx.hir.span(id), "can't build MIR for {:?}", def_id);
41     };
42
43     // Figure out what primary body this item has.
44     let body_id = match tcx.hir.get(id) {
45         hir::map::NodeItem(item) => {
46             match item.node {
47                 hir::ItemConst(_, body) |
48                 hir::ItemStatic(_, _, body) |
49                 hir::ItemFn(.., body) => body,
50                 _ => unsupported()
51             }
52         }
53         hir::map::NodeTraitItem(item) => {
54             match item.node {
55                 hir::TraitItemKind::Const(_, Some(body)) |
56                 hir::TraitItemKind::Method(_,
57                     hir::TraitMethod::Provided(body)) => body,
58                 _ => unsupported()
59             }
60         }
61         hir::map::NodeImplItem(item) => {
62             match item.node {
63                 hir::ImplItemKind::Const(_, body) |
64                 hir::ImplItemKind::Method(_, body) => body,
65                 _ => unsupported()
66             }
67         }
68         hir::map::NodeExpr(expr) => {
69             // FIXME(eddyb) Closures should have separate
70             // function definition IDs and expression IDs.
71             // Type-checking should not let closures get
72             // this far in a constant position.
73             // Assume that everything other than closures
74             // is a constant "initializer" expression.
75             match expr.node {
76                 hir::ExprClosure(_, _, body, _, _) => body,
77                 _ => hir::BodyId { node_id: expr.id },
78             }
79         }
80         hir::map::NodeVariant(variant) =>
81             return create_constructor_shim(tcx, id, &variant.node.data),
82         hir::map::NodeStructCtor(ctor) =>
83             return create_constructor_shim(tcx, id, ctor),
84         _ => unsupported(),
85     };
86
87     tcx.infer_ctxt().enter(|infcx| {
88         let cx = Cx::new(&infcx, id);
89         let mut mir = if cx.tables().tainted_by_errors {
90             build::construct_error(cx, body_id)
91         } else if let hir::BodyOwnerKind::Fn = cx.body_owner_kind {
92             // fetch the fully liberated fn signature (that is, all bound
93             // types/lifetimes replaced)
94             let fn_hir_id = tcx.hir.node_to_hir_id(id);
95             let fn_sig = cx.tables().liberated_fn_sigs()[fn_hir_id].clone();
96
97             let ty = tcx.type_of(tcx.hir.local_def_id(id));
98             let mut abi = fn_sig.abi;
99             let implicit_argument = match ty.sty {
100                 ty::TyClosure(..) => {
101                     // HACK(eddyb) Avoid having RustCall on closures,
102                     // as it adds unnecessary (and wrong) auto-tupling.
103                     abi = Abi::Rust;
104                     Some((liberated_closure_env_ty(tcx, id, body_id), None))
105                 }
106                 ty::TyGenerator(..) => {
107                     let gen_ty = tcx.body_tables(body_id).node_id_to_type(fn_hir_id);
108                     Some((gen_ty, None))
109                 }
110                 _ => None,
111             };
112
113             // FIXME: safety in closures
114             let safety = match fn_sig.unsafety {
115                 hir::Unsafety::Normal => Safety::Safe,
116                 hir::Unsafety::Unsafe => Safety::FnUnsafe,
117             };
118
119             let body = tcx.hir.body(body_id);
120             let explicit_arguments =
121                 body.arguments
122                     .iter()
123                     .enumerate()
124                     .map(|(index, arg)| {
125                         (fn_sig.inputs()[index], Some(&*arg.pat))
126                     });
127
128             let arguments = implicit_argument.into_iter().chain(explicit_arguments);
129
130             let (yield_ty, return_ty) = if body.is_generator {
131                 let gen_sig = match ty.sty {
132                     ty::TyGenerator(gen_def_id, gen_substs, ..) =>
133                         gen_substs.generator_sig(gen_def_id, tcx),
134                     _ =>
135                         span_bug!(tcx.hir.span(id), "generator w/o generator type: {:?}", ty),
136                 };
137                 (Some(gen_sig.yield_ty), gen_sig.return_ty)
138             } else {
139                 (None, fn_sig.output())
140             };
141
142             build::construct_fn(cx, id, arguments, safety, abi,
143                                 return_ty, yield_ty, body)
144         } else {
145             build::construct_const(cx, body_id)
146         };
147
148         // Convert the Mir to global types.
149         let mut globalizer = GlobalizeMir {
150             tcx,
151             span: mir.span
152         };
153         globalizer.visit_mir(&mut mir);
154         let mir = unsafe {
155             mem::transmute::<Mir, Mir<'tcx>>(mir)
156         };
157
158         mir_util::dump_mir(tcx, None, "mir_map", &0,
159                            MirSource::item(def_id), &mir, |_, _| Ok(()) );
160
161         mir
162     })
163 }
164
165 /// A pass to lift all the types and substitutions in a Mir
166 /// to the global tcx. Sadly, we don't have a "folder" that
167 /// can change 'tcx so we have to transmute afterwards.
168 struct GlobalizeMir<'a, 'gcx: 'a> {
169     tcx: TyCtxt<'a, 'gcx, 'gcx>,
170     span: Span
171 }
172
173 impl<'a, 'gcx: 'tcx, 'tcx> MutVisitor<'tcx> for GlobalizeMir<'a, 'gcx> {
174     fn visit_ty(&mut self, ty: &mut Ty<'tcx>, _: TyContext) {
175         if let Some(lifted) = self.tcx.lift(ty) {
176             *ty = lifted;
177         } else {
178             span_bug!(self.span,
179                       "found type `{:?}` with inference types/regions in MIR",
180                       ty);
181         }
182     }
183
184     fn visit_region(&mut self, region: &mut ty::Region<'tcx>, _: Location) {
185         if let Some(lifted) = self.tcx.lift(region) {
186             *region = lifted;
187         } else {
188             span_bug!(self.span,
189                       "found region `{:?}` with inference types/regions in MIR",
190                       region);
191         }
192     }
193
194     fn visit_const(&mut self, constant: &mut &'tcx ty::Const<'tcx>, _: Location) {
195         if let Some(lifted) = self.tcx.lift(constant) {
196             *constant = lifted;
197         } else {
198             span_bug!(self.span,
199                       "found constant `{:?}` with inference types/regions in MIR",
200                       constant);
201         }
202     }
203
204     fn visit_substs(&mut self, substs: &mut &'tcx Substs<'tcx>, _: Location) {
205         if let Some(lifted) = self.tcx.lift(substs) {
206             *substs = lifted;
207         } else {
208             span_bug!(self.span,
209                       "found substs `{:?}` with inference types/regions in MIR",
210                       substs);
211         }
212     }
213 }
214
215 fn create_constructor_shim<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
216                                      ctor_id: ast::NodeId,
217                                      v: &'tcx hir::VariantData)
218                                      -> Mir<'tcx>
219 {
220     let span = tcx.hir.span(ctor_id);
221     if let hir::VariantData::Tuple(ref fields, ctor_id) = *v {
222         tcx.infer_ctxt().enter(|infcx| {
223             let mut mir = shim::build_adt_ctor(&infcx, ctor_id, fields, span);
224
225             // Convert the Mir to global types.
226             let tcx = infcx.tcx.global_tcx();
227             let mut globalizer = GlobalizeMir {
228                 tcx,
229                 span: mir.span
230             };
231             globalizer.visit_mir(&mut mir);
232             let mir = unsafe {
233                 mem::transmute::<Mir, Mir<'tcx>>(mir)
234             };
235
236             mir_util::dump_mir(tcx, None, "mir_map", &0,
237                                MirSource::item(tcx.hir.local_def_id(ctor_id)),
238                                &mir, |_, _| Ok(()) );
239
240             mir
241         })
242     } else {
243         span_bug!(span, "attempting to create MIR for non-tuple variant {:?}", v);
244     }
245 }
246
247 ///////////////////////////////////////////////////////////////////////////
248 // BuildMir -- walks a crate, looking for fn items and methods to build MIR from
249
250 fn liberated_closure_env_ty<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
251                                             closure_expr_id: ast::NodeId,
252                                             body_id: hir::BodyId)
253                                             -> Ty<'tcx> {
254     let closure_expr_hir_id = tcx.hir.node_to_hir_id(closure_expr_id);
255     let closure_ty = tcx.body_tables(body_id).node_id_to_type(closure_expr_hir_id);
256
257     let (closure_def_id, closure_substs) = match closure_ty.sty {
258         ty::TyClosure(closure_def_id, closure_substs) => (closure_def_id, closure_substs),
259         _ => bug!("closure expr does not have closure type: {:?}", closure_ty)
260     };
261
262     let closure_env_ty = tcx.closure_env_ty(closure_def_id, closure_substs).unwrap();
263     tcx.liberate_late_bound_regions(closure_def_id, &closure_env_ty)
264 }
265
266 struct Builder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
267     hir: Cx<'a, 'gcx, 'tcx>,
268     cfg: CFG<'tcx>,
269
270     fn_span: Span,
271     arg_count: usize,
272
273     /// the current set of scopes, updated as we traverse;
274     /// see the `scope` module for more details
275     scopes: Vec<scope::Scope<'tcx>>,
276
277     /// The current unsafe block in scope, even if it is hidden by
278     /// a PushUnsafeBlock
279     unpushed_unsafe: Safety,
280
281     /// The number of `push_unsafe_block` levels in scope
282     push_unsafe_count: usize,
283
284     /// the current set of breakables; see the `scope` module for more
285     /// details
286     breakable_scopes: Vec<scope::BreakableScope<'tcx>>,
287
288     /// the vector of all scopes that we have created thus far;
289     /// we track this for debuginfo later
290     visibility_scopes: IndexVec<VisibilityScope, VisibilityScopeData>,
291     visibility_scope_info: IndexVec<VisibilityScope, VisibilityScopeInfo>,
292     visibility_scope: VisibilityScope,
293
294     /// Maps node ids of variable bindings to the `Local`s created for them.
295     var_indices: NodeMap<Local>,
296     local_decls: IndexVec<Local, LocalDecl<'tcx>>,
297     unit_temp: Option<Place<'tcx>>,
298
299     /// cached block with the RESUME terminator; this is created
300     /// when first set of cleanups are built.
301     cached_resume_block: Option<BasicBlock>,
302     /// cached block with the RETURN terminator
303     cached_return_block: Option<BasicBlock>,
304     /// cached block with the UNREACHABLE terminator
305     cached_unreachable_block: Option<BasicBlock>,
306 }
307
308 struct CFG<'tcx> {
309     basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
310 }
311
312 newtype_index!(ScopeId);
313
314 ///////////////////////////////////////////////////////////////////////////
315 /// The `BlockAnd` "monad" packages up the new basic block along with a
316 /// produced value (sometimes just unit, of course). The `unpack!`
317 /// macro (and methods below) makes working with `BlockAnd` much more
318 /// convenient.
319
320 #[must_use = "if you don't use one of these results, you're leaving a dangling edge"]
321 struct BlockAnd<T>(BasicBlock, T);
322
323 trait BlockAndExtension {
324     fn and<T>(self, v: T) -> BlockAnd<T>;
325     fn unit(self) -> BlockAnd<()>;
326 }
327
328 impl BlockAndExtension for BasicBlock {
329     fn and<T>(self, v: T) -> BlockAnd<T> {
330         BlockAnd(self, v)
331     }
332
333     fn unit(self) -> BlockAnd<()> {
334         BlockAnd(self, ())
335     }
336 }
337
338 /// Update a block pointer and return the value.
339 /// Use it like `let x = unpack!(block = self.foo(block, foo))`.
340 macro_rules! unpack {
341     ($x:ident = $c:expr) => {
342         {
343             let BlockAnd(b, v) = $c;
344             $x = b;
345             v
346         }
347     };
348
349     ($c:expr) => {
350         {
351             let BlockAnd(b, ()) = $c;
352             b
353         }
354     };
355 }
356
357 fn should_abort_on_panic<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
358                                          fn_def_id: DefId,
359                                          abi: Abi)
360                                          -> bool {
361     // Not callable from C, so we can safely unwind through these
362     if abi == Abi::Rust || abi == Abi::RustCall { return false; }
363
364     // We never unwind, so it's not relevant to stop an unwind
365     if tcx.sess.panic_strategy() != PanicStrategy::Unwind { return false; }
366
367     // We cannot add landing pads, so don't add one
368     if tcx.sess.no_landing_pads() { return false; }
369
370     // This is a special case: some functions have a C abi but are meant to
371     // unwind anyway. Don't stop them.
372     let attrs = &tcx.get_attrs(fn_def_id);
373     match attr::find_unwind_attr(Some(tcx.sess.diagnostic()), attrs) {
374         None => {
375             // FIXME(rust-lang/rust#48251) -- Had to disable
376             // abort-on-panic for backwards compatibility reasons.
377             false
378         }
379
380         Some(UnwindAttr::Allowed) => false,
381         Some(UnwindAttr::Aborts) => true,
382     }
383 }
384
385 ///////////////////////////////////////////////////////////////////////////
386 /// the main entry point for building MIR for a function
387
388 fn construct_fn<'a, 'gcx, 'tcx, A>(hir: Cx<'a, 'gcx, 'tcx>,
389                                    fn_id: ast::NodeId,
390                                    arguments: A,
391                                    safety: Safety,
392                                    abi: Abi,
393                                    return_ty: Ty<'gcx>,
394                                    yield_ty: Option<Ty<'gcx>>,
395                                    body: &'gcx hir::Body)
396                                    -> Mir<'tcx>
397     where A: Iterator<Item=(Ty<'gcx>, Option<&'gcx hir::Pat>)>
398 {
399     let arguments: Vec<_> = arguments.collect();
400
401     let tcx = hir.tcx();
402     let span = tcx.hir.span(fn_id);
403     let mut builder = Builder::new(hir.clone(),
404         span,
405         arguments.len(),
406         safety,
407         return_ty);
408
409     let fn_def_id = tcx.hir.local_def_id(fn_id);
410     let call_site_scope = region::Scope::CallSite(body.value.hir_id.local_id);
411     let arg_scope = region::Scope::Arguments(body.value.hir_id.local_id);
412     let mut block = START_BLOCK;
413     let source_info = builder.source_info(span);
414     let call_site_s = (call_site_scope, source_info);
415     unpack!(block = builder.in_scope(call_site_s, LintLevel::Inherited, block, |builder| {
416         if should_abort_on_panic(tcx, fn_def_id, abi) {
417             builder.schedule_abort();
418         }
419
420         let arg_scope_s = (arg_scope, source_info);
421         unpack!(block = builder.in_scope(arg_scope_s, LintLevel::Inherited, block, |builder| {
422             builder.args_and_body(block, &arguments, arg_scope, &body.value)
423         }));
424         // Attribute epilogue to function's closing brace
425         let fn_end = span.shrink_to_hi();
426         let source_info = builder.source_info(fn_end);
427         let return_block = builder.return_block();
428         builder.cfg.terminate(block, source_info,
429                               TerminatorKind::Goto { target: return_block });
430         builder.cfg.terminate(return_block, source_info,
431                               TerminatorKind::Return);
432         // Attribute any unreachable codepaths to the function's closing brace
433         if let Some(unreachable_block) = builder.cached_unreachable_block {
434             builder.cfg.terminate(unreachable_block, source_info,
435                                   TerminatorKind::Unreachable);
436         }
437         return_block.unit()
438     }));
439     assert_eq!(block, builder.return_block());
440
441     let mut spread_arg = None;
442     if abi == Abi::RustCall {
443         // RustCall pseudo-ABI untuples the last argument.
444         spread_arg = Some(Local::new(arguments.len()));
445     }
446     let closure_expr_id = tcx.hir.local_def_id(fn_id);
447     info!("fn_id {:?} has attrs {:?}", closure_expr_id,
448           tcx.get_attrs(closure_expr_id));
449
450     // Gather the upvars of a closure, if any.
451     let upvar_decls: Vec<_> = tcx.with_freevars(fn_id, |freevars| {
452         freevars.iter().map(|fv| {
453             let var_id = fv.var_id();
454             let var_hir_id = tcx.hir.node_to_hir_id(var_id);
455             let closure_expr_id = tcx.hir.local_def_id(fn_id);
456             let capture = hir.tables().upvar_capture(ty::UpvarId {
457                 var_id: var_hir_id,
458                 closure_expr_id: LocalDefId::from_def_id(closure_expr_id),
459             });
460             let by_ref = match capture {
461                 ty::UpvarCapture::ByValue => false,
462                 ty::UpvarCapture::ByRef(..) => true
463             };
464             let mut decl = UpvarDecl {
465                 debug_name: keywords::Invalid.name(),
466                 by_ref,
467                 mutability: Mutability::Not,
468             };
469             if let Some(hir::map::NodeBinding(pat)) = tcx.hir.find(var_id) {
470                 if let hir::PatKind::Binding(_, _, ref ident, _) = pat.node {
471                     decl.debug_name = ident.node;
472
473                     let bm = *hir.tables.pat_binding_modes()
474                                         .get(pat.hir_id)
475                                         .expect("missing binding mode");
476                     if bm == ty::BindByValue(hir::MutMutable) {
477                         decl.mutability = Mutability::Mut;
478                     } else {
479                         decl.mutability = Mutability::Not;
480                     }
481                 }
482             }
483             decl
484         }).collect()
485     });
486
487     let mut mir = builder.finish(upvar_decls, yield_ty);
488     mir.spread_arg = spread_arg;
489     mir
490 }
491
492 fn construct_const<'a, 'gcx, 'tcx>(hir: Cx<'a, 'gcx, 'tcx>,
493                                    body_id: hir::BodyId)
494                                    -> Mir<'tcx> {
495     let tcx = hir.tcx();
496     let ast_expr = &tcx.hir.body(body_id).value;
497     let ty = hir.tables().expr_ty_adjusted(ast_expr);
498     let owner_id = tcx.hir.body_owner(body_id);
499     let span = tcx.hir.span(owner_id);
500     let mut builder = Builder::new(hir.clone(), span, 0, Safety::Safe, ty);
501
502     let mut block = START_BLOCK;
503     let expr = builder.hir.mirror(ast_expr);
504     unpack!(block = builder.into_expr(&Place::Local(RETURN_PLACE), block, expr));
505
506     let source_info = builder.source_info(span);
507     builder.cfg.terminate(block, source_info, TerminatorKind::Return);
508
509     // Constants can't `return` so a return block should not be created.
510     assert_eq!(builder.cached_return_block, None);
511
512     // Constants may be match expressions in which case an unreachable block may
513     // be created, so terminate it properly.
514     if let Some(unreachable_block) = builder.cached_unreachable_block {
515         builder.cfg.terminate(unreachable_block, source_info,
516                               TerminatorKind::Unreachable);
517     }
518
519     builder.finish(vec![], None)
520 }
521
522 fn construct_error<'a, 'gcx, 'tcx>(hir: Cx<'a, 'gcx, 'tcx>,
523                                    body_id: hir::BodyId)
524                                    -> Mir<'tcx> {
525     let owner_id = hir.tcx().hir.body_owner(body_id);
526     let span = hir.tcx().hir.span(owner_id);
527     let ty = hir.tcx().types.err;
528     let mut builder = Builder::new(hir, span, 0, Safety::Safe, ty);
529     let source_info = builder.source_info(span);
530     builder.cfg.terminate(START_BLOCK, source_info, TerminatorKind::Unreachable);
531     builder.finish(vec![], None)
532 }
533
534 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
535     fn new(hir: Cx<'a, 'gcx, 'tcx>,
536            span: Span,
537            arg_count: usize,
538            safety: Safety,
539            return_ty: Ty<'tcx>)
540            -> Builder<'a, 'gcx, 'tcx> {
541         let lint_level = LintLevel::Explicit(hir.root_lint_level);
542         let mut builder = Builder {
543             hir,
544             cfg: CFG { basic_blocks: IndexVec::new() },
545             fn_span: span,
546             arg_count,
547             scopes: vec![],
548             visibility_scopes: IndexVec::new(),
549             visibility_scope: ARGUMENT_VISIBILITY_SCOPE,
550             visibility_scope_info: IndexVec::new(),
551             push_unsafe_count: 0,
552             unpushed_unsafe: safety,
553             breakable_scopes: vec![],
554             local_decls: IndexVec::from_elem_n(LocalDecl::new_return_place(return_ty,
555                                                                              span), 1),
556             var_indices: NodeMap(),
557             unit_temp: None,
558             cached_resume_block: None,
559             cached_return_block: None,
560             cached_unreachable_block: None,
561         };
562
563         assert_eq!(builder.cfg.start_new_block(), START_BLOCK);
564         assert_eq!(
565             builder.new_visibility_scope(span, lint_level, Some(safety)),
566             ARGUMENT_VISIBILITY_SCOPE);
567         builder.visibility_scopes[ARGUMENT_VISIBILITY_SCOPE].parent_scope = None;
568
569         builder
570     }
571
572     fn finish(self,
573               upvar_decls: Vec<UpvarDecl>,
574               yield_ty: Option<Ty<'tcx>>)
575               -> Mir<'tcx> {
576         for (index, block) in self.cfg.basic_blocks.iter().enumerate() {
577             if block.terminator.is_none() {
578                 span_bug!(self.fn_span, "no terminator on block {:?}", index);
579             }
580         }
581
582         Mir::new(self.cfg.basic_blocks,
583                  self.visibility_scopes,
584                  ClearCrossCrate::Set(self.visibility_scope_info),
585                  IndexVec::new(),
586                  yield_ty,
587                  self.local_decls,
588                  self.arg_count,
589                  upvar_decls,
590                  self.fn_span
591         )
592     }
593
594     fn args_and_body(&mut self,
595                      mut block: BasicBlock,
596                      arguments: &[(Ty<'gcx>, Option<&'gcx hir::Pat>)],
597                      argument_scope: region::Scope,
598                      ast_body: &'gcx hir::Expr)
599                      -> BlockAnd<()>
600     {
601         // Allocate locals for the function arguments
602         for &(ty, pattern) in arguments.iter() {
603             // If this is a simple binding pattern, give the local a nice name for debuginfo.
604             let mut name = None;
605             if let Some(pat) = pattern {
606                 if let hir::PatKind::Binding(_, _, ref ident, _) = pat.node {
607                     name = Some(ident.node);
608                 }
609             }
610
611             self.local_decls.push(LocalDecl {
612                 mutability: Mutability::Mut,
613                 ty,
614                 source_info: SourceInfo {
615                     scope: ARGUMENT_VISIBILITY_SCOPE,
616                     span: pattern.map_or(self.fn_span, |pat| pat.span)
617                 },
618                 syntactic_scope: ARGUMENT_VISIBILITY_SCOPE,
619                 name,
620                 internal: false,
621                 is_user_variable: false,
622             });
623         }
624
625         let mut scope = None;
626         // Bind the argument patterns
627         for (index, &(ty, pattern)) in arguments.iter().enumerate() {
628             // Function arguments always get the first Local indices after the return place
629             let local = Local::new(index + 1);
630             let place = Place::Local(local);
631
632             if let Some(pattern) = pattern {
633                 let pattern = self.hir.pattern_from_hir(pattern);
634
635                 match *pattern.kind {
636                     // Don't introduce extra copies for simple bindings
637                     PatternKind::Binding { mutability, var, mode: BindingMode::ByValue, .. } => {
638                         self.local_decls[local].mutability = mutability;
639                         self.var_indices.insert(var, local);
640                     }
641                     _ => {
642                         scope = self.declare_bindings(scope, ast_body.span,
643                                                       LintLevel::Inherited, &pattern);
644                         unpack!(block = self.place_into_pattern(block, pattern, &place));
645                     }
646                 }
647             }
648
649             // Make sure we drop (parts of) the argument even when not matched on.
650             self.schedule_drop(pattern.as_ref().map_or(ast_body.span, |pat| pat.span),
651                                argument_scope, &place, ty);
652
653         }
654
655         // Enter the argument pattern bindings visibility scope, if it exists.
656         if let Some(visibility_scope) = scope {
657             self.visibility_scope = visibility_scope;
658         }
659
660         let body = self.hir.mirror(ast_body);
661         self.into(&Place::Local(RETURN_PLACE), block, body)
662     }
663
664     fn get_unit_temp(&mut self) -> Place<'tcx> {
665         match self.unit_temp {
666             Some(ref tmp) => tmp.clone(),
667             None => {
668                 let ty = self.hir.unit_ty();
669                 let fn_span = self.fn_span;
670                 let tmp = self.temp(ty, fn_span);
671                 self.unit_temp = Some(tmp.clone());
672                 tmp
673             }
674         }
675     }
676
677     fn return_block(&mut self) -> BasicBlock {
678         match self.cached_return_block {
679             Some(rb) => rb,
680             None => {
681                 let rb = self.cfg.start_new_block();
682                 self.cached_return_block = Some(rb);
683                 rb
684             }
685         }
686     }
687
688     fn unreachable_block(&mut self) -> BasicBlock {
689         match self.cached_unreachable_block {
690             Some(ub) => ub,
691             None => {
692                 let ub = self.cfg.start_new_block();
693                 self.cached_unreachable_block = Some(ub);
694                 ub
695             }
696         }
697     }
698 }
699
700 ///////////////////////////////////////////////////////////////////////////
701 // Builder methods are broken up into modules, depending on what kind
702 // of thing is being translated. Note that they use the `unpack` macro
703 // above extensively.
704
705 mod block;
706 mod cfg;
707 mod expr;
708 mod into;
709 mod matches;
710 mod misc;
711 mod scope;