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