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.
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.
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
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.
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.
31 //! ## Checking initialization
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.
40 //! After each explicit move, the variable must be dead.
42 //! ## Computing last uses
44 //! Any use of the variable where the variable is dead afterwards is a
47 //! # Implementation details
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).
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.
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.
67 //! ## The `Users` struct
69 //! At each live node `N`, we track three pieces of information for each
70 //! variable `V` (these are encapsulated in the `Users` struct):
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).
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`.
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.
89 //! ## Special Variables
91 //! We generate various special variables for various, well, special purposes.
92 //! These are described in the `specials` struct:
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.
97 //! - `fallthrough_ln`: a live node that represents a fallthrough
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::*;
110 use ty::{self, TyCtxt};
112 use util::nodemap::{NodeMap, NodeSet};
114 use std::collections::VecDeque;
115 use std::{fmt, usize};
116 use std::io::prelude::*;
119 use syntax::ast::{self, NodeId};
121 use syntax::symbol::keywords;
122 use syntax_pos::Span;
126 use hir::intravisit::{self, Visitor, FnKind, NestedVisitorMap};
128 /// For use with `propagate_through_loop`.
130 /// An endless `loop` loop.
132 /// A `while` loop, with the given expression as condition.
136 #[derive(Copy, Clone, PartialEq)]
137 struct Variable(usize);
139 #[derive(Copy, PartialEq)]
140 struct LiveNode(usize);
143 fn get(&self) -> usize { let Variable(v) = *self; v }
147 fn get(&self) -> usize { let LiveNode(v) = *self; v }
150 impl Clone for LiveNode {
151 fn clone(&self) -> LiveNode {
156 #[derive(Copy, Clone, PartialEq, Debug)]
164 fn live_node_kind_to_string(lnk: LiveNodeKind, tcx: TyCtxt) -> String {
165 let cm = tcx.sess.codemap();
168 format!("Free var node [{}]", cm.span_to_string(s))
171 format!("Expr node [{}]", cm.span_to_string(s))
174 format!("Var def node [{}]", cm.span_to_string(s))
176 ExitNode => "Exit node".to_string(),
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)
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);
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); }
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();
200 impl fmt::Debug for LiveNode {
201 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
202 write!(f, "ln({})", self.get())
206 impl fmt::Debug for Variable {
207 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
208 write!(f, "v({})", self.get())
212 // ______________________________________________________________________
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.
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.
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.
235 fn is_valid(&self) -> bool {
236 self.get() != usize::MAX
240 fn invalid_node() -> LiveNode { LiveNode(usize::MAX) }
247 #[derive(Copy, Clone, Debug)]
254 #[derive(Copy, Clone, Debug)]
256 Arg(NodeId, ast::Name),
261 struct IrMaps<'a, 'tcx: 'a> {
262 tcx: TyCtxt<'a, 'tcx, 'tcx>,
264 num_live_nodes: 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>,
273 impl<'a, 'tcx> IrMaps<'a, 'tcx> {
274 fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> IrMaps<'a, 'tcx> {
279 live_node_map: NodeMap(),
280 variable_map: NodeMap(),
281 capture_info_map: NodeMap(),
282 var_kinds: Vec::new(),
287 fn add_live_node(&mut self, lnk: LiveNodeKind) -> LiveNode {
288 let ln = LiveNode(self.num_live_nodes);
290 self.num_live_nodes += 1;
292 debug!("{:?} is of kind {}", ln,
293 live_node_kind_to_string(lnk, self.tcx));
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);
302 debug!("{:?} is node {}", ln, node_id);
305 fn add_variable(&mut self, vk: VarKind) -> Variable {
306 let v = Variable(self.num_vars);
307 self.var_kinds.push(vk);
311 Local(LocalInfo { id: node_id, .. }) | Arg(node_id, _) => {
312 self.variable_map.insert(node_id, v);
317 debug!("{:?} is {:?}", v, vk);
322 fn variable(&self, node_id: NodeId, span: Span) -> Variable {
323 match self.variable_map.get(&node_id) {
326 span_bug!(span, "no variable registered for id {}", node_id);
331 fn variable_name(&self, var: Variable) -> String {
332 match self.var_kinds[var.get()] {
333 Local(LocalInfo { name, .. }) | Arg(_, name) => {
336 CleanExit => "<clean-exit>".to_string()
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
347 fn set_captures(&mut self, node_id: NodeId, cs: Vec<CaptureInfo>) {
348 self.capture_info_map.insert(node_id, Rc::new(cs));
351 fn lnk(&self, ln: LiveNode) -> LiveNodeKind {
356 fn visit_fn<'a, 'tcx: 'a>(ir: &mut IrMaps<'a, 'tcx>,
358 decl: &'tcx hir::FnDecl,
359 body_id: hir::BodyId,
364 // swap in a new set of IR maps for this function body:
365 let mut fn_maps = IrMaps::new(ir.tcx);
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")) {
377 debug!("creating fn_maps: {:?}", &fn_maps as *const IrMaps);
379 let body = ir.tcx.hir.body(body_id);
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));
389 // gather up the various local variables, significant expressions,
391 intravisit::walk_fn(&mut fn_maps, fk, decl, body_id, sp, id);
394 let mut lsets = Liveness::new(&mut fn_maps, body_id);
395 let entry_ln = lsets.compute(&body.value);
397 // check for various error conditions
398 lsets.visit_body(body);
399 lsets.warn_about_unused_args(body, entry_ln);
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`).
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();
412 while let Some(pat) = pats.pop_front() {
415 Binding(_, _, _, ref inner_pat) => {
416 pats.extend(inner_pat.iter());
418 Struct(_, ref fields, _) => {
419 for field in fields {
420 if field.node.is_shorthand {
421 shorthand_field_ids.insert(field.node.pat.id);
425 Ref(ref inner_pat, _) |
426 Box(ref inner_pat) => {
427 pats.push_back(inner_pat);
429 TupleStruct(_, ref inner_pats, _) |
430 Tuple(ref inner_pats, _) => {
431 pats.extend(inner_pats.iter());
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());
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 {
448 is_shorthand: shorthand_field_ids.contains(&p_id)
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);
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);
462 intravisit::walk_arm(ir, arm);
465 fn visit_expr<'a, 'tcx>(ir: &mut IrMaps<'a, 'tcx>, expr: &'tcx Expr) {
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));
473 intravisit::walk_expr(ir, expr);
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));
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| {
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,
494 ir.set_captures(expr.id, call_caps);
496 intravisit::walk_expr(ir, expr);
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);
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);
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);
524 // ______________________________________________________________________
525 // Computing liveness sets
527 // Actually we compute just a bit more than just liveness, but we use
528 // the same basic propagation framework in all cases.
530 #[derive(Clone, Copy)]
537 fn invalid_users() -> Users {
539 reader: invalid_node(),
540 writer: invalid_node(),
545 #[derive(Copy, Clone)]
548 fallthrough_ln: LiveNode,
549 clean_exit_var: Variable
552 const ACC_READ: u32 = 1;
553 const ACC_WRITE: u32 = 2;
554 const ACC_USE: u32 = 4;
556 struct Liveness<'a, 'tcx: 'a> {
557 ir: &'a mut IrMaps<'a, 'tcx>,
558 tables: &'a ty::TypeckTables<'tcx>,
560 successors: Vec<LiveNode>,
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>,
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)
582 let tables = ir.tcx.body_tables(body);
584 let num_live_nodes = ir.num_live_nodes;
585 let num_vars = ir.num_vars;
591 successors: vec![invalid_node(); num_live_nodes],
592 users: vec![invalid_users(); num_live_nodes * num_vars],
598 fn live_node(&self, node_id: NodeId, span: Span) -> LiveNode {
599 match self.ir.live_node_map.get(&node_id) {
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.
608 "no live node registered for node {}",
614 fn variable(&self, node_id: NodeId, span: Span) -> Variable {
615 self.ir.variable(node_id, span)
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),
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);
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),
631 if let Some(pat) = pat {
632 self.pat_bindings(pat, f);
636 fn define_bindings_in_pat(&mut self, pat: &hir::Pat, succ: LiveNode)
638 self.define_bindings_in_arm_pats(Some(pat), succ)
641 fn define_bindings_in_arm_pats(&mut self, pat: Option<&hir::Pat>, succ: LiveNode)
644 self.arm_pats_bindings(pat, |this, ln, var, _sp, _id| {
645 this.init_from_succ(ln, succ);
646 this.define(ln, var);
652 fn idx(&self, ln: LiveNode, var: Variable) -> usize {
653 ln.get() * self.ir.num_vars + var.get()
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}
664 Is this variable live on entry to any of its successor nodes?
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)
672 fn used_on_entry(&self, ln: LiveNode, var: Variable) -> bool {
673 assert!(ln.is_valid());
674 self.users[self.idx(ln, var)].used
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}
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)
690 fn indices2<F>(&mut self, ln: LiveNode, succ_ln: LiveNode, mut op: F) where
691 F: FnMut(&mut Liveness<'a, 'tcx>, usize, usize),
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);
700 fn write_vars<F>(&self,
704 -> io::Result<()> where
705 F: FnMut(usize) -> LiveNode,
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))?;
718 #[allow(unused_must_use)]
719 fn ln_str(&self, ln: LiveNode) -> String {
720 let mut wr = Vec::new();
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()]);
729 String::from_utf8(wr).unwrap()
732 fn init_empty(&mut self, ln: LiveNode, succ_ln: LiveNode) {
733 self.successors[ln.get()] = succ_ln;
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.
740 // self.indices(ln) { |idx|
741 // self.users[idx] = invalid_users();
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;
749 self.indices2(ln, succ_ln, |this, idx, succ_idx| {
750 this.users[idx] = this.users[succ_idx]
752 debug!("init_from_succ(ln={}, succ={})",
753 self.ln_str(ln), self.ln_str(succ_ln));
756 fn merge_from_succ(&mut self,
761 if ln == succ_ln { return false; }
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;
775 debug!("merge_from_succ(ln={:?}, succ={}, first_merge={}, changed={})",
776 ln, self.ln_str(succ_ln), first_merge, changed);
779 fn copy_if_invalid(src: LiveNode, dst: &mut LiveNode) -> bool {
780 if src.is_valid() && !dst.is_valid() {
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();
797 debug!("{:?} defines {:?} (idx={}): {}", writer, var,
798 idx, self.ln_str(writer));
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));
806 let idx = self.idx(ln, var);
807 let user = &mut self.users[idx];
809 if (acc & ACC_WRITE) != 0 {
810 user.reader = invalid_node();
814 // Important: if we both read/write, must do read second
815 // or else the write will override.
816 if (acc & ACC_READ) != 0 {
820 if (acc & ACC_USE) != 0 {
825 // _______________________________________________________________________
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.
832 debug!("compute: using id for body, {}", self.ir.tcx.hir.node_to_pretty_string(body.id));
834 let exit_ln = self.s.exit_ln;
836 self.break_ln.insert(body.id, exit_ln);
837 self.cont_ln.insert(body.id, exit_ln);
839 // the fallthrough exit is only for those cases where we do not
840 // explicitly return:
842 self.init_from_succ(s.fallthrough_ln, s.exit_ln);
843 self.acc(s.fallthrough_ln, s.clean_exit_var, ACC_READ);
845 let entry_ln = self.propagate_through_expr(body, s.fallthrough_ln);
847 // hack to skip the loop unless debug! is enabled:
848 debug!("^^ liveness computation results for body {} (entry={:?})",
850 for ln_idx in 0..self.ir.num_live_nodes {
851 debug!("{:?}", self.ln_str(LiveNode(ln_idx)));
860 fn propagate_through_block(&mut self, blk: &hir::Block, succ: LiveNode)
862 if blk.targeted_by_break {
863 self.break_ln.insert(blk.id, succ);
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)
871 fn propagate_through_stmt(&mut self, stmt: &hir::Stmt, succ: LiveNode)
874 hir::StmtDecl(ref decl, _) => {
875 self.propagate_through_decl(&decl, succ)
878 hir::StmtExpr(ref expr, _) | hir::StmtSemi(ref expr, _) => {
879 self.propagate_through_expr(&expr, succ)
884 fn propagate_through_decl(&mut self, decl: &hir::Decl, succ: LiveNode)
887 hir::DeclLocal(ref local) => {
888 self.propagate_through_local(&local, succ)
890 hir::DeclItem(_) => succ,
894 fn propagate_through_local(&mut self, local: &hir::Local, succ: 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.
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.
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)
914 fn propagate_through_exprs(&mut self, exprs: &[Expr], succ: LiveNode)
916 exprs.iter().rev().fold(succ, |succ, expr| {
917 self.propagate_through_expr(&expr, succ)
921 fn propagate_through_opt_expr(&mut self,
922 opt_expr: Option<&Expr>,
925 opt_expr.map_or(succ, |expr| self.propagate_through_expr(expr, succ))
928 fn propagate_through_expr(&mut self, expr: &Expr, succ: LiveNode)
930 debug!("propagate_through_expr: {}", self.ir.tcx.hir.node_to_pretty_string(expr.id));
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)
938 hir::ExprField(ref e, _) => {
939 self.propagate_through_expr(&e, succ)
942 hir::ExprClosure(.., blk_id, _, _) => {
943 debug!("{} is an ExprClosure", self.ir.tcx.hir.node_to_pretty_string(expr.id));
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.
949 let node = self.live_node(expr.id, expr.span);
953 self.break_ln.insert(blk_id.node_id, break_ln);
954 self.cont_ln.insert(blk_id.node_id, cont_ln);
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(),
961 span_bug!(expr.span, "no registered caps");
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);
972 hir::ExprIf(ref cond, ref then, ref els) => {
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)
994 hir::ExprWhile(ref cond, ref blk, _) => {
995 self.propagate_through_loop(expr, WhileLoop(&cond), &blk, succ)
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)
1004 hir::ExprMatch(ref e, ref arms, _) => {
1019 let ln = self.live_node(expr.id, expr.span);
1020 self.init_empty(ln, succ);
1021 let mut first_merge = true;
1024 self.propagate_through_expr(&arm.body, 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
1031 self.define_bindings_in_arm_pats(arm.pats.first().map(|p| &**p),
1033 self.merge_from_succ(ln, arm_succ, first_merge);
1034 first_merge = false;
1036 self.propagate_through_expr(&e, ln)
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)
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),
1052 // Now that we know the label we're going to,
1053 // look it up in the break loop nodes table
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")
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),
1068 // Now that we know the label we're going to,
1069 // look it up in the continue loop nodes table
1071 match self.cont_ln.get(&sc) {
1073 None => span_bug!(expr.span, "continue to unknown label")
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)
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)
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)
1099 // Uninteresting cases: just propagate in rev exec order
1101 hir::ExprArray(ref exprs) => {
1102 self.propagate_through_exprs(exprs, succ)
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)
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() {
1119 let succ = self.propagate_through_exprs(args, succ);
1120 self.propagate_through_expr(&f, succ)
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() {
1130 self.propagate_through_exprs(args, succ)
1133 hir::ExprTup(ref exprs) => {
1134 self.propagate_through_exprs(exprs, succ)
1137 hir::ExprBinary(op, ref l, ref r) if op.node.is_lazy() => {
1138 let r_succ = self.propagate_through_expr(&r, succ);
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);
1144 self.propagate_through_expr(&l, ln)
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)
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)
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()
1168 self.propagate_through_expr(output, succ)
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)
1176 // Inputs are executed first. Propagate last because of rev order
1177 self.propagate_through_exprs(inputs, succ)
1180 hir::ExprLit(..) | hir::ExprPath(hir::QPath::TypeRelative(..)) => {
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)
1192 fn propagate_through_place_components(&mut self,
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.
1204 // The two kinds of graphs are:
1206 // Tracked place Untracked place
1207 // ----------------------++-----------------------
1211 // (rvalue) || (rvalue)
1214 // (write of place) || (place components)
1219 // ----------------------++-----------------------
1221 // I will cover the two cases in turn:
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
1231 // # Non-tracked places
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).
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.
1246 hir::ExprPath(_) => succ,
1247 hir::ExprField(ref e, _) => self.propagate_through_expr(&e, succ),
1248 _ => self.propagate_through_expr(expr, succ)
1252 // see comment on propagate_through_place()
1253 fn write_place(&mut self, expr: &Expr, succ: LiveNode, acc: u32)
1256 hir::ExprPath(hir::QPath::Resolved(_, ref path)) => {
1257 self.access_path(expr.id, path, succ, acc)
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.
1268 fn access_var(&mut self, id: NodeId, nid: NodeId, succ: LiveNode, acc: u32, span: Span)
1270 let ln = self.live_node(id, span);
1272 self.init_from_succ(ln, succ);
1273 let var = self.variable(nid, span);
1274 self.acc(ln, var, acc);
1279 fn access_path(&mut self, id: NodeId, path: &hir::Path, succ: LiveNode, acc: u32)
1282 Def::Local(nid) => {
1283 self.access_var(id, nid, succ, acc, path.span)
1289 fn propagate_through_loop(&mut self,
1298 We model control flow like this:
1316 let mut first_merge = true;
1317 let ln = self.live_node(expr.id, expr.span);
1318 self.init_empty(ln, succ);
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;
1329 debug!("propagate_through_loop: using id for loop body {} {}",
1330 expr.id, self.ir.tcx.hir.node_to_pretty_string(body.id));
1332 let break_ln = succ;
1334 self.break_ln.insert(expr.id, break_ln);
1335 self.cont_ln.insert(expr.id, cont_ln);
1337 let cond_ln = match kind {
1339 WhileLoop(ref cond) => self.propagate_through_expr(&cond, ln),
1341 let body_ln = self.propagate_through_block(body, cond_ln);
1343 // repeat until fixed point is reached:
1344 while self.merge_from_succ(ln, body_ln, first_merge) {
1345 first_merge = false;
1347 let new_cond_ln = match kind {
1349 WhileLoop(ref cond) => {
1350 self.propagate_through_expr(&cond, ln)
1353 assert!(cond_ln == new_cond_ln);
1354 assert!(body_ln == self.propagate_through_block(body, cond_ln));
1361 // _______________________________________________________________________
1362 // Checking for error conditions
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
1369 fn visit_local(&mut self, l: &'tcx hir::Local) {
1370 check_local(self, l);
1372 fn visit_expr(&mut self, ex: &'tcx Expr) {
1373 check_expr(self, ex);
1375 fn visit_arm(&mut self, a: &'tcx hir::Arm) {
1380 fn check_local<'a, 'tcx>(this: &mut Liveness<'a, 'tcx>, local: &'tcx hir::Local) {
1383 this.warn_about_unused_or_dead_vars_in_pat(&local.pat);
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);
1393 intravisit::walk_local(this, local);
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);
1403 intravisit::walk_arm(this, arm);
1406 fn check_expr<'a, 'tcx>(this: &mut Liveness<'a, 'tcx>, expr: &'tcx Expr) {
1408 hir::ExprAssign(ref l, _) => {
1409 this.check_place(&l);
1411 intravisit::walk_expr(this, expr);
1414 hir::ExprAssignOp(_, ref l, _) => {
1415 if !this.tables.is_method_call(expr) {
1416 this.check_place(&l);
1419 intravisit::walk_expr(this, expr);
1422 hir::ExprInlineAsm(ref ia, ref outputs, ref inputs) => {
1423 for input in inputs {
1424 this.visit_expr(input);
1427 // Output operands must be places
1428 for (o, output) in ia.outputs.iter().zip(outputs) {
1430 this.check_place(output);
1432 this.visit_expr(output);
1435 intravisit::walk_expr(this, expr);
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);
1454 impl<'a, 'tcx> Liveness<'a, 'tcx> {
1455 fn check_place(&mut self, expr: &'tcx Expr) {
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
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);
1469 // For other kinds of places, no checks are required,
1470 // and any embedded expressions are actually rvalues
1471 intravisit::walk_expr(self, expr);
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) {
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);
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);
1511 fn warn_about_unused(&self,
1517 if !self.used_on_entry(ln, var) {
1518 let r = self.should_warn(var);
1519 if let Some(name) = r {
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 {
1527 self.assigned_on_exit(ln, var).is_some()
1530 let suggest_underscore_msg = format!("consider using `_{}` instead",
1535 .lint_node_note(lint::builtin::UNUSED_VARIABLES, id, sp,
1536 &format!("variable `{}` is assigned to, but never used",
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));
1547 err.span_suggestion_short(sp, &suggest_underscore_msg,
1548 format!("_{}", name));
1559 fn warn_about_dead_assign(&self,
1564 if self.live_on_exit(ln, var).is_none() {
1565 self.report_dead_assign(id, sp, var, false);
1569 fn report_dead_assign(&self, id: NodeId, sp: Span, var: Variable, is_argument: bool) {
1570 if let Some(name) = self.should_warn(var) {
1572 self.ir.tcx.lint_node(lint::builtin::UNUSED_ASSIGNMENTS, id, sp,
1573 &format!("value passed to `{}` is never read", name));
1575 self.ir.tcx.lint_node(lint::builtin::UNUSED_ASSIGNMENTS, id, sp,
1576 &format!("value assigned to `{}` is never read", name));