]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/liveness.rs
3db8c746713fd3f7cf64202b28804ba5029cef2e
[rust.git] / src / librustc / middle / liveness.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 //! A classic liveness analysis based on dataflow over the AST.  Computes,
12 //! for each local variable in a function, whether that variable is live
13 //! at a given point.  Program execution points are identified by their
14 //! id.
15 //!
16 //! # Basic idea
17 //!
18 //! The basic model is that each local variable is assigned an index.  We
19 //! represent sets of local variables using a vector indexed by this
20 //! index.  The value in the vector is either 0, indicating the variable
21 //! is dead, or the id of an expression that uses the variable.
22 //!
23 //! We conceptually walk over the AST in reverse execution order.  If we
24 //! find a use of a variable, we add it to the set of live variables.  If
25 //! we find an assignment to a variable, we remove it from the set of live
26 //! variables.  When we have to merge two flows, we take the union of
27 //! those two flows---if the variable is live on both paths, we simply
28 //! pick one id.  In the event of loops, we continue doing this until a
29 //! fixed point is reached.
30 //!
31 //! ## Checking initialization
32 //!
33 //! At the function entry point, all variables must be dead.  If this is
34 //! not the case, we can report an error using the id found in the set of
35 //! live variables, which identifies a use of the variable which is not
36 //! dominated by an assignment.
37 //!
38 //! ## Checking moves
39 //!
40 //! After each explicit move, the variable must be dead.
41 //!
42 //! ## Computing last uses
43 //!
44 //! Any use of the variable where the variable is dead afterwards is a
45 //! last use.
46 //!
47 //! # Implementation details
48 //!
49 //! The actual implementation contains two (nested) walks over the AST.
50 //! The outer walk has the job of building up the ir_maps instance for the
51 //! enclosing function.  On the way down the tree, it identifies those AST
52 //! nodes and variable IDs that will be needed for the liveness analysis
53 //! and assigns them contiguous IDs.  The liveness id for an AST node is
54 //! called a `live_node` (it's a newtype'd usize) and the id for a variable
55 //! is called a `variable` (another newtype'd usize).
56 //!
57 //! On the way back up the tree, as we are about to exit from a function
58 //! declaration we allocate a `liveness` instance.  Now that we know
59 //! precisely how many nodes and variables we need, we can allocate all
60 //! the various arrays that we will need to precisely the right size.  We then
61 //! perform the actual propagation on the `liveness` instance.
62 //!
63 //! This propagation is encoded in the various `propagate_through_*()`
64 //! methods.  It effectively does a reverse walk of the AST; whenever we
65 //! reach a loop node, we iterate until a fixed point is reached.
66 //!
67 //! ## The `Users` struct
68 //!
69 //! At each live node `N`, we track three pieces of information for each
70 //! variable `V` (these are encapsulated in the `Users` struct):
71 //!
72 //! - `reader`: the `LiveNode` ID of some node which will read the value
73 //!    that `V` holds on entry to `N`.  Formally: a node `M` such
74 //!    that there exists a path `P` from `N` to `M` where `P` does not
75 //!    write `V`.  If the `reader` is `invalid_node()`, then the current
76 //!    value will never be read (the variable is dead, essentially).
77 //!
78 //! - `writer`: the `LiveNode` ID of some node which will write the
79 //!    variable `V` and which is reachable from `N`.  Formally: a node `M`
80 //!    such that there exists a path `P` from `N` to `M` and `M` writes
81 //!    `V`.  If the `writer` is `invalid_node()`, then there is no writer
82 //!    of `V` that follows `N`.
83 //!
84 //! - `used`: a boolean value indicating whether `V` is *used*.  We
85 //!   distinguish a *read* from a *use* in that a *use* is some read that
86 //!   is not just used to generate a new value.  For example, `x += 1` is
87 //!   a read but not a use.  This is used to generate better warnings.
88 //!
89 //! ## Special Variables
90 //!
91 //! We generate various special variables for various, well, special purposes.
92 //! These are described in the `specials` struct:
93 //!
94 //! - `exit_ln`: a live node that is generated to represent every 'exit' from
95 //!   the function, whether it be by explicit return, panic, or other means.
96 //!
97 //! - `fallthrough_ln`: a live node that represents a fallthrough
98 //!
99 //! - `clean_exit_var`: a synthetic variable that is only 'read' from the
100 //!   fallthrough node.  It is only live if the function could converge
101 //!   via means other than an explicit `return` expression. That is, it is
102 //!   only dead if the end of the function's block can never be reached.
103 //!   It is the responsibility of typeck to ensure that there are no
104 //!   `return` expressions in a function declared as diverging.
105 use self::LoopKind::*;
106 use self::LiveNodeKind::*;
107 use self::VarKind::*;
108
109 use hir::def::*;
110 use ty::{self, TyCtxt};
111 use lint;
112 use util::nodemap::{NodeMap, NodeSet};
113
114 use std::collections::VecDeque;
115 use std::{fmt, usize};
116 use std::io::prelude::*;
117 use std::io;
118 use std::rc::Rc;
119 use syntax::ast::{self, NodeId};
120 use syntax::ptr::P;
121 use syntax::symbol::keywords;
122 use syntax_pos::Span;
123
124 use hir::Expr;
125 use hir;
126 use hir::intravisit::{self, Visitor, FnKind, NestedVisitorMap};
127
128 /// For use with `propagate_through_loop`.
129 enum LoopKind<'a> {
130     /// An endless `loop` loop.
131     LoopLoop,
132     /// A `while` loop, with the given expression as condition.
133     WhileLoop(&'a Expr),
134 }
135
136 #[derive(Copy, Clone, PartialEq)]
137 struct Variable(usize);
138
139 #[derive(Copy, PartialEq)]
140 struct LiveNode(usize);
141
142 impl Variable {
143     fn get(&self) -> usize { let Variable(v) = *self; v }
144 }
145
146 impl LiveNode {
147     fn get(&self) -> usize { let LiveNode(v) = *self; v }
148 }
149
150 impl Clone for LiveNode {
151     fn clone(&self) -> LiveNode {
152         LiveNode(self.get())
153     }
154 }
155
156 #[derive(Copy, Clone, PartialEq, Debug)]
157 enum LiveNodeKind {
158     FreeVarNode(Span),
159     ExprNode(Span),
160     VarDefNode(Span),
161     ExitNode
162 }
163
164 fn live_node_kind_to_string(lnk: LiveNodeKind, tcx: TyCtxt) -> String {
165     let cm = tcx.sess.codemap();
166     match lnk {
167         FreeVarNode(s) => {
168             format!("Free var node [{}]", cm.span_to_string(s))
169         }
170         ExprNode(s) => {
171             format!("Expr node [{}]", cm.span_to_string(s))
172         }
173         VarDefNode(s) => {
174             format!("Var def node [{}]", cm.span_to_string(s))
175         }
176         ExitNode => "Exit node".to_string(),
177     }
178 }
179
180 impl<'a, 'tcx> Visitor<'tcx> for IrMaps<'a, 'tcx> {
181     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
182         NestedVisitorMap::OnlyBodies(&self.tcx.hir)
183     }
184
185     fn visit_fn(&mut self, fk: FnKind<'tcx>, fd: &'tcx hir::FnDecl,
186                 b: hir::BodyId, s: Span, id: NodeId) {
187         visit_fn(self, fk, fd, b, s, id);
188     }
189
190     fn visit_local(&mut self, l: &'tcx hir::Local) { visit_local(self, l); }
191     fn visit_expr(&mut self, ex: &'tcx Expr) { visit_expr(self, ex); }
192     fn visit_arm(&mut self, a: &'tcx hir::Arm) { visit_arm(self, a); }
193 }
194
195 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
196     tcx.hir.krate().visit_all_item_likes(&mut IrMaps::new(tcx).as_deep_visitor());
197     tcx.sess.abort_if_errors();
198 }
199
200 impl fmt::Debug for LiveNode {
201     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
202         write!(f, "ln({})", self.get())
203     }
204 }
205
206 impl fmt::Debug for Variable {
207     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
208         write!(f, "v({})", self.get())
209     }
210 }
211
212 // ______________________________________________________________________
213 // Creating ir_maps
214 //
215 // This is the first pass and the one that drives the main
216 // computation.  It walks up and down the IR once.  On the way down,
217 // we count for each function the number of variables as well as
218 // liveness nodes.  A liveness node is basically an expression or
219 // capture clause that does something of interest: either it has
220 // interesting control flow or it uses/defines a local variable.
221 //
222 // On the way back up, at each function node we create liveness sets
223 // (we now know precisely how big to make our various vectors and so
224 // forth) and then do the data-flow propagation to compute the set
225 // of live variables at each program point.
226 //
227 // Finally, we run back over the IR one last time and, using the
228 // computed liveness, check various safety conditions.  For example,
229 // there must be no live nodes at the definition site for a variable
230 // unless it has an initializer.  Similarly, each non-mutable local
231 // variable must not be assigned if there is some successor
232 // assignment.  And so forth.
233
234 impl LiveNode {
235     fn is_valid(&self) -> bool {
236         self.get() != usize::MAX
237     }
238 }
239
240 fn invalid_node() -> LiveNode { LiveNode(usize::MAX) }
241
242 struct CaptureInfo {
243     ln: LiveNode,
244     var_nid: NodeId
245 }
246
247 #[derive(Copy, Clone, Debug)]
248 struct LocalInfo {
249     id: NodeId,
250     name: ast::Name,
251     is_shorthand: bool,
252 }
253
254 #[derive(Copy, Clone, Debug)]
255 enum VarKind {
256     Arg(NodeId, ast::Name),
257     Local(LocalInfo),
258     CleanExit
259 }
260
261 struct IrMaps<'a, 'tcx: 'a> {
262     tcx: TyCtxt<'a, 'tcx, 'tcx>,
263
264     num_live_nodes: usize,
265     num_vars: usize,
266     live_node_map: NodeMap<LiveNode>,
267     variable_map: NodeMap<Variable>,
268     capture_info_map: NodeMap<Rc<Vec<CaptureInfo>>>,
269     var_kinds: Vec<VarKind>,
270     lnks: Vec<LiveNodeKind>,
271 }
272
273 impl<'a, 'tcx> IrMaps<'a, 'tcx> {
274     fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> IrMaps<'a, 'tcx> {
275         IrMaps {
276             tcx,
277             num_live_nodes: 0,
278             num_vars: 0,
279             live_node_map: NodeMap(),
280             variable_map: NodeMap(),
281             capture_info_map: NodeMap(),
282             var_kinds: Vec::new(),
283             lnks: Vec::new(),
284         }
285     }
286
287     fn add_live_node(&mut self, lnk: LiveNodeKind) -> LiveNode {
288         let ln = LiveNode(self.num_live_nodes);
289         self.lnks.push(lnk);
290         self.num_live_nodes += 1;
291
292         debug!("{:?} is of kind {}", ln,
293                live_node_kind_to_string(lnk, self.tcx));
294
295         ln
296     }
297
298     fn add_live_node_for_node(&mut self, node_id: NodeId, lnk: LiveNodeKind) {
299         let ln = self.add_live_node(lnk);
300         self.live_node_map.insert(node_id, ln);
301
302         debug!("{:?} is node {}", ln, node_id);
303     }
304
305     fn add_variable(&mut self, vk: VarKind) -> Variable {
306         let v = Variable(self.num_vars);
307         self.var_kinds.push(vk);
308         self.num_vars += 1;
309
310         match vk {
311             Local(LocalInfo { id: node_id, .. }) | Arg(node_id, _) => {
312                 self.variable_map.insert(node_id, v);
313             },
314             CleanExit => {}
315         }
316
317         debug!("{:?} is {:?}", v, vk);
318
319         v
320     }
321
322     fn variable(&self, node_id: NodeId, span: Span) -> Variable {
323         match self.variable_map.get(&node_id) {
324             Some(&var) => var,
325             None => {
326                 span_bug!(span, "no variable registered for id {}", node_id);
327             }
328         }
329     }
330
331     fn variable_name(&self, var: Variable) -> String {
332         match self.var_kinds[var.get()] {
333             Local(LocalInfo { name, .. }) | Arg(_, name) => {
334                 name.to_string()
335             },
336             CleanExit => "<clean-exit>".to_string()
337         }
338     }
339
340     fn variable_is_shorthand(&self, var: Variable) -> bool {
341         match self.var_kinds[var.get()] {
342             Local(LocalInfo { is_shorthand, .. }) => is_shorthand,
343             Arg(..) | CleanExit => false
344         }
345     }
346
347     fn set_captures(&mut self, node_id: NodeId, cs: Vec<CaptureInfo>) {
348         self.capture_info_map.insert(node_id, Rc::new(cs));
349     }
350
351     fn lnk(&self, ln: LiveNode) -> LiveNodeKind {
352         self.lnks[ln.get()]
353     }
354 }
355
356 fn visit_fn<'a, 'tcx: 'a>(ir: &mut IrMaps<'a, 'tcx>,
357                           fk: FnKind<'tcx>,
358                           decl: &'tcx hir::FnDecl,
359                           body_id: hir::BodyId,
360                           sp: Span,
361                           id: ast::NodeId) {
362     debug!("visit_fn");
363
364     // swap in a new set of IR maps for this function body:
365     let mut fn_maps = IrMaps::new(ir.tcx);
366
367     // Don't run unused pass for #[derive()]
368     if let FnKind::Method(..) = fk {
369         let parent = ir.tcx.hir.get_parent(id);
370         if let Some(hir::map::Node::NodeItem(i)) = ir.tcx.hir.find(parent) {
371             if i.attrs.iter().any(|a| a.check_name("automatically_derived")) {
372                 return;
373             }
374         }
375     }
376
377     debug!("creating fn_maps: {:?}", &fn_maps as *const IrMaps);
378
379     let body = ir.tcx.hir.body(body_id);
380
381     for arg in &body.arguments {
382         arg.pat.each_binding(|_bm, arg_id, _x, path1| {
383             debug!("adding argument {}", arg_id);
384             let name = path1.node;
385             fn_maps.add_variable(Arg(arg_id, name));
386         })
387     };
388
389     // gather up the various local variables, significant expressions,
390     // and so forth:
391     intravisit::walk_fn(&mut fn_maps, fk, decl, body_id, sp, id);
392
393     // compute liveness
394     let mut lsets = Liveness::new(&mut fn_maps, body_id);
395     let entry_ln = lsets.compute(&body.value);
396
397     // check for various error conditions
398     lsets.visit_body(body);
399     lsets.warn_about_unused_args(body, entry_ln);
400 }
401
402 fn add_from_pat<'a, 'tcx>(ir: &mut IrMaps<'a, 'tcx>, pat: &P<hir::Pat>) {
403     // For struct patterns, take note of which fields used shorthand
404     // (`x` rather than `x: x`).
405     //
406     // FIXME: according to the rust-lang-nursery/rustc-guide book, `NodeId`s are to be
407     // phased out in favor of `HirId`s; however, we need to match the signature of
408     // `each_binding`, which uses `NodeIds`.
409     let mut shorthand_field_ids = NodeSet();
410     let mut pats = VecDeque::new();
411     pats.push_back(pat);
412     while let Some(pat) = pats.pop_front() {
413         use hir::PatKind::*;
414         match pat.node {
415             Binding(_, _, _, ref inner_pat) => {
416                 pats.extend(inner_pat.iter());
417             }
418             Struct(_, ref fields, _) => {
419                 for field in fields {
420                     if field.node.is_shorthand {
421                         shorthand_field_ids.insert(field.node.pat.id);
422                     }
423                 }
424             }
425             Ref(ref inner_pat, _) |
426             Box(ref inner_pat) => {
427                 pats.push_back(inner_pat);
428             }
429             TupleStruct(_, ref inner_pats, _) |
430             Tuple(ref inner_pats, _) => {
431                 pats.extend(inner_pats.iter());
432             }
433             Slice(ref pre_pats, ref inner_pat, ref post_pats) => {
434                 pats.extend(pre_pats.iter());
435                 pats.extend(inner_pat.iter());
436                 pats.extend(post_pats.iter());
437             }
438             _ => {}
439         }
440     }
441
442     pat.each_binding(|_bm, p_id, _sp, path1| {
443         let name = path1.node;
444         ir.add_live_node_for_node(p_id, VarDefNode(path1.span));
445         ir.add_variable(Local(LocalInfo {
446             id: p_id,
447             name,
448             is_shorthand: shorthand_field_ids.contains(&p_id)
449         }));
450     });
451 }
452
453 fn visit_local<'a, 'tcx>(ir: &mut IrMaps<'a, 'tcx>, local: &'tcx hir::Local) {
454     add_from_pat(ir, &local.pat);
455     intravisit::walk_local(ir, local);
456 }
457
458 fn visit_arm<'a, 'tcx>(ir: &mut IrMaps<'a, 'tcx>, arm: &'tcx hir::Arm) {
459     for pat in &arm.pats {
460         add_from_pat(ir, pat);
461     }
462     intravisit::walk_arm(ir, arm);
463 }
464
465 fn visit_expr<'a, 'tcx>(ir: &mut IrMaps<'a, 'tcx>, expr: &'tcx Expr) {
466     match expr.node {
467       // live nodes required for uses or definitions of variables:
468       hir::ExprPath(hir::QPath::Resolved(_, ref path)) => {
469         debug!("expr {}: path that leads to {:?}", expr.id, path.def);
470         if let Def::Local(..) = path.def {
471             ir.add_live_node_for_node(expr.id, ExprNode(expr.span));
472         }
473         intravisit::walk_expr(ir, expr);
474       }
475       hir::ExprClosure(..) => {
476         // Interesting control flow (for loops can contain labeled
477         // breaks or continues)
478         ir.add_live_node_for_node(expr.id, ExprNode(expr.span));
479
480         // Make a live_node for each captured variable, with the span
481         // being the location that the variable is used.  This results
482         // in better error messages than just pointing at the closure
483         // construction site.
484         let mut call_caps = Vec::new();
485         ir.tcx.with_freevars(expr.id, |freevars| {
486             for fv in freevars {
487                 if let Def::Local(rv) = fv.def {
488                     let fv_ln = ir.add_live_node(FreeVarNode(fv.span));
489                     call_caps.push(CaptureInfo {ln: fv_ln,
490                                                 var_nid: rv});
491                 }
492             }
493         });
494         ir.set_captures(expr.id, call_caps);
495
496         intravisit::walk_expr(ir, expr);
497       }
498
499       // live nodes required for interesting control flow:
500       hir::ExprIf(..) | hir::ExprMatch(..) | hir::ExprWhile(..) | hir::ExprLoop(..) => {
501         ir.add_live_node_for_node(expr.id, ExprNode(expr.span));
502         intravisit::walk_expr(ir, expr);
503       }
504       hir::ExprBinary(op, ..) if op.node.is_lazy() => {
505         ir.add_live_node_for_node(expr.id, ExprNode(expr.span));
506         intravisit::walk_expr(ir, expr);
507       }
508
509       // otherwise, live nodes are not required:
510       hir::ExprIndex(..) | hir::ExprField(..) |
511       hir::ExprArray(..) | hir::ExprCall(..) | hir::ExprMethodCall(..) |
512       hir::ExprTup(..) | hir::ExprBinary(..) | hir::ExprAddrOf(..) |
513       hir::ExprCast(..) | hir::ExprUnary(..) | hir::ExprBreak(..) |
514       hir::ExprAgain(_) | hir::ExprLit(_) | hir::ExprRet(..) |
515       hir::ExprBlock(..) | hir::ExprAssign(..) | hir::ExprAssignOp(..) |
516       hir::ExprStruct(..) | hir::ExprRepeat(..) |
517       hir::ExprInlineAsm(..) | hir::ExprBox(..) | hir::ExprYield(..) |
518       hir::ExprType(..) | hir::ExprPath(hir::QPath::TypeRelative(..)) => {
519           intravisit::walk_expr(ir, expr);
520       }
521     }
522 }
523
524 // ______________________________________________________________________
525 // Computing liveness sets
526 //
527 // Actually we compute just a bit more than just liveness, but we use
528 // the same basic propagation framework in all cases.
529
530 #[derive(Clone, Copy)]
531 struct Users {
532     reader: LiveNode,
533     writer: LiveNode,
534     used: bool
535 }
536
537 fn invalid_users() -> Users {
538     Users {
539         reader: invalid_node(),
540         writer: invalid_node(),
541         used: false
542     }
543 }
544
545 #[derive(Copy, Clone)]
546 struct Specials {
547     exit_ln: LiveNode,
548     fallthrough_ln: LiveNode,
549     clean_exit_var: Variable
550 }
551
552 const ACC_READ: u32 = 1;
553 const ACC_WRITE: u32 = 2;
554 const ACC_USE: u32 = 4;
555
556 struct Liveness<'a, 'tcx: 'a> {
557     ir: &'a mut IrMaps<'a, 'tcx>,
558     tables: &'a ty::TypeckTables<'tcx>,
559     s: Specials,
560     successors: Vec<LiveNode>,
561     users: Vec<Users>,
562
563     // mappings from loop node ID to LiveNode
564     // ("break" label should map to loop node ID,
565     // it probably doesn't now)
566     break_ln: NodeMap<LiveNode>,
567     cont_ln: NodeMap<LiveNode>,
568 }
569
570 impl<'a, 'tcx> Liveness<'a, 'tcx> {
571     fn new(ir: &'a mut IrMaps<'a, 'tcx>, body: hir::BodyId) -> Liveness<'a, 'tcx> {
572         // Special nodes and variables:
573         // - exit_ln represents the end of the fn, either by return or panic
574         // - implicit_ret_var is a pseudo-variable that represents
575         //   an implicit return
576         let specials = Specials {
577             exit_ln: ir.add_live_node(ExitNode),
578             fallthrough_ln: ir.add_live_node(ExitNode),
579             clean_exit_var: ir.add_variable(CleanExit)
580         };
581
582         let tables = ir.tcx.body_tables(body);
583
584         let num_live_nodes = ir.num_live_nodes;
585         let num_vars = ir.num_vars;
586
587         Liveness {
588             ir,
589             tables,
590             s: specials,
591             successors: vec![invalid_node(); num_live_nodes],
592             users: vec![invalid_users(); num_live_nodes * num_vars],
593             break_ln: NodeMap(),
594             cont_ln: NodeMap(),
595         }
596     }
597
598     fn live_node(&self, node_id: NodeId, span: Span) -> LiveNode {
599         match self.ir.live_node_map.get(&node_id) {
600           Some(&ln) => ln,
601           None => {
602             // This must be a mismatch between the ir_map construction
603             // above and the propagation code below; the two sets of
604             // code have to agree about which AST nodes are worth
605             // creating liveness nodes for.
606             span_bug!(
607                 span,
608                 "no live node registered for node {}",
609                 node_id);
610           }
611         }
612     }
613
614     fn variable(&self, node_id: NodeId, span: Span) -> Variable {
615         self.ir.variable(node_id, span)
616     }
617
618     fn pat_bindings<F>(&mut self, pat: &hir::Pat, mut f: F) where
619         F: FnMut(&mut Liveness<'a, 'tcx>, LiveNode, Variable, Span, NodeId),
620     {
621         pat.each_binding(|_bm, p_id, sp, n| {
622             let ln = self.live_node(p_id, sp);
623             let var = self.variable(p_id, n.span);
624             f(self, ln, var, n.span, p_id);
625         })
626     }
627
628     fn arm_pats_bindings<F>(&mut self, pat: Option<&hir::Pat>, f: F) where
629         F: FnMut(&mut Liveness<'a, 'tcx>, LiveNode, Variable, Span, NodeId),
630     {
631         if let Some(pat) = pat {
632             self.pat_bindings(pat, f);
633         }
634     }
635
636     fn define_bindings_in_pat(&mut self, pat: &hir::Pat, succ: LiveNode)
637                               -> LiveNode {
638         self.define_bindings_in_arm_pats(Some(pat), succ)
639     }
640
641     fn define_bindings_in_arm_pats(&mut self, pat: Option<&hir::Pat>, succ: LiveNode)
642                                    -> LiveNode {
643         let mut succ = succ;
644         self.arm_pats_bindings(pat, |this, ln, var, _sp, _id| {
645             this.init_from_succ(ln, succ);
646             this.define(ln, var);
647             succ = ln;
648         });
649         succ
650     }
651
652     fn idx(&self, ln: LiveNode, var: Variable) -> usize {
653         ln.get() * self.ir.num_vars + var.get()
654     }
655
656     fn live_on_entry(&self, ln: LiveNode, var: Variable)
657                       -> Option<LiveNodeKind> {
658         assert!(ln.is_valid());
659         let reader = self.users[self.idx(ln, var)].reader;
660         if reader.is_valid() {Some(self.ir.lnk(reader))} else {None}
661     }
662
663     /*
664     Is this variable live on entry to any of its successor nodes?
665     */
666     fn live_on_exit(&self, ln: LiveNode, var: Variable)
667                     -> Option<LiveNodeKind> {
668         let successor = self.successors[ln.get()];
669         self.live_on_entry(successor, var)
670     }
671
672     fn used_on_entry(&self, ln: LiveNode, var: Variable) -> bool {
673         assert!(ln.is_valid());
674         self.users[self.idx(ln, var)].used
675     }
676
677     fn assigned_on_entry(&self, ln: LiveNode, var: Variable)
678                          -> Option<LiveNodeKind> {
679         assert!(ln.is_valid());
680         let writer = self.users[self.idx(ln, var)].writer;
681         if writer.is_valid() {Some(self.ir.lnk(writer))} else {None}
682     }
683
684     fn assigned_on_exit(&self, ln: LiveNode, var: Variable)
685                         -> Option<LiveNodeKind> {
686         let successor = self.successors[ln.get()];
687         self.assigned_on_entry(successor, var)
688     }
689
690     fn indices2<F>(&mut self, ln: LiveNode, succ_ln: LiveNode, mut op: F) where
691         F: FnMut(&mut Liveness<'a, 'tcx>, usize, usize),
692     {
693         let node_base_idx = self.idx(ln, Variable(0));
694         let succ_base_idx = self.idx(succ_ln, Variable(0));
695         for var_idx in 0..self.ir.num_vars {
696             op(self, node_base_idx + var_idx, succ_base_idx + var_idx);
697         }
698     }
699
700     fn write_vars<F>(&self,
701                      wr: &mut dyn Write,
702                      ln: LiveNode,
703                      mut test: F)
704                      -> io::Result<()> where
705         F: FnMut(usize) -> LiveNode,
706     {
707         let node_base_idx = self.idx(ln, Variable(0));
708         for var_idx in 0..self.ir.num_vars {
709             let idx = node_base_idx + var_idx;
710             if test(idx).is_valid() {
711                 write!(wr, " {:?}", Variable(var_idx))?;
712             }
713         }
714         Ok(())
715     }
716
717
718     #[allow(unused_must_use)]
719     fn ln_str(&self, ln: LiveNode) -> String {
720         let mut wr = Vec::new();
721         {
722             let wr = &mut wr as &mut dyn Write;
723             write!(wr, "[ln({:?}) of kind {:?} reads", ln.get(), self.ir.lnk(ln));
724             self.write_vars(wr, ln, |idx| self.users[idx].reader);
725             write!(wr, "  writes");
726             self.write_vars(wr, ln, |idx| self.users[idx].writer);
727             write!(wr, "  precedes {:?}]", self.successors[ln.get()]);
728         }
729         String::from_utf8(wr).unwrap()
730     }
731
732     fn init_empty(&mut self, ln: LiveNode, succ_ln: LiveNode) {
733         self.successors[ln.get()] = succ_ln;
734
735         // It is not necessary to initialize the
736         // values to empty because this is the value
737         // they have when they are created, and the sets
738         // only grow during iterations.
739         //
740         // self.indices(ln) { |idx|
741         //     self.users[idx] = invalid_users();
742         // }
743     }
744
745     fn init_from_succ(&mut self, ln: LiveNode, succ_ln: LiveNode) {
746         // more efficient version of init_empty() / merge_from_succ()
747         self.successors[ln.get()] = succ_ln;
748
749         self.indices2(ln, succ_ln, |this, idx, succ_idx| {
750             this.users[idx] = this.users[succ_idx]
751         });
752         debug!("init_from_succ(ln={}, succ={})",
753                self.ln_str(ln), self.ln_str(succ_ln));
754     }
755
756     fn merge_from_succ(&mut self,
757                        ln: LiveNode,
758                        succ_ln: LiveNode,
759                        first_merge: bool)
760                        -> bool {
761         if ln == succ_ln { return false; }
762
763         let mut changed = false;
764         self.indices2(ln, succ_ln, |this, idx, succ_idx| {
765             changed |= copy_if_invalid(this.users[succ_idx].reader,
766                                        &mut this.users[idx].reader);
767             changed |= copy_if_invalid(this.users[succ_idx].writer,
768                                        &mut this.users[idx].writer);
769             if this.users[succ_idx].used && !this.users[idx].used {
770                 this.users[idx].used = true;
771                 changed = true;
772             }
773         });
774
775         debug!("merge_from_succ(ln={:?}, succ={}, first_merge={}, changed={})",
776                ln, self.ln_str(succ_ln), first_merge, changed);
777         return changed;
778
779         fn copy_if_invalid(src: LiveNode, dst: &mut LiveNode) -> bool {
780             if src.is_valid() && !dst.is_valid() {
781                 *dst = src;
782                 true
783             } else {
784                 false
785             }
786         }
787     }
788
789     // Indicates that a local variable was *defined*; we know that no
790     // uses of the variable can precede the definition (resolve checks
791     // this) so we just clear out all the data.
792     fn define(&mut self, writer: LiveNode, var: Variable) {
793         let idx = self.idx(writer, var);
794         self.users[idx].reader = invalid_node();
795         self.users[idx].writer = invalid_node();
796
797         debug!("{:?} defines {:?} (idx={}): {}", writer, var,
798                idx, self.ln_str(writer));
799     }
800
801     // Either read, write, or both depending on the acc bitset
802     fn acc(&mut self, ln: LiveNode, var: Variable, acc: u32) {
803         debug!("{:?} accesses[{:x}] {:?}: {}",
804                ln, acc, var, self.ln_str(ln));
805
806         let idx = self.idx(ln, var);
807         let user = &mut self.users[idx];
808
809         if (acc & ACC_WRITE) != 0 {
810             user.reader = invalid_node();
811             user.writer = ln;
812         }
813
814         // Important: if we both read/write, must do read second
815         // or else the write will override.
816         if (acc & ACC_READ) != 0 {
817             user.reader = ln;
818         }
819
820         if (acc & ACC_USE) != 0 {
821             user.used = true;
822         }
823     }
824
825     // _______________________________________________________________________
826
827     fn compute(&mut self, body: &hir::Expr) -> LiveNode {
828         // if there is a `break` or `again` at the top level, then it's
829         // effectively a return---this only occurs in `for` loops,
830         // where the body is really a closure.
831
832         debug!("compute: using id for body, {}", self.ir.tcx.hir.node_to_pretty_string(body.id));
833
834         let exit_ln = self.s.exit_ln;
835
836         self.break_ln.insert(body.id, exit_ln);
837         self.cont_ln.insert(body.id, exit_ln);
838
839         // the fallthrough exit is only for those cases where we do not
840         // explicitly return:
841         let s = self.s;
842         self.init_from_succ(s.fallthrough_ln, s.exit_ln);
843         self.acc(s.fallthrough_ln, s.clean_exit_var, ACC_READ);
844
845         let entry_ln = self.propagate_through_expr(body, s.fallthrough_ln);
846
847         // hack to skip the loop unless debug! is enabled:
848         debug!("^^ liveness computation results for body {} (entry={:?})",
849                {
850                    for ln_idx in 0..self.ir.num_live_nodes {
851                        debug!("{:?}", self.ln_str(LiveNode(ln_idx)));
852                    }
853                    body.id
854                },
855                entry_ln);
856
857         entry_ln
858     }
859
860     fn propagate_through_block(&mut self, blk: &hir::Block, succ: LiveNode)
861                                -> LiveNode {
862         if blk.targeted_by_break {
863             self.break_ln.insert(blk.id, succ);
864         }
865         let succ = self.propagate_through_opt_expr(blk.expr.as_ref().map(|e| &**e), succ);
866         blk.stmts.iter().rev().fold(succ, |succ, stmt| {
867             self.propagate_through_stmt(stmt, succ)
868         })
869     }
870
871     fn propagate_through_stmt(&mut self, stmt: &hir::Stmt, succ: LiveNode)
872                               -> LiveNode {
873         match stmt.node {
874             hir::StmtDecl(ref decl, _) => {
875                 self.propagate_through_decl(&decl, succ)
876             }
877
878             hir::StmtExpr(ref expr, _) | hir::StmtSemi(ref expr, _) => {
879                 self.propagate_through_expr(&expr, succ)
880             }
881         }
882     }
883
884     fn propagate_through_decl(&mut self, decl: &hir::Decl, succ: LiveNode)
885                               -> LiveNode {
886         match decl.node {
887             hir::DeclLocal(ref local) => {
888                 self.propagate_through_local(&local, succ)
889             }
890             hir::DeclItem(_) => succ,
891         }
892     }
893
894     fn propagate_through_local(&mut self, local: &hir::Local, succ: LiveNode)
895                                -> LiveNode {
896         // Note: we mark the variable as defined regardless of whether
897         // there is an initializer.  Initially I had thought to only mark
898         // the live variable as defined if it was initialized, and then we
899         // could check for uninit variables just by scanning what is live
900         // at the start of the function. But that doesn't work so well for
901         // immutable variables defined in a loop:
902         //     loop { let x; x = 5; }
903         // because the "assignment" loops back around and generates an error.
904         //
905         // So now we just check that variables defined w/o an
906         // initializer are not live at the point of their
907         // initialization, which is mildly more complex than checking
908         // once at the func header but otherwise equivalent.
909
910         let succ = self.propagate_through_opt_expr(local.init.as_ref().map(|e| &**e), succ);
911         self.define_bindings_in_pat(&local.pat, succ)
912     }
913
914     fn propagate_through_exprs(&mut self, exprs: &[Expr], succ: LiveNode)
915                                -> LiveNode {
916         exprs.iter().rev().fold(succ, |succ, expr| {
917             self.propagate_through_expr(&expr, succ)
918         })
919     }
920
921     fn propagate_through_opt_expr(&mut self,
922                                   opt_expr: Option<&Expr>,
923                                   succ: LiveNode)
924                                   -> LiveNode {
925         opt_expr.map_or(succ, |expr| self.propagate_through_expr(expr, succ))
926     }
927
928     fn propagate_through_expr(&mut self, expr: &Expr, succ: LiveNode)
929                               -> LiveNode {
930         debug!("propagate_through_expr: {}", self.ir.tcx.hir.node_to_pretty_string(expr.id));
931
932         match expr.node {
933           // Interesting cases with control flow or which gen/kill
934           hir::ExprPath(hir::QPath::Resolved(_, ref path)) => {
935               self.access_path(expr.id, path, succ, ACC_READ | ACC_USE)
936           }
937
938           hir::ExprField(ref e, _) => {
939               self.propagate_through_expr(&e, succ)
940           }
941
942           hir::ExprClosure(.., blk_id, _, _) => {
943               debug!("{} is an ExprClosure", self.ir.tcx.hir.node_to_pretty_string(expr.id));
944
945               /*
946               The next-node for a break is the successor of the entire
947               loop. The next-node for a continue is the top of this loop.
948               */
949               let node = self.live_node(expr.id, expr.span);
950
951               let break_ln = succ;
952               let cont_ln = node;
953               self.break_ln.insert(blk_id.node_id, break_ln);
954               self.cont_ln.insert(blk_id.node_id, cont_ln);
955
956               // the construction of a closure itself is not important,
957               // but we have to consider the closed over variables.
958               let caps = match self.ir.capture_info_map.get(&expr.id) {
959                   Some(caps) => caps.clone(),
960                   None => {
961                       span_bug!(expr.span, "no registered caps");
962                   }
963               };
964               caps.iter().rev().fold(succ, |succ, cap| {
965                   self.init_from_succ(cap.ln, succ);
966                   let var = self.variable(cap.var_nid, expr.span);
967                   self.acc(cap.ln, var, ACC_READ | ACC_USE);
968                   cap.ln
969               })
970           }
971
972           hir::ExprIf(ref cond, ref then, ref els) => {
973             //
974             //     (cond)
975             //       |
976             //       v
977             //     (expr)
978             //     /   \
979             //    |     |
980             //    v     v
981             //  (then)(els)
982             //    |     |
983             //    v     v
984             //   (  succ  )
985             //
986             let else_ln = self.propagate_through_opt_expr(els.as_ref().map(|e| &**e), succ);
987             let then_ln = self.propagate_through_expr(&then, succ);
988             let ln = self.live_node(expr.id, expr.span);
989             self.init_from_succ(ln, else_ln);
990             self.merge_from_succ(ln, then_ln, false);
991             self.propagate_through_expr(&cond, ln)
992           }
993
994           hir::ExprWhile(ref cond, ref blk, _) => {
995             self.propagate_through_loop(expr, WhileLoop(&cond), &blk, succ)
996           }
997
998           // Note that labels have been resolved, so we don't need to look
999           // at the label ident
1000           hir::ExprLoop(ref blk, _, _) => {
1001             self.propagate_through_loop(expr, LoopLoop, &blk, succ)
1002           }
1003
1004           hir::ExprMatch(ref e, ref arms, _) => {
1005             //
1006             //      (e)
1007             //       |
1008             //       v
1009             //     (expr)
1010             //     / | \
1011             //    |  |  |
1012             //    v  v  v
1013             //   (..arms..)
1014             //    |  |  |
1015             //    v  v  v
1016             //   (  succ  )
1017             //
1018             //
1019             let ln = self.live_node(expr.id, expr.span);
1020             self.init_empty(ln, succ);
1021             let mut first_merge = true;
1022             for arm in arms {
1023                 let body_succ =
1024                     self.propagate_through_expr(&arm.body, succ);
1025                 let guard_succ =
1026                     self.propagate_through_opt_expr(arm.guard.as_ref().map(|e| &**e), body_succ);
1027                 // only consider the first pattern; any later patterns must have
1028                 // the same bindings, and we also consider the first pattern to be
1029                 // the "authoritative" set of ids
1030                 let arm_succ =
1031                     self.define_bindings_in_arm_pats(arm.pats.first().map(|p| &**p),
1032                                                      guard_succ);
1033                 self.merge_from_succ(ln, arm_succ, first_merge);
1034                 first_merge = false;
1035             };
1036             self.propagate_through_expr(&e, ln)
1037           }
1038
1039           hir::ExprRet(ref o_e) => {
1040             // ignore succ and subst exit_ln:
1041             let exit_ln = self.s.exit_ln;
1042             self.propagate_through_opt_expr(o_e.as_ref().map(|e| &**e), exit_ln)
1043           }
1044
1045           hir::ExprBreak(label, ref opt_expr) => {
1046               // Find which label this break jumps to
1047               let target = match label.target_id {
1048                     Ok(node_id) => self.break_ln.get(&node_id),
1049                     Err(err) => span_bug!(expr.span, "loop scope error: {}", err),
1050               }.map(|x| *x);
1051
1052               // Now that we know the label we're going to,
1053               // look it up in the break loop nodes table
1054
1055               match target {
1056                   Some(b) => self.propagate_through_opt_expr(opt_expr.as_ref().map(|e| &**e), b),
1057                   None => span_bug!(expr.span, "break to unknown label")
1058               }
1059           }
1060
1061           hir::ExprAgain(label) => {
1062               // Find which label this expr continues to
1063               let sc = match label.target_id {
1064                     Ok(node_id) => node_id,
1065                     Err(err) => span_bug!(expr.span, "loop scope error: {}", err),
1066               };
1067
1068               // Now that we know the label we're going to,
1069               // look it up in the continue loop nodes table
1070
1071               match self.cont_ln.get(&sc) {
1072                   Some(&b) => b,
1073                   None => span_bug!(expr.span, "continue to unknown label")
1074               }
1075           }
1076
1077           hir::ExprAssign(ref l, ref r) => {
1078             // see comment on places in
1079             // propagate_through_place_components()
1080             let succ = self.write_place(&l, succ, ACC_WRITE);
1081             let succ = self.propagate_through_place_components(&l, succ);
1082             self.propagate_through_expr(&r, succ)
1083           }
1084
1085           hir::ExprAssignOp(_, ref l, ref r) => {
1086             // an overloaded assign op is like a method call
1087             if self.tables.is_method_call(expr) {
1088                 let succ = self.propagate_through_expr(&l, succ);
1089                 self.propagate_through_expr(&r, succ)
1090             } else {
1091                 // see comment on places in
1092                 // propagate_through_place_components()
1093                 let succ = self.write_place(&l, succ, ACC_WRITE|ACC_READ);
1094                 let succ = self.propagate_through_expr(&r, succ);
1095                 self.propagate_through_place_components(&l, succ)
1096             }
1097           }
1098
1099           // Uninteresting cases: just propagate in rev exec order
1100
1101           hir::ExprArray(ref exprs) => {
1102             self.propagate_through_exprs(exprs, succ)
1103           }
1104
1105           hir::ExprStruct(_, ref fields, ref with_expr) => {
1106             let succ = self.propagate_through_opt_expr(with_expr.as_ref().map(|e| &**e), succ);
1107             fields.iter().rev().fold(succ, |succ, field| {
1108                 self.propagate_through_expr(&field.expr, succ)
1109             })
1110           }
1111
1112           hir::ExprCall(ref f, ref args) => {
1113             // FIXME(canndrew): This is_never should really be an is_uninhabited
1114             let succ = if self.tables.expr_ty(expr).is_never() {
1115                 self.s.exit_ln
1116             } else {
1117                 succ
1118             };
1119             let succ = self.propagate_through_exprs(args, succ);
1120             self.propagate_through_expr(&f, succ)
1121           }
1122
1123           hir::ExprMethodCall(.., ref args) => {
1124             // FIXME(canndrew): This is_never should really be an is_uninhabited
1125             let succ = if self.tables.expr_ty(expr).is_never() {
1126                 self.s.exit_ln
1127             } else {
1128                 succ
1129             };
1130             self.propagate_through_exprs(args, succ)
1131           }
1132
1133           hir::ExprTup(ref exprs) => {
1134             self.propagate_through_exprs(exprs, succ)
1135           }
1136
1137           hir::ExprBinary(op, ref l, ref r) if op.node.is_lazy() => {
1138             let r_succ = self.propagate_through_expr(&r, succ);
1139
1140             let ln = self.live_node(expr.id, expr.span);
1141             self.init_from_succ(ln, succ);
1142             self.merge_from_succ(ln, r_succ, false);
1143
1144             self.propagate_through_expr(&l, ln)
1145           }
1146
1147           hir::ExprIndex(ref l, ref r) |
1148           hir::ExprBinary(_, ref l, ref r) => {
1149             let r_succ = self.propagate_through_expr(&r, succ);
1150             self.propagate_through_expr(&l, r_succ)
1151           }
1152
1153           hir::ExprBox(ref e) |
1154           hir::ExprAddrOf(_, ref e) |
1155           hir::ExprCast(ref e, _) |
1156           hir::ExprType(ref e, _) |
1157           hir::ExprUnary(_, ref e) |
1158           hir::ExprYield(ref e) |
1159           hir::ExprRepeat(ref e, _) => {
1160             self.propagate_through_expr(&e, succ)
1161           }
1162
1163           hir::ExprInlineAsm(ref ia, ref outputs, ref inputs) => {
1164             let succ = ia.outputs.iter().zip(outputs).rev().fold(succ, |succ, (o, output)| {
1165                 // see comment on places
1166                 // in propagate_through_place_components()
1167                 if o.is_indirect {
1168                     self.propagate_through_expr(output, succ)
1169                 } else {
1170                     let acc = if o.is_rw { ACC_WRITE|ACC_READ } else { ACC_WRITE };
1171                     let succ = self.write_place(output, succ, acc);
1172                     self.propagate_through_place_components(output, succ)
1173                 }
1174             });
1175
1176             // Inputs are executed first. Propagate last because of rev order
1177             self.propagate_through_exprs(inputs, succ)
1178           }
1179
1180           hir::ExprLit(..) | hir::ExprPath(hir::QPath::TypeRelative(..)) => {
1181             succ
1182           }
1183
1184           // Note that labels have been resolved, so we don't need to look
1185           // at the label ident
1186           hir::ExprBlock(ref blk, _) => {
1187             self.propagate_through_block(&blk, succ)
1188           }
1189         }
1190     }
1191
1192     fn propagate_through_place_components(&mut self,
1193                                            expr: &Expr,
1194                                            succ: LiveNode)
1195                                            -> LiveNode {
1196         // # Places
1197         //
1198         // In general, the full flow graph structure for an
1199         // assignment/move/etc can be handled in one of two ways,
1200         // depending on whether what is being assigned is a "tracked
1201         // value" or not. A tracked value is basically a local
1202         // variable or argument.
1203         //
1204         // The two kinds of graphs are:
1205         //
1206         //    Tracked place          Untracked place
1207         // ----------------------++-----------------------
1208         //                       ||
1209         //         |             ||           |
1210         //         v             ||           v
1211         //     (rvalue)          ||       (rvalue)
1212         //         |             ||           |
1213         //         v             ||           v
1214         // (write of place)     ||   (place components)
1215         //         |             ||           |
1216         //         v             ||           v
1217         //      (succ)           ||        (succ)
1218         //                       ||
1219         // ----------------------++-----------------------
1220         //
1221         // I will cover the two cases in turn:
1222         //
1223         // # Tracked places
1224         //
1225         // A tracked place is a local variable/argument `x`.  In
1226         // these cases, the link_node where the write occurs is linked
1227         // to node id of `x`.  The `write_place()` routine generates
1228         // the contents of this node.  There are no subcomponents to
1229         // consider.
1230         //
1231         // # Non-tracked places
1232         //
1233         // These are places like `x[5]` or `x.f`.  In that case, we
1234         // basically ignore the value which is written to but generate
1235         // reads for the components---`x` in these two examples.  The
1236         // components reads are generated by
1237         // `propagate_through_place_components()` (this fn).
1238         //
1239         // # Illegal places
1240         //
1241         // It is still possible to observe assignments to non-places;
1242         // these errors are detected in the later pass borrowck.  We
1243         // just ignore such cases and treat them as reads.
1244
1245         match expr.node {
1246             hir::ExprPath(_) => succ,
1247             hir::ExprField(ref e, _) => self.propagate_through_expr(&e, succ),
1248             _ => self.propagate_through_expr(expr, succ)
1249         }
1250     }
1251
1252     // see comment on propagate_through_place()
1253     fn write_place(&mut self, expr: &Expr, succ: LiveNode, acc: u32)
1254                     -> LiveNode {
1255         match expr.node {
1256           hir::ExprPath(hir::QPath::Resolved(_, ref path)) => {
1257               self.access_path(expr.id, path, succ, acc)
1258           }
1259
1260           // We do not track other places, so just propagate through
1261           // to their subcomponents.  Also, it may happen that
1262           // non-places occur here, because those are detected in the
1263           // later pass borrowck.
1264           _ => succ
1265         }
1266     }
1267
1268     fn access_var(&mut self, id: NodeId, nid: NodeId, succ: LiveNode, acc: u32, span: Span)
1269                   -> LiveNode {
1270         let ln = self.live_node(id, span);
1271         if acc != 0 {
1272             self.init_from_succ(ln, succ);
1273             let var = self.variable(nid, span);
1274             self.acc(ln, var, acc);
1275         }
1276         ln
1277     }
1278
1279     fn access_path(&mut self, id: NodeId, path: &hir::Path, succ: LiveNode, acc: u32)
1280                    -> LiveNode {
1281         match path.def {
1282           Def::Local(nid) => {
1283             self.access_var(id, nid, succ, acc, path.span)
1284           }
1285           _ => succ
1286         }
1287     }
1288
1289     fn propagate_through_loop(&mut self,
1290                               expr: &Expr,
1291                               kind: LoopKind,
1292                               body: &hir::Block,
1293                               succ: LiveNode)
1294                               -> LiveNode {
1295
1296         /*
1297
1298         We model control flow like this:
1299
1300               (cond) <--+
1301                 |       |
1302                 v       |
1303           +-- (expr)    |
1304           |     |       |
1305           |     v       |
1306           |   (body) ---+
1307           |
1308           |
1309           v
1310         (succ)
1311
1312         */
1313
1314
1315         // first iteration:
1316         let mut first_merge = true;
1317         let ln = self.live_node(expr.id, expr.span);
1318         self.init_empty(ln, succ);
1319         match kind {
1320             LoopLoop => {}
1321             _ => {
1322                 // If this is not a `loop` loop, then it's possible we bypass
1323                 // the body altogether. Otherwise, the only way is via a `break`
1324                 // in the loop body.
1325                 self.merge_from_succ(ln, succ, first_merge);
1326                 first_merge = false;
1327             }
1328         }
1329         debug!("propagate_through_loop: using id for loop body {} {}",
1330                expr.id, self.ir.tcx.hir.node_to_pretty_string(body.id));
1331
1332         let break_ln = succ;
1333         let cont_ln = ln;
1334         self.break_ln.insert(expr.id, break_ln);
1335         self.cont_ln.insert(expr.id, cont_ln);
1336
1337         let cond_ln = match kind {
1338             LoopLoop => ln,
1339             WhileLoop(ref cond) => self.propagate_through_expr(&cond, ln),
1340         };
1341         let body_ln = self.propagate_through_block(body, cond_ln);
1342
1343         // repeat until fixed point is reached:
1344         while self.merge_from_succ(ln, body_ln, first_merge) {
1345             first_merge = false;
1346
1347             let new_cond_ln = match kind {
1348                 LoopLoop => ln,
1349                 WhileLoop(ref cond) => {
1350                     self.propagate_through_expr(&cond, ln)
1351                 }
1352             };
1353             assert!(cond_ln == new_cond_ln);
1354             assert!(body_ln == self.propagate_through_block(body, cond_ln));
1355         }
1356
1357         cond_ln
1358     }
1359 }
1360
1361 // _______________________________________________________________________
1362 // Checking for error conditions
1363
1364 impl<'a, 'tcx> Visitor<'tcx> for Liveness<'a, 'tcx> {
1365     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1366         NestedVisitorMap::None
1367     }
1368
1369     fn visit_local(&mut self, l: &'tcx hir::Local) {
1370         check_local(self, l);
1371     }
1372     fn visit_expr(&mut self, ex: &'tcx Expr) {
1373         check_expr(self, ex);
1374     }
1375     fn visit_arm(&mut self, a: &'tcx hir::Arm) {
1376         check_arm(self, a);
1377     }
1378 }
1379
1380 fn check_local<'a, 'tcx>(this: &mut Liveness<'a, 'tcx>, local: &'tcx hir::Local) {
1381     match local.init {
1382         Some(_) => {
1383             this.warn_about_unused_or_dead_vars_in_pat(&local.pat);
1384         },
1385         None => {
1386             this.pat_bindings(&local.pat, |this, ln, var, sp, id| {
1387                 let span = local.pat.simple_span().unwrap_or(sp);
1388                 this.warn_about_unused(span, id, ln, var);
1389             })
1390         }
1391     }
1392
1393     intravisit::walk_local(this, local);
1394 }
1395
1396 fn check_arm<'a, 'tcx>(this: &mut Liveness<'a, 'tcx>, arm: &'tcx hir::Arm) {
1397     // only consider the first pattern; any later patterns must have
1398     // the same bindings, and we also consider the first pattern to be
1399     // the "authoritative" set of ids
1400     this.arm_pats_bindings(arm.pats.first().map(|p| &**p), |this, ln, var, sp, id| {
1401         this.warn_about_unused(sp, id, ln, var);
1402     });
1403     intravisit::walk_arm(this, arm);
1404 }
1405
1406 fn check_expr<'a, 'tcx>(this: &mut Liveness<'a, 'tcx>, expr: &'tcx Expr) {
1407     match expr.node {
1408       hir::ExprAssign(ref l, _) => {
1409         this.check_place(&l);
1410
1411         intravisit::walk_expr(this, expr);
1412       }
1413
1414       hir::ExprAssignOp(_, ref l, _) => {
1415         if !this.tables.is_method_call(expr) {
1416             this.check_place(&l);
1417         }
1418
1419         intravisit::walk_expr(this, expr);
1420       }
1421
1422       hir::ExprInlineAsm(ref ia, ref outputs, ref inputs) => {
1423         for input in inputs {
1424           this.visit_expr(input);
1425         }
1426
1427         // Output operands must be places
1428         for (o, output) in ia.outputs.iter().zip(outputs) {
1429           if !o.is_indirect {
1430             this.check_place(output);
1431           }
1432           this.visit_expr(output);
1433         }
1434
1435         intravisit::walk_expr(this, expr);
1436       }
1437
1438       // no correctness conditions related to liveness
1439       hir::ExprCall(..) | hir::ExprMethodCall(..) | hir::ExprIf(..) |
1440       hir::ExprMatch(..) | hir::ExprWhile(..) | hir::ExprLoop(..) |
1441       hir::ExprIndex(..) | hir::ExprField(..) |
1442       hir::ExprArray(..) | hir::ExprTup(..) | hir::ExprBinary(..) |
1443       hir::ExprCast(..) | hir::ExprUnary(..) | hir::ExprRet(..) |
1444       hir::ExprBreak(..) | hir::ExprAgain(..) | hir::ExprLit(_) |
1445       hir::ExprBlock(..) | hir::ExprAddrOf(..) |
1446       hir::ExprStruct(..) | hir::ExprRepeat(..) |
1447       hir::ExprClosure(..) | hir::ExprPath(_) | hir::ExprYield(..) |
1448       hir::ExprBox(..) | hir::ExprType(..) => {
1449         intravisit::walk_expr(this, expr);
1450       }
1451     }
1452 }
1453
1454 impl<'a, 'tcx> Liveness<'a, 'tcx> {
1455     fn check_place(&mut self, expr: &'tcx Expr) {
1456         match expr.node {
1457             hir::ExprPath(hir::QPath::Resolved(_, ref path)) => {
1458                 if let Def::Local(nid) = path.def {
1459                     // Assignment to an immutable variable or argument: only legal
1460                     // if there is no later assignment. If this local is actually
1461                     // mutable, then check for a reassignment to flag the mutability
1462                     // as being used.
1463                     let ln = self.live_node(expr.id, expr.span);
1464                     let var = self.variable(nid, expr.span);
1465                     self.warn_about_dead_assign(expr.span, expr.id, ln, var);
1466                 }
1467             }
1468             _ => {
1469                 // For other kinds of places, no checks are required,
1470                 // and any embedded expressions are actually rvalues
1471                 intravisit::walk_expr(self, expr);
1472             }
1473         }
1474     }
1475
1476     fn should_warn(&self, var: Variable) -> Option<String> {
1477         let name = self.ir.variable_name(var);
1478         if name.is_empty() || name.as_bytes()[0] == ('_' as u8) {
1479             None
1480         } else {
1481             Some(name)
1482         }
1483     }
1484
1485     fn warn_about_unused_args(&self, body: &hir::Body, entry_ln: LiveNode) {
1486         for arg in &body.arguments {
1487             arg.pat.each_binding(|_bm, p_id, _, path1| {
1488                 let sp = path1.span;
1489                 let var = self.variable(p_id, sp);
1490                 // Ignore unused self.
1491                 let name = path1.node;
1492                 if name != keywords::SelfValue.name() {
1493                     if !self.warn_about_unused(sp, p_id, entry_ln, var) {
1494                         if self.live_on_entry(entry_ln, var).is_none() {
1495                             self.report_dead_assign(p_id, sp, var, true);
1496                         }
1497                     }
1498                 }
1499             })
1500         }
1501     }
1502
1503     fn warn_about_unused_or_dead_vars_in_pat(&mut self, pat: &hir::Pat) {
1504         self.pat_bindings(pat, |this, ln, var, sp, id| {
1505             if !this.warn_about_unused(sp, id, ln, var) {
1506                 this.warn_about_dead_assign(sp, id, ln, var);
1507             }
1508         })
1509     }
1510
1511     fn warn_about_unused(&self,
1512                          sp: Span,
1513                          id: NodeId,
1514                          ln: LiveNode,
1515                          var: Variable)
1516                          -> bool {
1517         if !self.used_on_entry(ln, var) {
1518             let r = self.should_warn(var);
1519             if let Some(name) = r {
1520
1521                 // annoying: for parameters in funcs like `fn(x: i32)
1522                 // {ret}`, there is only one node, so asking about
1523                 // assigned_on_exit() is not meaningful.
1524                 let is_assigned = if ln == self.s.exit_ln {
1525                     false
1526                 } else {
1527                     self.assigned_on_exit(ln, var).is_some()
1528                 };
1529
1530                 let suggest_underscore_msg = format!("consider using `_{}` instead",
1531                                                      name);
1532
1533                 if is_assigned {
1534                     self.ir.tcx
1535                         .lint_node_note(lint::builtin::UNUSED_VARIABLES, id, sp,
1536                                         &format!("variable `{}` is assigned to, but never used",
1537                                                  name),
1538                                         &suggest_underscore_msg);
1539                 } else if name != "self" {
1540                     let msg = format!("unused variable: `{}`", name);
1541                     let mut err = self.ir.tcx
1542                         .struct_span_lint_node(lint::builtin::UNUSED_VARIABLES, id, sp, &msg);
1543                     if self.ir.variable_is_shorthand(var) {
1544                         err.span_suggestion(sp, "try ignoring the field",
1545                                             format!("{}: _", name));
1546                     } else {
1547                         err.span_suggestion_short(sp, &suggest_underscore_msg,
1548                                                   format!("_{}", name));
1549                     }
1550                     err.emit()
1551                 }
1552             }
1553             true
1554         } else {
1555             false
1556         }
1557     }
1558
1559     fn warn_about_dead_assign(&self,
1560                               sp: Span,
1561                               id: NodeId,
1562                               ln: LiveNode,
1563                               var: Variable) {
1564         if self.live_on_exit(ln, var).is_none() {
1565             self.report_dead_assign(id, sp, var, false);
1566         }
1567     }
1568
1569     fn report_dead_assign(&self, id: NodeId, sp: Span, var: Variable, is_argument: bool) {
1570         if let Some(name) = self.should_warn(var) {
1571             if is_argument {
1572                 self.ir.tcx.lint_node(lint::builtin::UNUSED_ASSIGNMENTS, id, sp,
1573                     &format!("value passed to `{}` is never read", name));
1574             } else {
1575                 self.ir.tcx.lint_node(lint::builtin::UNUSED_ASSIGNMENTS, id, sp,
1576                     &format!("value assigned to `{}` is never read", name));
1577             }
1578         }
1579     }
1580 }