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