]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/build/mod.rs
Clear up some code
[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 build::scope::{CachedBlock, DropKind};
14 use hair::cx::Cx;
15 use hair::{LintLevel, BindingMode, PatternKind};
16 use rustc::hir;
17 use rustc::hir::Node;
18 use rustc::hir::def_id::{DefId, LocalDefId};
19 use rustc::middle::region;
20 use rustc::mir::*;
21 use rustc::mir::visit::{MutVisitor, TyContext};
22 use rustc::ty::{self, Ty, TyCtxt};
23 use rustc::ty::subst::Substs;
24 use rustc::util::nodemap::NodeMap;
25 use rustc_target::spec::PanicStrategy;
26 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
27 use shim;
28 use std::mem;
29 use std::u32;
30 use rustc_target::spec::abi::Abi;
31 use syntax::ast;
32 use syntax::attr::{self, UnwindAttr};
33 use syntax::symbol::keywords;
34 use syntax_pos::Span;
35 use transform::MirSource;
36 use util as mir_util;
37
38 use super::lints;
39
40 /// Construct the MIR for a given def-id.
41 pub fn mir_build<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Mir<'tcx> {
42     let id = tcx.hir.as_local_node_id(def_id).unwrap();
43
44     // Figure out what primary body this item has.
45     let (body_id, return_ty_span) = match tcx.hir.get(id) {
46         Node::Variant(variant) =>
47             return create_constructor_shim(tcx, id, &variant.node.data),
48         Node::StructCtor(ctor) =>
49             return create_constructor_shim(tcx, id, ctor),
50
51         Node::Expr(hir::Expr { node: hir::ExprKind::Closure(_, decl, body_id, _, _), .. })
52         | Node::Item(hir::Item { node: hir::ItemKind::Fn(decl, _, _, body_id), .. })
53         | Node::ImplItem(
54             hir::ImplItem {
55                 node: hir::ImplItemKind::Method(hir::MethodSig { decl, .. }, body_id),
56                 ..
57             }
58         )
59         | Node::TraitItem(
60             hir::TraitItem {
61                 node: hir::TraitItemKind::Method(
62                     hir::MethodSig { decl, .. },
63                     hir::TraitMethod::Provided(body_id),
64                 ),
65                 ..
66             }
67         ) => {
68             (*body_id, decl.output.span())
69         }
70         Node::Item(hir::Item { node: hir::ItemKind::Static(ty, _, body_id), .. })
71         | Node::Item(hir::Item { node: hir::ItemKind::Const(ty, body_id), .. })
72         | Node::ImplItem(hir::ImplItem { node: hir::ImplItemKind::Const(ty, body_id), .. })
73         | Node::TraitItem(
74             hir::TraitItem { node: hir::TraitItemKind::Const(ty, Some(body_id)), .. }
75         ) => {
76             (*body_id, ty.span)
77         }
78         Node::AnonConst(hir::AnonConst { body, id, .. }) => {
79             (*body, tcx.hir.span(*id))
80         }
81
82         _ => span_bug!(tcx.hir.span(id), "can't build MIR for {:?}", def_id),
83     };
84
85     tcx.infer_ctxt().enter(|infcx| {
86         let cx = Cx::new(&infcx, id);
87         let mut mir = if cx.tables().tainted_by_errors {
88             build::construct_error(cx, body_id)
89         } else if let hir::BodyOwnerKind::Fn = cx.body_owner_kind {
90             // fetch the fully liberated fn signature (that is, all bound
91             // types/lifetimes replaced)
92             let fn_hir_id = tcx.hir.node_to_hir_id(id);
93             let fn_sig = cx.tables().liberated_fn_sigs()[fn_hir_id].clone();
94             let fn_def_id = tcx.hir.local_def_id(id);
95
96             let ty = tcx.type_of(fn_def_id);
97             let mut abi = fn_sig.abi;
98             let implicit_argument = match ty.sty {
99                 ty::Closure(..) => {
100                     // HACK(eddyb) Avoid having RustCall on closures,
101                     // as it adds unnecessary (and wrong) auto-tupling.
102                     abi = Abi::Rust;
103                     Some(ArgInfo(liberated_closure_env_ty(tcx, id, body_id), None, None, None))
104                 }
105                 ty::Generator(..) => {
106                     let gen_ty = tcx.body_tables(body_id).node_id_to_type(fn_hir_id);
107                     Some(ArgInfo(gen_ty, None, None, None))
108                 }
109                 _ => None,
110             };
111
112             let safety = match fn_sig.unsafety {
113                 hir::Unsafety::Normal => Safety::Safe,
114                 hir::Unsafety::Unsafe if tcx.is_min_const_fn(fn_def_id) => {
115                     // As specified in #55607, a `const unsafe fn` differs
116                     // from an `unsafe fn` in that its body is still considered
117                     // safe code by default.
118                     assert!(!implicit_argument.is_none());
119                     Safety::Safe
120                 },
121                 hir::Unsafety::Unsafe => Safety::FnUnsafe,
122             };
123
124             let body = tcx.hir.body(body_id);
125             let explicit_arguments =
126                 body.arguments
127                     .iter()
128                     .enumerate()
129                     .map(|(index, arg)| {
130                         let owner_id = tcx.hir.body_owner(body_id);
131                         let opt_ty_info;
132                         let self_arg;
133                         if let Some(ref fn_decl) = tcx.hir.fn_decl(owner_id) {
134                             let ty_hir_id = fn_decl.inputs[index].hir_id;
135                             let ty_span = tcx.hir.span(tcx.hir.hir_to_node_id(ty_hir_id));
136                             opt_ty_info = Some(ty_span);
137                             self_arg = if index == 0 && fn_decl.implicit_self.has_implicit_self() {
138                                 match fn_decl.implicit_self {
139                                     hir::ImplicitSelfKind::Imm => Some(ImplicitSelfKind::Imm),
140                                     hir::ImplicitSelfKind::Mut => Some(ImplicitSelfKind::Mut),
141                                     hir::ImplicitSelfKind::ImmRef => Some(ImplicitSelfKind::ImmRef),
142                                     hir::ImplicitSelfKind::MutRef => Some(ImplicitSelfKind::MutRef),
143                                     _ => None,
144                                 }
145                             } else {
146                                 None
147                             };
148                         } else {
149                             opt_ty_info = None;
150                             self_arg = None;
151                         }
152                         ArgInfo(fn_sig.inputs()[index], opt_ty_info, Some(&*arg.pat), self_arg)
153                     });
154
155             let arguments = implicit_argument.into_iter().chain(explicit_arguments);
156
157             let (yield_ty, return_ty) = if body.is_generator {
158                 let gen_sig = match ty.sty {
159                     ty::Generator(gen_def_id, gen_substs, ..) =>
160                         gen_substs.sig(gen_def_id, tcx),
161                     _ =>
162                         span_bug!(tcx.hir.span(id), "generator w/o generator type: {:?}", ty),
163                 };
164                 (Some(gen_sig.yield_ty), gen_sig.return_ty)
165             } else {
166                 (None, fn_sig.output())
167             };
168
169             build::construct_fn(cx, id, arguments, safety, abi,
170                                 return_ty, yield_ty, return_ty_span, body)
171         } else {
172             build::construct_const(cx, body_id, return_ty_span)
173         };
174
175         // Convert the Mir to global types.
176         let mut globalizer = GlobalizeMir {
177             tcx,
178             span: mir.span
179         };
180         globalizer.visit_mir(&mut mir);
181         let mir = unsafe {
182             mem::transmute::<Mir, Mir<'tcx>>(mir)
183         };
184
185         mir_util::dump_mir(tcx, None, "mir_map", &0,
186                            MirSource::item(def_id), &mir, |_, _| Ok(()) );
187
188         lints::check(tcx, &mir, def_id);
189
190         mir
191     })
192 }
193
194 /// A pass to lift all the types and substitutions in a Mir
195 /// to the global tcx. Sadly, we don't have a "folder" that
196 /// can change 'tcx so we have to transmute afterwards.
197 struct GlobalizeMir<'a, 'gcx: 'a> {
198     tcx: TyCtxt<'a, 'gcx, 'gcx>,
199     span: Span
200 }
201
202 impl<'a, 'gcx: 'tcx, 'tcx> MutVisitor<'tcx> for GlobalizeMir<'a, 'gcx> {
203     fn visit_ty(&mut self, ty: &mut Ty<'tcx>, _: TyContext) {
204         if let Some(lifted) = self.tcx.lift(ty) {
205             *ty = lifted;
206         } else {
207             span_bug!(self.span,
208                       "found type `{:?}` with inference types/regions in MIR",
209                       ty);
210         }
211     }
212
213     fn visit_region(&mut self, region: &mut ty::Region<'tcx>, _: Location) {
214         if let Some(lifted) = self.tcx.lift(region) {
215             *region = lifted;
216         } else {
217             span_bug!(self.span,
218                       "found region `{:?}` with inference types/regions in MIR",
219                       region);
220         }
221     }
222
223     fn visit_const(&mut self, constant: &mut &'tcx ty::Const<'tcx>, _: Location) {
224         if let Some(lifted) = self.tcx.lift(constant) {
225             *constant = lifted;
226         } else {
227             span_bug!(self.span,
228                       "found constant `{:?}` with inference types/regions in MIR",
229                       constant);
230         }
231     }
232
233     fn visit_substs(&mut self, substs: &mut &'tcx Substs<'tcx>, _: Location) {
234         if let Some(lifted) = self.tcx.lift(substs) {
235             *substs = lifted;
236         } else {
237             span_bug!(self.span,
238                       "found substs `{:?}` with inference types/regions in MIR",
239                       substs);
240         }
241     }
242 }
243
244 fn create_constructor_shim<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
245                                      ctor_id: ast::NodeId,
246                                      v: &'tcx hir::VariantData)
247                                      -> Mir<'tcx>
248 {
249     let span = tcx.hir.span(ctor_id);
250     if let hir::VariantData::Tuple(ref fields, ctor_id) = *v {
251         tcx.infer_ctxt().enter(|infcx| {
252             let mut mir = shim::build_adt_ctor(&infcx, ctor_id, fields, span);
253
254             // Convert the Mir to global types.
255             let tcx = infcx.tcx.global_tcx();
256             let mut globalizer = GlobalizeMir {
257                 tcx,
258                 span: mir.span
259             };
260             globalizer.visit_mir(&mut mir);
261             let mir = unsafe {
262                 mem::transmute::<Mir, Mir<'tcx>>(mir)
263             };
264
265             mir_util::dump_mir(tcx, None, "mir_map", &0,
266                                MirSource::item(tcx.hir.local_def_id(ctor_id)),
267                                &mir, |_, _| Ok(()) );
268
269             mir
270         })
271     } else {
272         span_bug!(span, "attempting to create MIR for non-tuple variant {:?}", v);
273     }
274 }
275
276 ///////////////////////////////////////////////////////////////////////////
277 // BuildMir -- walks a crate, looking for fn items and methods to build MIR from
278
279 fn liberated_closure_env_ty<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
280                                             closure_expr_id: ast::NodeId,
281                                             body_id: hir::BodyId)
282                                             -> Ty<'tcx> {
283     let closure_expr_hir_id = tcx.hir.node_to_hir_id(closure_expr_id);
284     let closure_ty = tcx.body_tables(body_id).node_id_to_type(closure_expr_hir_id);
285
286     let (closure_def_id, closure_substs) = match closure_ty.sty {
287         ty::Closure(closure_def_id, closure_substs) => (closure_def_id, closure_substs),
288         _ => bug!("closure expr does not have closure type: {:?}", closure_ty)
289     };
290
291     let closure_env_ty = tcx.closure_env_ty(closure_def_id, closure_substs).unwrap();
292     tcx.liberate_late_bound_regions(closure_def_id, &closure_env_ty)
293 }
294
295 #[derive(Debug, PartialEq, Eq)]
296 pub enum BlockFrame {
297     /// Evaluation is currently within a statement.
298     ///
299     /// Examples include:
300     ///  1. `EXPR;`
301     ///  2. `let _ = EXPR;`
302     ///  3. `let x = EXPR;`
303     Statement {
304         /// If true, then statement discards result from evaluating
305         /// the expression (such as examples 1 and 2 above).
306         ignores_expr_result: bool
307     },
308
309     /// Evaluation is currently within the tail expression of a block.
310     ///
311     /// Example: `{ STMT_1; STMT_2; EXPR }`
312     TailExpr {
313         /// If true, then the surrounding context of the block ignores
314         /// the result of evaluating the block's tail expression.
315         ///
316         /// Example: `let _ = { STMT_1; EXPR };`
317         tail_result_is_ignored: bool
318     },
319
320     /// Generic mark meaning that the block occurred as a subexpression
321     /// where the result might be used.
322     ///
323     /// Examples: `foo(EXPR)`, `match EXPR { ... }`
324     SubExpr,
325 }
326
327 impl BlockFrame {
328     fn is_tail_expr(&self) -> bool {
329         match *self {
330             BlockFrame::TailExpr { .. } => true,
331
332             BlockFrame::Statement { .. } |
333             BlockFrame::SubExpr => false,
334         }
335     }
336     fn is_statement(&self) -> bool {
337         match *self {
338             BlockFrame::Statement { .. } => true,
339
340             BlockFrame::TailExpr { .. } |
341             BlockFrame::SubExpr => false,
342         }
343     }
344  }
345
346 #[derive(Debug)]
347 struct BlockContext(Vec<BlockFrame>);
348
349 struct Builder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
350     hir: Cx<'a, 'gcx, 'tcx>,
351     cfg: CFG<'tcx>,
352
353     fn_span: Span,
354     arg_count: usize,
355
356     /// the current set of scopes, updated as we traverse;
357     /// see the `scope` module for more details
358     scopes: Vec<scope::Scope<'tcx>>,
359
360     /// the block-context: each time we build the code within an hair::Block,
361     /// we push a frame here tracking whether we are building a statement or
362     /// if we are pushing the tail expression of the block. This is used to
363     /// embed information in generated temps about whether they were created
364     /// for a block tail expression or not.
365     ///
366     /// It would be great if we could fold this into `self.scopes`
367     /// somehow; but right now I think that is very tightly tied to
368     /// the code generation in ways that we cannot (or should not)
369     /// start just throwing new entries onto that vector in order to
370     /// distinguish the context of EXPR1 from the context of EXPR2 in
371     /// `{ STMTS; EXPR1 } + EXPR2`
372     block_context: BlockContext,
373
374     /// The current unsafe block in scope, even if it is hidden by
375     /// a PushUnsafeBlock
376     unpushed_unsafe: Safety,
377
378     /// The number of `push_unsafe_block` levels in scope
379     push_unsafe_count: usize,
380
381     /// the current set of breakables; see the `scope` module for more
382     /// details
383     breakable_scopes: Vec<scope::BreakableScope<'tcx>>,
384
385     /// the vector of all scopes that we have created thus far;
386     /// we track this for debuginfo later
387     source_scopes: IndexVec<SourceScope, SourceScopeData>,
388     source_scope_local_data: IndexVec<SourceScope, SourceScopeLocalData>,
389     source_scope: SourceScope,
390
391     /// the guard-context: each time we build the guard expression for
392     /// a match arm, we push onto this stack, and then pop when we
393     /// finish building it.
394     guard_context: Vec<GuardFrame>,
395
396     /// Maps node ids of variable bindings to the `Local`s created for them.
397     /// (A match binding can have two locals; the 2nd is for the arm's guard.)
398     var_indices: NodeMap<LocalsForNode>,
399     local_decls: IndexVec<Local, LocalDecl<'tcx>>,
400     upvar_decls: Vec<UpvarDecl>,
401     unit_temp: Option<Place<'tcx>>,
402
403     /// cached block with the RESUME terminator; this is created
404     /// when first set of cleanups are built.
405     cached_resume_block: Option<BasicBlock>,
406     /// cached block with the RETURN terminator
407     cached_return_block: Option<BasicBlock>,
408     /// cached block with the UNREACHABLE terminator
409     cached_unreachable_block: Option<BasicBlock>,
410 }
411
412 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
413     fn is_bound_var_in_guard(&self, id: ast::NodeId) -> bool {
414         self.guard_context.iter().any(|frame| frame.locals.iter().any(|local| local.id == id))
415     }
416
417     fn var_local_id(&self, id: ast::NodeId, for_guard: ForGuard) -> Local {
418         self.var_indices[&id].local_id(for_guard)
419     }
420 }
421
422 impl BlockContext {
423     fn new() -> Self { BlockContext(vec![]) }
424     fn push(&mut self, bf: BlockFrame) { self.0.push(bf); }
425     fn pop(&mut self) -> Option<BlockFrame> { self.0.pop() }
426
427     /// Traverses the frames on the BlockContext, searching for either
428     /// the first block-tail expression frame with no intervening
429     /// statement frame.
430     ///
431     /// Notably, this skips over `SubExpr` frames; this method is
432     /// meant to be used in the context of understanding the
433     /// relationship of a temp (created within some complicated
434     /// expression) with its containing expression, and whether the
435     /// value of that *containing expression* (not the temp!) is
436     /// ignored.
437     fn currently_in_block_tail(&self) -> Option<BlockTailInfo> {
438         for bf in self.0.iter().rev() {
439             match bf {
440                 BlockFrame::SubExpr => continue,
441                 BlockFrame::Statement { .. } => break,
442                 &BlockFrame::TailExpr { tail_result_is_ignored } =>
443                     return Some(BlockTailInfo { tail_result_is_ignored })
444             }
445         }
446
447         return None;
448     }
449
450     /// Looks at the topmost frame on the BlockContext and reports
451     /// whether its one that would discard a block tail result.
452     ///
453     /// Unlike `currently_within_ignored_tail_expression`, this does
454     /// *not* skip over `SubExpr` frames: here, we want to know
455     /// whether the block result itself is discarded.
456     fn currently_ignores_tail_results(&self) -> bool {
457         match self.0.last() {
458             // no context: conservatively assume result is read
459             None => false,
460
461             // sub-expression: block result feeds into some computation
462             Some(BlockFrame::SubExpr) => false,
463
464             // otherwise: use accumulated is_ignored state.
465             Some(BlockFrame::TailExpr { tail_result_is_ignored: ignored }) |
466             Some(BlockFrame::Statement { ignores_expr_result: ignored }) => *ignored,
467         }
468     }
469 }
470
471 #[derive(Debug)]
472 enum LocalsForNode {
473     /// In the usual case, a node-id for an identifier maps to at most
474     /// one Local declaration.
475     One(Local),
476
477     /// The exceptional case is identifiers in a match arm's pattern
478     /// that are referenced in a guard of that match arm. For these,
479     /// we can have `2+k` Locals, where `k` is the number of candidate
480     /// patterns (separated by `|`) in the arm.
481     ///
482     /// * `for_arm_body` is the Local used in the arm body (which is
483     ///   just like the `One` case above),
484     ///
485     /// * `ref_for_guard` is the Local used in the arm's guard (which
486     ///   is a reference to a temp that is an alias of
487     ///   `for_arm_body`).
488     ///
489     /// * `vals_for_guard` is the `k` Locals; at most one of them will
490     ///   get initialized by the arm's execution, and after it is
491     ///   initialized, `ref_for_guard` will be assigned a reference to
492     ///   it.
493     ///
494     /// There reason we have `k` Locals rather than just 1 is to
495     /// accommodate some restrictions imposed by two-phase borrows,
496     /// which apply when we have a `ref mut` pattern.
497     ForGuard { vals_for_guard: Vec<Local>, ref_for_guard: Local, for_arm_body: Local },
498 }
499
500 #[derive(Debug)]
501 struct GuardFrameLocal {
502     id: ast::NodeId,
503 }
504
505 impl GuardFrameLocal {
506     fn new(id: ast::NodeId, _binding_mode: BindingMode) -> Self {
507         GuardFrameLocal {
508             id: id,
509         }
510     }
511 }
512
513 #[derive(Debug)]
514 struct GuardFrame {
515     /// These are the id's of names that are bound by patterns of the
516     /// arm of *this* guard.
517     ///
518     /// (Frames higher up the stack will have the id's bound in arms
519     /// further out, such as in a case like:
520     ///
521     /// match E1 {
522     ///      P1(id1) if (... (match E2 { P2(id2) if ... => B2 })) => B1,
523     /// }
524     ///
525     /// here, when building for FIXME
526     locals: Vec<GuardFrameLocal>,
527 }
528
529 /// ForGuard indicates whether we are talking about:
530 ///   1. the temp for a local binding used solely within guard expressions,
531 ///   2. the temp that holds reference to (1.), which is actually what the
532 ///      guard expressions see, or
533 ///   3. the temp for use outside of guard expressions.
534 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
535 enum ForGuard {
536     /// The `usize` identifies for which candidate pattern we want the
537     /// local binding. We keep a temp per-candidate to accommodate
538     /// two-phase borrows (see `LocalsForNode` documentation).
539     ValWithinGuard(usize),
540     RefWithinGuard,
541     OutsideGuard,
542 }
543
544 impl LocalsForNode {
545     fn local_id(&self, for_guard: ForGuard) -> Local {
546         match (self, for_guard) {
547             (&LocalsForNode::One(local_id), ForGuard::OutsideGuard) |
548             (&LocalsForNode::ForGuard { ref_for_guard: local_id, .. }, ForGuard::RefWithinGuard) |
549             (&LocalsForNode::ForGuard { for_arm_body: local_id, .. }, ForGuard::OutsideGuard) =>
550                 local_id,
551
552             (&LocalsForNode::ForGuard { ref vals_for_guard, .. },
553              ForGuard::ValWithinGuard(pat_idx)) =>
554                 vals_for_guard[pat_idx],
555
556             (&LocalsForNode::One(_), ForGuard::ValWithinGuard(_)) |
557             (&LocalsForNode::One(_), ForGuard::RefWithinGuard) =>
558                 bug!("anything with one local should never be within a guard."),
559         }
560     }
561 }
562
563 struct CFG<'tcx> {
564     basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
565 }
566
567 newtype_index! {
568     pub struct ScopeId { .. }
569 }
570
571 ///////////////////////////////////////////////////////////////////////////
572 /// The `BlockAnd` "monad" packages up the new basic block along with a
573 /// produced value (sometimes just unit, of course). The `unpack!`
574 /// macro (and methods below) makes working with `BlockAnd` much more
575 /// convenient.
576
577 #[must_use = "if you don't use one of these results, you're leaving a dangling edge"]
578 struct BlockAnd<T>(BasicBlock, T);
579
580 trait BlockAndExtension {
581     fn and<T>(self, v: T) -> BlockAnd<T>;
582     fn unit(self) -> BlockAnd<()>;
583 }
584
585 impl BlockAndExtension for BasicBlock {
586     fn and<T>(self, v: T) -> BlockAnd<T> {
587         BlockAnd(self, v)
588     }
589
590     fn unit(self) -> BlockAnd<()> {
591         BlockAnd(self, ())
592     }
593 }
594
595 /// Update a block pointer and return the value.
596 /// Use it like `let x = unpack!(block = self.foo(block, foo))`.
597 macro_rules! unpack {
598     ($x:ident = $c:expr) => {
599         {
600             let BlockAnd(b, v) = $c;
601             $x = b;
602             v
603         }
604     };
605
606     ($c:expr) => {
607         {
608             let BlockAnd(b, ()) = $c;
609             b
610         }
611     };
612 }
613
614 fn should_abort_on_panic<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
615                                          fn_def_id: DefId,
616                                          abi: Abi)
617                                          -> bool {
618     // Not callable from C, so we can safely unwind through these
619     if abi == Abi::Rust || abi == Abi::RustCall { return false; }
620
621     // We never unwind, so it's not relevant to stop an unwind
622     if tcx.sess.panic_strategy() != PanicStrategy::Unwind { return false; }
623
624     // We cannot add landing pads, so don't add one
625     if tcx.sess.no_landing_pads() { return false; }
626
627     // This is a special case: some functions have a C abi but are meant to
628     // unwind anyway. Don't stop them.
629     let attrs = &tcx.get_attrs(fn_def_id);
630     match attr::find_unwind_attr(Some(tcx.sess.diagnostic()), attrs) {
631         None => {
632             // FIXME(rust-lang/rust#48251) -- Had to disable
633             // abort-on-panic for backwards compatibility reasons.
634             false
635         }
636
637         Some(UnwindAttr::Allowed) => false,
638         Some(UnwindAttr::Aborts) => true,
639     }
640 }
641
642 ///////////////////////////////////////////////////////////////////////////
643 /// the main entry point for building MIR for a function
644
645 struct ArgInfo<'gcx>(Ty<'gcx>,
646                      Option<Span>,
647                      Option<&'gcx hir::Pat>,
648                      Option<ImplicitSelfKind>);
649
650 fn construct_fn<'a, 'gcx, 'tcx, A>(hir: Cx<'a, 'gcx, 'tcx>,
651                                    fn_id: ast::NodeId,
652                                    arguments: A,
653                                    safety: Safety,
654                                    abi: Abi,
655                                    return_ty: Ty<'gcx>,
656                                    yield_ty: Option<Ty<'gcx>>,
657                                    return_ty_span: Span,
658                                    body: &'gcx hir::Body)
659                                    -> Mir<'tcx>
660     where A: Iterator<Item=ArgInfo<'gcx>>
661 {
662     let arguments: Vec<_> = arguments.collect();
663
664     let tcx = hir.tcx();
665     let span = tcx.hir.span(fn_id);
666
667     // Gather the upvars of a closure, if any.
668     let upvar_decls: Vec<_> = tcx.with_freevars(fn_id, |freevars| {
669         freevars.iter().map(|fv| {
670             let var_id = fv.var_id();
671             let var_hir_id = tcx.hir.node_to_hir_id(var_id);
672             let closure_expr_id = tcx.hir.local_def_id(fn_id);
673             let capture = hir.tables().upvar_capture(ty::UpvarId {
674                 var_path: ty::UpvarPath {hir_id: var_hir_id},
675                 closure_expr_id: LocalDefId::from_def_id(closure_expr_id),
676             });
677             let by_ref = match capture {
678                 ty::UpvarCapture::ByValue => false,
679                 ty::UpvarCapture::ByRef(..) => true
680             };
681             let mut decl = UpvarDecl {
682                 debug_name: keywords::Invalid.name(),
683                 var_hir_id: ClearCrossCrate::Set(var_hir_id),
684                 by_ref,
685                 mutability: Mutability::Not,
686             };
687             if let Some(Node::Binding(pat)) = tcx.hir.find(var_id) {
688                 if let hir::PatKind::Binding(_, _, ident, _) = pat.node {
689                     decl.debug_name = ident.name;
690
691                     if let Some(&bm) = hir.tables.pat_binding_modes().get(pat.hir_id) {
692                         if bm == ty::BindByValue(hir::MutMutable) {
693                             decl.mutability = Mutability::Mut;
694                         } else {
695                             decl.mutability = Mutability::Not;
696                         }
697                     } else {
698                         tcx.sess.delay_span_bug(pat.span, "missing binding mode");
699                     }
700                 }
701             }
702             decl
703         }).collect()
704     });
705
706     let mut builder = Builder::new(hir,
707         span,
708         arguments.len(),
709         safety,
710         return_ty,
711         return_ty_span,
712         upvar_decls);
713
714     let fn_def_id = tcx.hir.local_def_id(fn_id);
715     let call_site_scope = region::Scope {
716         id: body.value.hir_id.local_id,
717         data: region::ScopeData::CallSite
718     };
719     let arg_scope = region::Scope {
720         id: body.value.hir_id.local_id,
721         data: region::ScopeData::Arguments
722     };
723     let mut block = START_BLOCK;
724     let source_info = builder.source_info(span);
725     let call_site_s = (call_site_scope, source_info);
726     unpack!(block = builder.in_scope(call_site_s, LintLevel::Inherited, block, |builder| {
727         if should_abort_on_panic(tcx, fn_def_id, abi) {
728             builder.schedule_abort();
729         }
730
731         let arg_scope_s = (arg_scope, source_info);
732         unpack!(block = builder.in_scope(arg_scope_s, LintLevel::Inherited, block, |builder| {
733             builder.args_and_body(block, &arguments, arg_scope, &body.value)
734         }));
735         // Attribute epilogue to function's closing brace
736         let fn_end = span.shrink_to_hi();
737         let source_info = builder.source_info(fn_end);
738         let return_block = builder.return_block();
739         builder.cfg.terminate(block, source_info,
740                               TerminatorKind::Goto { target: return_block });
741         builder.cfg.terminate(return_block, source_info,
742                               TerminatorKind::Return);
743         // Attribute any unreachable codepaths to the function's closing brace
744         if let Some(unreachable_block) = builder.cached_unreachable_block {
745             builder.cfg.terminate(unreachable_block, source_info,
746                                   TerminatorKind::Unreachable);
747         }
748         return_block.unit()
749     }));
750     assert_eq!(block, builder.return_block());
751
752     let mut spread_arg = None;
753     if abi == Abi::RustCall {
754         // RustCall pseudo-ABI untuples the last argument.
755         spread_arg = Some(Local::new(arguments.len()));
756     }
757     let closure_expr_id = tcx.hir.local_def_id(fn_id);
758     info!("fn_id {:?} has attrs {:?}", closure_expr_id,
759           tcx.get_attrs(closure_expr_id));
760
761     let mut mir = builder.finish(yield_ty);
762     mir.spread_arg = spread_arg;
763     mir
764 }
765
766 fn construct_const<'a, 'gcx, 'tcx>(
767     hir: Cx<'a, 'gcx, 'tcx>,
768     body_id: hir::BodyId,
769     ty_span: Span,
770 ) -> Mir<'tcx> {
771     let tcx = hir.tcx();
772     let ast_expr = &tcx.hir.body(body_id).value;
773     let ty = hir.tables().expr_ty_adjusted(ast_expr);
774     let owner_id = tcx.hir.body_owner(body_id);
775     let span = tcx.hir.span(owner_id);
776     let mut builder = Builder::new(hir, span, 0, Safety::Safe, ty, ty_span,vec![]);
777
778     let mut block = START_BLOCK;
779     let expr = builder.hir.mirror(ast_expr);
780     unpack!(block = builder.into_expr(&Place::Local(RETURN_PLACE), block, expr));
781
782     let source_info = builder.source_info(span);
783     builder.cfg.terminate(block, source_info, TerminatorKind::Return);
784
785     // Constants can't `return` so a return block should not be created.
786     assert_eq!(builder.cached_return_block, None);
787
788     // Constants may be match expressions in which case an unreachable block may
789     // be created, so terminate it properly.
790     if let Some(unreachable_block) = builder.cached_unreachable_block {
791         builder.cfg.terminate(unreachable_block, source_info,
792                               TerminatorKind::Unreachable);
793     }
794
795     builder.finish(None)
796 }
797
798 fn construct_error<'a, 'gcx, 'tcx>(hir: Cx<'a, 'gcx, 'tcx>,
799                                    body_id: hir::BodyId)
800                                    -> Mir<'tcx> {
801     let owner_id = hir.tcx().hir.body_owner(body_id);
802     let span = hir.tcx().hir.span(owner_id);
803     let ty = hir.tcx().types.err;
804     let mut builder = Builder::new(hir, span, 0, Safety::Safe, ty, span, vec![]);
805     let source_info = builder.source_info(span);
806     builder.cfg.terminate(START_BLOCK, source_info, TerminatorKind::Unreachable);
807     builder.finish(None)
808 }
809
810 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
811     fn new(hir: Cx<'a, 'gcx, 'tcx>,
812            span: Span,
813            arg_count: usize,
814            safety: Safety,
815            return_ty: Ty<'tcx>,
816            return_span: Span,
817            upvar_decls: Vec<UpvarDecl>)
818            -> Builder<'a, 'gcx, 'tcx> {
819         let lint_level = LintLevel::Explicit(hir.root_lint_level);
820         let mut builder = Builder {
821             hir,
822             cfg: CFG { basic_blocks: IndexVec::new() },
823             fn_span: span,
824             arg_count,
825             scopes: vec![],
826             block_context: BlockContext::new(),
827             source_scopes: IndexVec::new(),
828             source_scope: OUTERMOST_SOURCE_SCOPE,
829             source_scope_local_data: IndexVec::new(),
830             guard_context: vec![],
831             push_unsafe_count: 0,
832             unpushed_unsafe: safety,
833             breakable_scopes: vec![],
834             local_decls: IndexVec::from_elem_n(
835                 LocalDecl::new_return_place(return_ty, return_span),
836                 1,
837             ),
838             upvar_decls,
839             var_indices: Default::default(),
840             unit_temp: None,
841             cached_resume_block: None,
842             cached_return_block: None,
843             cached_unreachable_block: None,
844         };
845
846         assert_eq!(builder.cfg.start_new_block(), START_BLOCK);
847         assert_eq!(
848             builder.new_source_scope(span, lint_level, Some(safety)),
849             OUTERMOST_SOURCE_SCOPE);
850         builder.source_scopes[OUTERMOST_SOURCE_SCOPE].parent_scope = None;
851
852         builder
853     }
854
855     fn finish(self,
856               yield_ty: Option<Ty<'tcx>>)
857               -> Mir<'tcx> {
858         for (index, block) in self.cfg.basic_blocks.iter().enumerate() {
859             if block.terminator.is_none() {
860                 span_bug!(self.fn_span, "no terminator on block {:?}", index);
861             }
862         }
863
864         Mir::new(self.cfg.basic_blocks,
865                  self.source_scopes,
866                  ClearCrossCrate::Set(self.source_scope_local_data),
867                  IndexVec::new(),
868                  yield_ty,
869                  self.local_decls,
870                  self.arg_count,
871                  self.upvar_decls,
872                  self.fn_span
873         )
874     }
875
876     fn args_and_body(&mut self,
877                      mut block: BasicBlock,
878                      arguments: &[ArgInfo<'gcx>],
879                      argument_scope: region::Scope,
880                      ast_body: &'gcx hir::Expr)
881                      -> BlockAnd<()>
882     {
883         // Allocate locals for the function arguments
884         for &ArgInfo(ty, _, pattern, _) in arguments.iter() {
885             // If this is a simple binding pattern, give the local a name for
886             // debuginfo and so that error reporting knows that this is a user
887             // variable. For any other pattern the pattern introduces new
888             // variables which will be named instead.
889             let mut name = None;
890             if let Some(pat) = pattern {
891                 match pat.node {
892                     hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, ident, _)
893                     | hir::PatKind::Binding(hir::BindingAnnotation::Mutable, _, ident, _) => {
894                         name = Some(ident.name);
895                     }
896                     _ => (),
897                 }
898             }
899
900             let source_info = SourceInfo {
901                 scope: OUTERMOST_SOURCE_SCOPE,
902                 span: pattern.map_or(self.fn_span, |pat| pat.span)
903             };
904             self.local_decls.push(LocalDecl {
905                 mutability: Mutability::Mut,
906                 ty,
907                 user_ty: UserTypeProjections::none(),
908                 source_info,
909                 visibility_scope: source_info.scope,
910                 name,
911                 internal: false,
912                 is_user_variable: None,
913                 is_block_tail: None,
914             });
915         }
916
917         let mut scope = None;
918         // Bind the argument patterns
919         for (index, arg_info) in arguments.iter().enumerate() {
920             // Function arguments always get the first Local indices after the return place
921             let local = Local::new(index + 1);
922             let place = Place::Local(local);
923             let &ArgInfo(ty, opt_ty_info, pattern, ref self_binding) = arg_info;
924
925             if let Some(pattern) = pattern {
926                 let pattern = self.hir.pattern_from_hir(pattern);
927                 let span = pattern.span;
928
929                 match *pattern.kind {
930                     // Don't introduce extra copies for simple bindings
931                     PatternKind::Binding { mutability, var, mode: BindingMode::ByValue, .. } => {
932                         self.local_decls[local].mutability = mutability;
933                         self.local_decls[local].is_user_variable =
934                             if let Some(kind) = self_binding {
935                                 Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf(*kind)))
936                             } else {
937                                 let binding_mode = ty::BindingMode::BindByValue(mutability.into());
938                                 Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
939                                     binding_mode,
940                                     opt_ty_info,
941                                     opt_match_place: Some((Some(place.clone()), span)),
942                                     pat_span: span,
943                                 })))
944                             };
945                         self.var_indices.insert(var, LocalsForNode::One(local));
946                     }
947                     _ => {
948                         scope = self.declare_bindings(scope, ast_body.span,
949                                                       LintLevel::Inherited, &[pattern.clone()],
950                                                       matches::ArmHasGuard(false),
951                                                       Some((Some(&place), span)));
952                         unpack!(block = self.place_into_pattern(block, pattern, &place, false));
953                     }
954                 }
955             }
956
957             // Make sure we drop (parts of) the argument even when not matched on.
958             self.schedule_drop(
959                 pattern.as_ref().map_or(ast_body.span, |pat| pat.span),
960                 argument_scope, &place, ty,
961                 DropKind::Value { cached_block: CachedBlock::default() },
962             );
963         }
964
965         // Enter the argument pattern bindings source scope, if it exists.
966         if let Some(source_scope) = scope {
967             self.source_scope = source_scope;
968         }
969
970         let body = self.hir.mirror(ast_body);
971         self.into(&Place::Local(RETURN_PLACE), block, body)
972     }
973
974     fn get_unit_temp(&mut self) -> Place<'tcx> {
975         match self.unit_temp {
976             Some(ref tmp) => tmp.clone(),
977             None => {
978                 let ty = self.hir.unit_ty();
979                 let fn_span = self.fn_span;
980                 let tmp = self.temp(ty, fn_span);
981                 self.unit_temp = Some(tmp.clone());
982                 tmp
983             }
984         }
985     }
986
987     fn return_block(&mut self) -> BasicBlock {
988         match self.cached_return_block {
989             Some(rb) => rb,
990             None => {
991                 let rb = self.cfg.start_new_block();
992                 self.cached_return_block = Some(rb);
993                 rb
994             }
995         }
996     }
997
998     fn unreachable_block(&mut self) -> BasicBlock {
999         match self.cached_unreachable_block {
1000             Some(ub) => ub,
1001             None => {
1002                 let ub = self.cfg.start_new_block();
1003                 self.cached_unreachable_block = Some(ub);
1004                 ub
1005             }
1006         }
1007     }
1008 }
1009
1010 ///////////////////////////////////////////////////////////////////////////
1011 // Builder methods are broken up into modules, depending on what kind
1012 // of thing is being lowered. Note that they use the `unpack` macro
1013 // above extensively.
1014
1015 mod block;
1016 mod cfg;
1017 mod expr;
1018 mod into;
1019 mod matches;
1020 mod misc;
1021 mod scope;