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 //! - `no_ret_var`: a synthetic variable that is only 'read' from, the
100 //! fallthrough node. This allows us to detect functions where we fail
101 //! to return explicitly.
102 //! - `clean_exit_var`: a synthetic variable that is only 'read' from the
103 //! fallthrough node. It is only live if the function could converge
104 //! via means other than an explicit `return` expression. That is, it is
105 //! only dead if the end of the function's block can never be reached.
106 //! It is the responsibility of typeck to ensure that there are no
107 //! `return` expressions in a function declared as diverging.
108 use self::LoopKind
::*;
109 use self::LiveNodeKind
::*;
110 use self::VarKind
::*;
113 use middle
::pat_util
;
116 use util
::nodemap
::NodeMap
;
118 use std
::{fmt, usize}
;
119 use std
::io
::prelude
::*;
122 use syntax
::ast
::{self, NodeId}
;
123 use syntax
::codemap
::{BytePos, original_sp, Span}
;
124 use syntax
::parse
::token
::special_idents
;
127 use rustc_front
::hir
::Expr
;
128 use rustc_front
::hir
;
129 use rustc_front
::print
::pprust
::{expr_to_string, block_to_string}
;
130 use rustc_front
::intravisit
::{self, Visitor, FnKind}
;
132 /// For use with `propagate_through_loop`.
134 /// An endless `loop` loop.
136 /// A `while` loop, with the given expression as condition.
140 #[derive(Copy, Clone, PartialEq)]
141 struct Variable(usize);
143 #[derive(Copy, PartialEq)]
144 struct LiveNode(usize);
147 fn get(&self) -> usize { let Variable(v) = *self; v }
151 fn get(&self) -> usize { let LiveNode(v) = *self; v }
154 impl Clone
for LiveNode
{
155 fn clone(&self) -> LiveNode
{
160 #[derive(Copy, Clone, PartialEq, Debug)]
168 fn live_node_kind_to_string(lnk
: LiveNodeKind
, cx
: &ty
::ctxt
) -> String
{
169 let cm
= cx
.sess
.codemap();
172 format
!("Free var node [{}]", cm
.span_to_string(s
))
175 format
!("Expr node [{}]", cm
.span_to_string(s
))
178 format
!("Var def node [{}]", cm
.span_to_string(s
))
180 ExitNode
=> "Exit node".to_string(),
184 impl<'a
, 'tcx
, 'v
> Visitor
<'v
> for IrMaps
<'a
, 'tcx
> {
185 fn visit_fn(&mut self, fk
: FnKind
<'v
>, fd
: &'v hir
::FnDecl
,
186 b
: &'v hir
::Block
, s
: Span
, id
: NodeId
) {
187 visit_fn(self, fk
, fd
, b
, s
, id
);
189 fn visit_local(&mut self, l
: &hir
::Local
) { visit_local(self, l); }
190 fn visit_expr(&mut self, ex
: &Expr
) { visit_expr(self, ex); }
191 fn visit_arm(&mut self, a
: &hir
::Arm
) { visit_arm(self, a); }
194 pub fn check_crate(tcx
: &ty
::ctxt
) {
195 tcx
.map
.krate().visit_all_items(&mut IrMaps
::new(tcx
));
196 tcx
.sess
.abort_if_errors();
199 impl fmt
::Debug
for LiveNode
{
200 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
201 write
!(f
, "ln({})", self.get())
205 impl fmt
::Debug
for Variable
{
206 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
207 write
!(f
, "v({})", self.get())
211 // ______________________________________________________________________
214 // This is the first pass and the one that drives the main
215 // computation. It walks up and down the IR once. On the way down,
216 // we count for each function the number of variables as well as
217 // liveness nodes. A liveness node is basically an expression or
218 // capture clause that does something of interest: either it has
219 // interesting control flow or it uses/defines a local variable.
221 // On the way back up, at each function node we create liveness sets
222 // (we now know precisely how big to make our various vectors and so
223 // forth) and then do the data-flow propagation to compute the set
224 // of live variables at each program point.
226 // Finally, we run back over the IR one last time and, using the
227 // computed liveness, check various safety conditions. For example,
228 // there must be no live nodes at the definition site for a variable
229 // unless it has an initializer. Similarly, each non-mutable local
230 // variable must not be assigned if there is some successor
231 // assignment. And so forth.
234 fn is_valid(&self) -> bool
{
235 self.get() != usize::MAX
239 fn invalid_node() -> LiveNode { LiveNode(usize::MAX) }
246 #[derive(Copy, Clone, Debug)]
252 #[derive(Copy, Clone, Debug)]
254 Arg(NodeId
, ast
::Name
),
260 struct IrMaps
<'a
, 'tcx
: 'a
> {
261 tcx
: &'a ty
::ctxt
<'tcx
>,
263 num_live_nodes
: usize,
265 live_node_map
: NodeMap
<LiveNode
>,
266 variable_map
: NodeMap
<Variable
>,
267 capture_info_map
: NodeMap
<Rc
<Vec
<CaptureInfo
>>>,
268 var_kinds
: Vec
<VarKind
>,
269 lnks
: Vec
<LiveNodeKind
>,
272 impl<'a
, 'tcx
> IrMaps
<'a
, 'tcx
> {
273 fn new(tcx
: &'a ty
::ctxt
<'tcx
>) -> IrMaps
<'a
, 'tcx
> {
278 live_node_map
: NodeMap(),
279 variable_map
: NodeMap(),
280 capture_info_map
: NodeMap(),
281 var_kinds
: Vec
::new(),
286 fn add_live_node(&mut self, lnk
: LiveNodeKind
) -> LiveNode
{
287 let ln
= LiveNode(self.num_live_nodes
);
289 self.num_live_nodes
+= 1;
291 debug
!("{:?} is of kind {}", ln
,
292 live_node_kind_to_string(lnk
, self.tcx
));
297 fn add_live_node_for_node(&mut self, node_id
: NodeId
, lnk
: LiveNodeKind
) {
298 let ln
= self.add_live_node(lnk
);
299 self.live_node_map
.insert(node_id
, ln
);
301 debug
!("{:?} is node {}", ln
, node_id
);
304 fn add_variable(&mut self, vk
: VarKind
) -> Variable
{
305 let v
= Variable(self.num_vars
);
306 self.var_kinds
.push(vk
);
310 Local(LocalInfo { id: node_id, .. }
) | Arg(node_id
, _
) => {
311 self.variable_map
.insert(node_id
, v
);
313 ImplicitRet
| CleanExit
=> {}
316 debug
!("{:?} is {:?}", v
, vk
);
321 fn variable(&self, node_id
: NodeId
, span
: Span
) -> Variable
{
322 match self.variable_map
.get(&node_id
) {
327 .span_bug(span
, &format
!("no variable registered for id {}",
333 fn variable_name(&self, var
: Variable
) -> String
{
334 match self.var_kinds
[var
.get()] {
335 Local(LocalInfo { name, .. }
) | Arg(_
, name
) => {
338 ImplicitRet
=> "<implicit-ret>".to_string(),
339 CleanExit
=> "<clean-exit>".to_string()
343 fn set_captures(&mut self, node_id
: NodeId
, cs
: Vec
<CaptureInfo
>) {
344 self.capture_info_map
.insert(node_id
, Rc
::new(cs
));
347 fn lnk(&self, ln
: LiveNode
) -> LiveNodeKind
{
352 impl<'a
, 'tcx
, 'v
> Visitor
<'v
> for Liveness
<'a
, 'tcx
> {
353 fn visit_fn(&mut self, fk
: FnKind
<'v
>, fd
: &'v hir
::FnDecl
,
354 b
: &'v hir
::Block
, s
: Span
, n
: NodeId
) {
355 check_fn(self, fk
, fd
, b
, s
, n
);
357 fn visit_local(&mut self, l
: &hir
::Local
) {
358 check_local(self, l
);
360 fn visit_expr(&mut self, ex
: &Expr
) {
361 check_expr(self, ex
);
363 fn visit_arm(&mut self, a
: &hir
::Arm
) {
368 fn visit_fn(ir
: &mut IrMaps
,
376 // swap in a new set of IR maps for this function body:
377 let mut fn_maps
= IrMaps
::new(ir
.tcx
);
379 debug
!("creating fn_maps: {:?}", &fn_maps
as *const IrMaps
);
381 for arg
in &decl
.inputs
{
382 pat_util
::pat_bindings(&ir
.tcx
.def_map
,
384 |_bm
, arg_id
, _x
, path1
| {
385 debug
!("adding argument {}", arg_id
);
386 let name
= path1
.node
;
387 fn_maps
.add_variable(Arg(arg_id
, name
));
391 // gather up the various local variables, significant expressions,
393 intravisit
::walk_fn(&mut fn_maps
, fk
, decl
, body
, sp
);
395 // Special nodes and variables:
396 // - exit_ln represents the end of the fn, either by return or panic
397 // - implicit_ret_var is a pseudo-variable that represents
398 // an implicit return
399 let specials
= Specials
{
400 exit_ln
: fn_maps
.add_live_node(ExitNode
),
401 fallthrough_ln
: fn_maps
.add_live_node(ExitNode
),
402 no_ret_var
: fn_maps
.add_variable(ImplicitRet
),
403 clean_exit_var
: fn_maps
.add_variable(CleanExit
)
407 let mut lsets
= Liveness
::new(&mut fn_maps
, specials
);
408 let entry_ln
= lsets
.compute(decl
, body
);
410 // check for various error conditions
411 lsets
.visit_block(body
);
412 lsets
.check_ret(id
, sp
, fk
, entry_ln
, body
);
413 lsets
.warn_about_unused_args(decl
, entry_ln
);
416 fn visit_local(ir
: &mut IrMaps
, local
: &hir
::Local
) {
417 pat_util
::pat_bindings(&ir
.tcx
.def_map
, &*local
.pat
, |_
, p_id
, sp
, path1
| {
418 debug
!("adding local variable {}", p_id
);
419 let name
= path1
.node
;
420 ir
.add_live_node_for_node(p_id
, VarDefNode(sp
));
421 ir
.add_variable(Local(LocalInfo
{
426 intravisit
::walk_local(ir
, local
);
429 fn visit_arm(ir
: &mut IrMaps
, arm
: &hir
::Arm
) {
430 for pat
in &arm
.pats
{
431 pat_util
::pat_bindings(&ir
.tcx
.def_map
, &**pat
, |bm
, p_id
, sp
, path1
| {
432 debug
!("adding local variable {} from match with bm {:?}",
434 let name
= path1
.node
;
435 ir
.add_live_node_for_node(p_id
, VarDefNode(sp
));
436 ir
.add_variable(Local(LocalInfo
{
442 intravisit
::walk_arm(ir
, arm
);
445 fn visit_expr(ir
: &mut IrMaps
, expr
: &Expr
) {
447 // live nodes required for uses or definitions of variables:
448 hir
::ExprPath(..) => {
449 let def
= ir
.tcx
.def_map
.borrow().get(&expr
.id
).unwrap().full_def();
450 debug
!("expr {}: path that leads to {:?}", expr
.id
, def
);
451 if let DefLocal(..) = def
{
452 ir
.add_live_node_for_node(expr
.id
, ExprNode(expr
.span
));
454 intravisit
::walk_expr(ir
, expr
);
456 hir
::ExprClosure(..) => {
457 // Interesting control flow (for loops can contain labeled
458 // breaks or continues)
459 ir
.add_live_node_for_node(expr
.id
, ExprNode(expr
.span
));
461 // Make a live_node for each captured variable, with the span
462 // being the location that the variable is used. This results
463 // in better error messages than just pointing at the closure
464 // construction site.
465 let mut call_caps
= Vec
::new();
466 ir
.tcx
.with_freevars(expr
.id
, |freevars
| {
468 if let DefLocal(_
, rv
) = fv
.def
{
469 let fv_ln
= ir
.add_live_node(FreeVarNode(fv
.span
));
470 call_caps
.push(CaptureInfo
{ln
: fv_ln
,
475 ir
.set_captures(expr
.id
, call_caps
);
477 intravisit
::walk_expr(ir
, expr
);
480 // live nodes required for interesting control flow:
481 hir
::ExprIf(..) | hir
::ExprMatch(..) | hir
::ExprWhile(..) | hir
::ExprLoop(..) => {
482 ir
.add_live_node_for_node(expr
.id
, ExprNode(expr
.span
));
483 intravisit
::walk_expr(ir
, expr
);
485 hir
::ExprBinary(op
, _
, _
) if ::rustc_front
::util
::lazy_binop(op
.node
) => {
486 ir
.add_live_node_for_node(expr
.id
, ExprNode(expr
.span
));
487 intravisit
::walk_expr(ir
, expr
);
490 // otherwise, live nodes are not required:
491 hir
::ExprIndex(..) | hir
::ExprField(..) | hir
::ExprTupField(..) |
492 hir
::ExprVec(..) | hir
::ExprCall(..) | hir
::ExprMethodCall(..) |
493 hir
::ExprTup(..) | hir
::ExprBinary(..) | hir
::ExprAddrOf(..) |
494 hir
::ExprCast(..) | hir
::ExprUnary(..) | hir
::ExprBreak(_
) |
495 hir
::ExprAgain(_
) | hir
::ExprLit(_
) | hir
::ExprRet(..) |
496 hir
::ExprBlock(..) | hir
::ExprAssign(..) | hir
::ExprAssignOp(..) |
497 hir
::ExprStruct(..) | hir
::ExprRepeat(..) |
498 hir
::ExprInlineAsm(..) | hir
::ExprBox(..) |
499 hir
::ExprRange(..) | hir
::ExprType(..) => {
500 intravisit
::walk_expr(ir
, expr
);
505 // ______________________________________________________________________
506 // Computing liveness sets
508 // Actually we compute just a bit more than just liveness, but we use
509 // the same basic propagation framework in all cases.
511 #[derive(Clone, Copy)]
518 fn invalid_users() -> Users
{
520 reader
: invalid_node(),
521 writer
: invalid_node(),
526 #[derive(Copy, Clone)]
529 fallthrough_ln
: LiveNode
,
530 no_ret_var
: Variable
,
531 clean_exit_var
: Variable
534 const ACC_READ
: u32 = 1;
535 const ACC_WRITE
: u32 = 2;
536 const ACC_USE
: u32 = 4;
538 struct Liveness
<'a
, 'tcx
: 'a
> {
539 ir
: &'a
mut IrMaps
<'a
, 'tcx
>,
541 successors
: Vec
<LiveNode
>,
543 // The list of node IDs for the nested loop scopes
545 loop_scope
: Vec
<NodeId
>,
546 // mappings from loop node ID to LiveNode
547 // ("break" label should map to loop node ID,
548 // it probably doesn't now)
549 break_ln
: NodeMap
<LiveNode
>,
550 cont_ln
: NodeMap
<LiveNode
>
553 impl<'a
, 'tcx
> Liveness
<'a
, 'tcx
> {
554 fn new(ir
: &'a
mut IrMaps
<'a
, 'tcx
>, specials
: Specials
) -> Liveness
<'a
, 'tcx
> {
555 let num_live_nodes
= ir
.num_live_nodes
;
556 let num_vars
= ir
.num_vars
;
560 successors
: vec
![invalid_node(); num_live_nodes
],
561 users
: vec
![invalid_users(); num_live_nodes
* num_vars
],
562 loop_scope
: Vec
::new(),
568 fn live_node(&self, node_id
: NodeId
, span
: Span
) -> LiveNode
{
569 match self.ir
.live_node_map
.get(&node_id
) {
572 // This must be a mismatch between the ir_map construction
573 // above and the propagation code below; the two sets of
574 // code have to agree about which AST nodes are worth
575 // creating liveness nodes for.
576 self.ir
.tcx
.sess
.span_bug(
578 &format
!("no live node registered for node {}",
584 fn variable(&self, node_id
: NodeId
, span
: Span
) -> Variable
{
585 self.ir
.variable(node_id
, span
)
588 fn pat_bindings
<F
>(&mut self, pat
: &hir
::Pat
, mut f
: F
) where
589 F
: FnMut(&mut Liveness
<'a
, 'tcx
>, LiveNode
, Variable
, Span
, NodeId
),
591 pat_util
::pat_bindings(&self.ir
.tcx
.def_map
, pat
, |_bm
, p_id
, sp
, _n
| {
592 let ln
= self.live_node(p_id
, sp
);
593 let var
= self.variable(p_id
, sp
);
594 f(self, ln
, var
, sp
, p_id
);
598 fn arm_pats_bindings
<F
>(&mut self, pat
: Option
<&hir
::Pat
>, f
: F
) where
599 F
: FnMut(&mut Liveness
<'a
, 'tcx
>, LiveNode
, Variable
, Span
, NodeId
),
603 self.pat_bindings(pat
, f
);
609 fn define_bindings_in_pat(&mut self, pat
: &hir
::Pat
, succ
: LiveNode
)
611 self.define_bindings_in_arm_pats(Some(pat
), succ
)
614 fn define_bindings_in_arm_pats(&mut self, pat
: Option
<&hir
::Pat
>, succ
: LiveNode
)
617 self.arm_pats_bindings(pat
, |this
, ln
, var
, _sp
, _id
| {
618 this
.init_from_succ(ln
, succ
);
619 this
.define(ln
, var
);
625 fn idx(&self, ln
: LiveNode
, var
: Variable
) -> usize {
626 ln
.get() * self.ir
.num_vars
+ var
.get()
629 fn live_on_entry(&self, ln
: LiveNode
, var
: Variable
)
630 -> Option
<LiveNodeKind
> {
631 assert
!(ln
.is_valid());
632 let reader
= self.users
[self.idx(ln
, var
)].reader
;
633 if reader
.is_valid() {Some(self.ir.lnk(reader))}
else {None}
637 Is this variable live on entry to any of its successor nodes?
639 fn live_on_exit(&self, ln
: LiveNode
, var
: Variable
)
640 -> Option
<LiveNodeKind
> {
641 let successor
= self.successors
[ln
.get()];
642 self.live_on_entry(successor
, var
)
645 fn used_on_entry(&self, ln
: LiveNode
, var
: Variable
) -> bool
{
646 assert
!(ln
.is_valid());
647 self.users
[self.idx(ln
, var
)].used
650 fn assigned_on_entry(&self, ln
: LiveNode
, var
: Variable
)
651 -> Option
<LiveNodeKind
> {
652 assert
!(ln
.is_valid());
653 let writer
= self.users
[self.idx(ln
, var
)].writer
;
654 if writer
.is_valid() {Some(self.ir.lnk(writer))}
else {None}
657 fn assigned_on_exit(&self, ln
: LiveNode
, var
: Variable
)
658 -> Option
<LiveNodeKind
> {
659 let successor
= self.successors
[ln
.get()];
660 self.assigned_on_entry(successor
, var
)
663 fn indices2
<F
>(&mut self, ln
: LiveNode
, succ_ln
: LiveNode
, mut op
: F
) where
664 F
: FnMut(&mut Liveness
<'a
, 'tcx
>, usize, usize),
666 let node_base_idx
= self.idx(ln
, Variable(0));
667 let succ_base_idx
= self.idx(succ_ln
, Variable(0));
668 for var_idx
in 0..self.ir
.num_vars
{
669 op(self, node_base_idx
+ var_idx
, succ_base_idx
+ var_idx
);
673 fn write_vars
<F
>(&self,
677 -> io
::Result
<()> where
678 F
: FnMut(usize) -> LiveNode
,
680 let node_base_idx
= self.idx(ln
, Variable(0));
681 for var_idx
in 0..self.ir
.num_vars
{
682 let idx
= node_base_idx
+ var_idx
;
683 if test(idx
).is_valid() {
684 try
!(write
!(wr
, " {:?}", Variable(var_idx
)));
690 fn find_loop_scope(&self,
691 opt_label
: Option
<ast
::Name
>,
697 // Refers to a labeled loop. Use the results of resolve
699 match self.ir
.tcx
.def_map
.borrow().get(&id
).map(|d
| d
.full_def()) {
700 Some(DefLabel(loop_id
)) => loop_id
,
701 _
=> self.ir
.tcx
.sess
.span_bug(sp
, "label on break/loop \
702 doesn't refer to a loop")
706 // Vanilla 'break' or 'loop', so use the enclosing
708 if self.loop_scope
.is_empty() {
709 self.ir
.tcx
.sess
.span_bug(sp
, "break outside loop");
711 *self.loop_scope
.last().unwrap()
717 #[allow(unused_must_use)]
718 fn ln_str(&self, ln
: LiveNode
) -> String
{
719 let mut wr
= Vec
::new();
721 let wr
= &mut wr
as &mut Write
;
722 write
!(wr
, "[ln({:?}) of kind {:?} reads", ln
.get(), self.ir
.lnk(ln
));
723 self.write_vars(wr
, ln
, |idx
| self.users
[idx
].reader
);
724 write
!(wr
, " writes");
725 self.write_vars(wr
, ln
, |idx
| self.users
[idx
].writer
);
726 write
!(wr
, " precedes {:?}]", self.successors
[ln
.get()]);
728 String
::from_utf8(wr
).unwrap()
731 fn init_empty(&mut self, ln
: LiveNode
, succ_ln
: LiveNode
) {
732 self.successors
[ln
.get()] = succ_ln
;
734 // It is not necessary to initialize the
735 // values to empty because this is the value
736 // they have when they are created, and the sets
737 // only grow during iterations.
739 // self.indices(ln) { |idx|
740 // self.users[idx] = invalid_users();
744 fn init_from_succ(&mut self, ln
: LiveNode
, succ_ln
: LiveNode
) {
745 // more efficient version of init_empty() / merge_from_succ()
746 self.successors
[ln
.get()] = succ_ln
;
748 self.indices2(ln
, succ_ln
, |this
, idx
, succ_idx
| {
749 this
.users
[idx
] = this
.users
[succ_idx
]
751 debug
!("init_from_succ(ln={}, succ={})",
752 self.ln_str(ln
), self.ln_str(succ_ln
));
755 fn merge_from_succ(&mut self,
760 if ln
== succ_ln { return false; }
762 let mut changed
= false;
763 self.indices2(ln
, succ_ln
, |this
, idx
, succ_idx
| {
764 changed
|= copy_if_invalid(this
.users
[succ_idx
].reader
,
765 &mut this
.users
[idx
].reader
);
766 changed
|= copy_if_invalid(this
.users
[succ_idx
].writer
,
767 &mut this
.users
[idx
].writer
);
768 if this
.users
[succ_idx
].used
&& !this
.users
[idx
].used
{
769 this
.users
[idx
].used
= true;
774 debug
!("merge_from_succ(ln={:?}, succ={}, first_merge={}, changed={})",
775 ln
, self.ln_str(succ_ln
), first_merge
, changed
);
778 fn copy_if_invalid(src
: LiveNode
, dst
: &mut LiveNode
) -> bool
{
779 if src
.is_valid() && !dst
.is_valid() {
788 // Indicates that a local variable was *defined*; we know that no
789 // uses of the variable can precede the definition (resolve checks
790 // this) so we just clear out all the data.
791 fn define(&mut self, writer
: LiveNode
, var
: Variable
) {
792 let idx
= self.idx(writer
, var
);
793 self.users
[idx
].reader
= invalid_node();
794 self.users
[idx
].writer
= invalid_node();
796 debug
!("{:?} defines {:?} (idx={}): {}", writer
, var
,
797 idx
, self.ln_str(writer
));
800 // Either read, write, or both depending on the acc bitset
801 fn acc(&mut self, ln
: LiveNode
, var
: Variable
, acc
: u32) {
802 debug
!("{:?} accesses[{:x}] {:?}: {}",
803 ln
, acc
, var
, self.ln_str(ln
));
805 let idx
= self.idx(ln
, var
);
806 let user
= &mut self.users
[idx
];
808 if (acc
& ACC_WRITE
) != 0 {
809 user
.reader
= invalid_node();
813 // Important: if we both read/write, must do read second
814 // or else the write will override.
815 if (acc
& ACC_READ
) != 0 {
819 if (acc
& ACC_USE
) != 0 {
824 // _______________________________________________________________________
826 fn compute(&mut self, decl
: &hir
::FnDecl
, body
: &hir
::Block
) -> LiveNode
{
827 // if there is a `break` or `again` at the top level, then it's
828 // effectively a return---this only occurs in `for` loops,
829 // where the body is really a closure.
831 debug
!("compute: using id for block, {}", block_to_string(body
));
833 let exit_ln
= self.s
.exit_ln
;
834 let entry_ln
: LiveNode
=
835 self.with_loop_nodes(body
.id
, exit_ln
, exit_ln
,
836 |this
| this
.propagate_through_fn_block(decl
, body
));
838 // hack to skip the loop unless debug! is enabled:
839 debug
!("^^ liveness computation results for body {} (entry={:?})",
841 for ln_idx
in 0..self.ir
.num_live_nodes
{
842 debug
!("{:?}", self.ln_str(LiveNode(ln_idx
)));
851 fn propagate_through_fn_block(&mut self, _
: &hir
::FnDecl
, blk
: &hir
::Block
)
853 // the fallthrough exit is only for those cases where we do not
854 // explicitly return:
856 self.init_from_succ(s
.fallthrough_ln
, s
.exit_ln
);
857 if blk
.expr
.is_none() {
858 self.acc(s
.fallthrough_ln
, s
.no_ret_var
, ACC_READ
)
860 self.acc(s
.fallthrough_ln
, s
.clean_exit_var
, ACC_READ
);
862 self.propagate_through_block(blk
, s
.fallthrough_ln
)
865 fn propagate_through_block(&mut self, blk
: &hir
::Block
, succ
: LiveNode
)
867 let succ
= self.propagate_through_opt_expr(blk
.expr
.as_ref().map(|e
| &**e
), succ
);
868 blk
.stmts
.iter().rev().fold(succ
, |succ
, stmt
| {
869 self.propagate_through_stmt(stmt
, succ
)
873 fn propagate_through_stmt(&mut self, stmt
: &hir
::Stmt
, succ
: LiveNode
)
876 hir
::StmtDecl(ref decl
, _
) => {
877 self.propagate_through_decl(&**decl
, succ
)
880 hir
::StmtExpr(ref expr
, _
) | hir
::StmtSemi(ref expr
, _
) => {
881 self.propagate_through_expr(&**expr
, succ
)
886 fn propagate_through_decl(&mut self, decl
: &hir
::Decl
, succ
: LiveNode
)
889 hir
::DeclLocal(ref local
) => {
890 self.propagate_through_local(&**local
, succ
)
892 hir
::DeclItem(_
) => succ
,
896 fn propagate_through_local(&mut self, local
: &hir
::Local
, succ
: LiveNode
)
898 // Note: we mark the variable as defined regardless of whether
899 // there is an initializer. Initially I had thought to only mark
900 // the live variable as defined if it was initialized, and then we
901 // could check for uninit variables just by scanning what is live
902 // at the start of the function. But that doesn't work so well for
903 // immutable variables defined in a loop:
904 // loop { let x; x = 5; }
905 // because the "assignment" loops back around and generates an error.
907 // So now we just check that variables defined w/o an
908 // initializer are not live at the point of their
909 // initialization, which is mildly more complex than checking
910 // once at the func header but otherwise equivalent.
912 let succ
= self.propagate_through_opt_expr(local
.init
.as_ref().map(|e
| &**e
), succ
);
913 self.define_bindings_in_pat(&*local
.pat
, succ
)
916 fn propagate_through_exprs(&mut self, exprs
: &[P
<Expr
>], succ
: LiveNode
)
918 exprs
.iter().rev().fold(succ
, |succ
, expr
| {
919 self.propagate_through_expr(&**expr
, succ
)
923 fn propagate_through_opt_expr(&mut self,
924 opt_expr
: Option
<&Expr
>,
927 opt_expr
.map_or(succ
, |expr
| self.propagate_through_expr(expr
, succ
))
930 fn propagate_through_expr(&mut self, expr
: &Expr
, succ
: LiveNode
)
932 debug
!("propagate_through_expr: {}", expr_to_string(expr
));
935 // Interesting cases with control flow or which gen/kill
937 hir
::ExprPath(..) => {
938 self.access_path(expr
, succ
, ACC_READ
| ACC_USE
)
941 hir
::ExprField(ref e
, _
) => {
942 self.propagate_through_expr(&**e
, succ
)
945 hir
::ExprTupField(ref e
, _
) => {
946 self.propagate_through_expr(&**e
, succ
)
949 hir
::ExprClosure(_
, _
, ref blk
) => {
950 debug
!("{} is an ExprClosure",
951 expr_to_string(expr
));
954 The next-node for a break is the successor of the entire
955 loop. The next-node for a continue is the top of this loop.
957 let node
= self.live_node(expr
.id
, expr
.span
);
958 self.with_loop_nodes(blk
.id
, succ
, node
, |this
| {
960 // the construction of a closure itself is not important,
961 // but we have to consider the closed over variables.
962 let caps
= match this
.ir
.capture_info_map
.get(&expr
.id
) {
963 Some(caps
) => caps
.clone(),
965 this
.ir
.tcx
.sess
.span_bug(expr
.span
, "no registered caps");
968 caps
.iter().rev().fold(succ
, |succ
, cap
| {
969 this
.init_from_succ(cap
.ln
, succ
);
970 let var
= this
.variable(cap
.var_nid
, expr
.span
);
971 this
.acc(cap
.ln
, var
, ACC_READ
| ACC_USE
);
977 hir
::ExprIf(ref cond
, ref then
, ref els
) => {
991 let else_ln
= self.propagate_through_opt_expr(els
.as_ref().map(|e
| &**e
), succ
);
992 let then_ln
= self.propagate_through_block(&**then
, succ
);
993 let ln
= self.live_node(expr
.id
, expr
.span
);
994 self.init_from_succ(ln
, else_ln
);
995 self.merge_from_succ(ln
, then_ln
, false);
996 self.propagate_through_expr(&**cond
, ln
)
999 hir
::ExprWhile(ref cond
, ref blk
, _
) => {
1000 self.propagate_through_loop(expr
, WhileLoop(&**cond
), &**blk
, succ
)
1003 // Note that labels have been resolved, so we don't need to look
1004 // at the label ident
1005 hir
::ExprLoop(ref blk
, _
) => {
1006 self.propagate_through_loop(expr
, LoopLoop
, &**blk
, succ
)
1009 hir
::ExprMatch(ref e
, ref arms
, _
) => {
1024 let ln
= self.live_node(expr
.id
, expr
.span
);
1025 self.init_empty(ln
, succ
);
1026 let mut first_merge
= true;
1029 self.propagate_through_expr(&*arm
.body
, succ
);
1031 self.propagate_through_opt_expr(arm
.guard
.as_ref().map(|e
| &**e
), body_succ
);
1032 // only consider the first pattern; any later patterns must have
1033 // the same bindings, and we also consider the first pattern to be
1034 // the "authoritative" set of ids
1036 self.define_bindings_in_arm_pats(arm
.pats
.first().map(|p
| &**p
),
1038 self.merge_from_succ(ln
, arm_succ
, first_merge
);
1039 first_merge
= false;
1041 self.propagate_through_expr(&**e
, ln
)
1044 hir
::ExprRet(ref o_e
) => {
1045 // ignore succ and subst exit_ln:
1046 let exit_ln
= self.s
.exit_ln
;
1047 self.propagate_through_opt_expr(o_e
.as_ref().map(|e
| &**e
), exit_ln
)
1050 hir
::ExprBreak(opt_label
) => {
1051 // Find which label this break jumps to
1052 let sc
= self.find_loop_scope(opt_label
.map(|l
| l
.node
.name
), expr
.id
, expr
.span
);
1054 // Now that we know the label we're going to,
1055 // look it up in the break loop nodes table
1057 match self.break_ln
.get(&sc
) {
1059 None
=> self.ir
.tcx
.sess
.span_bug(expr
.span
,
1060 "break to unknown label")
1064 hir
::ExprAgain(opt_label
) => {
1065 // Find which label this expr continues to
1066 let sc
= self.find_loop_scope(opt_label
.map(|l
| l
.node
.name
), expr
.id
, expr
.span
);
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
=> self.ir
.tcx
.sess
.span_bug(expr
.span
,
1074 "loop to unknown label")
1078 hir
::ExprAssign(ref l
, ref r
) => {
1079 // see comment on lvalues in
1080 // propagate_through_lvalue_components()
1081 let succ
= self.write_lvalue(&**l
, succ
, ACC_WRITE
);
1082 let succ
= self.propagate_through_lvalue_components(&**l
, succ
);
1083 self.propagate_through_expr(&**r
, succ
)
1086 hir
::ExprAssignOp(_
, ref l
, ref r
) => {
1087 // see comment on lvalues in
1088 // propagate_through_lvalue_components()
1089 let succ
= self.write_lvalue(&**l
, succ
, ACC_WRITE
|ACC_READ
);
1090 let succ
= self.propagate_through_expr(&**r
, succ
);
1091 self.propagate_through_lvalue_components(&**l
, succ
)
1094 // Uninteresting cases: just propagate in rev exec order
1096 hir
::ExprVec(ref exprs
) => {
1097 self.propagate_through_exprs(&exprs
[..], succ
)
1100 hir
::ExprRepeat(ref element
, ref count
) => {
1101 let succ
= self.propagate_through_expr(&**count
, succ
);
1102 self.propagate_through_expr(&**element
, 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 let diverges
= !self.ir
.tcx
.is_method_call(expr
.id
) &&
1114 self.ir
.tcx
.expr_ty_adjusted(&**f
).fn_ret().diverges();
1115 let succ
= if diverges
{
1120 let succ
= self.propagate_through_exprs(&args
[..], succ
);
1121 self.propagate_through_expr(&**f
, succ
)
1124 hir
::ExprMethodCall(_
, _
, ref args
) => {
1125 let method_call
= ty
::MethodCall
::expr(expr
.id
);
1126 let method_ty
= self.ir
.tcx
.tables
.borrow().method_map
[&method_call
].ty
;
1127 let succ
= if method_ty
.fn_ret().diverges() {
1132 self.propagate_through_exprs(&args
[..], succ
)
1135 hir
::ExprTup(ref exprs
) => {
1136 self.propagate_through_exprs(&exprs
[..], succ
)
1139 hir
::ExprBinary(op
, ref l
, ref r
) if ::rustc_front
::util
::lazy_binop(op
.node
) => {
1140 let r_succ
= self.propagate_through_expr(&**r
, succ
);
1142 let ln
= self.live_node(expr
.id
, expr
.span
);
1143 self.init_from_succ(ln
, succ
);
1144 self.merge_from_succ(ln
, r_succ
, false);
1146 self.propagate_through_expr(&**l
, ln
)
1149 hir
::ExprIndex(ref l
, ref r
) |
1150 hir
::ExprBinary(_
, ref l
, ref r
) => {
1151 let r_succ
= self.propagate_through_expr(&**r
, succ
);
1152 self.propagate_through_expr(&**l
, r_succ
)
1155 hir
::ExprRange(ref e1
, ref e2
) => {
1156 let succ
= e2
.as_ref().map_or(succ
, |e
| self.propagate_through_expr(&**e
, succ
));
1157 e1
.as_ref().map_or(succ
, |e
| self.propagate_through_expr(&**e
, succ
))
1160 hir
::ExprBox(ref e
) |
1161 hir
::ExprAddrOf(_
, ref e
) |
1162 hir
::ExprCast(ref e
, _
) |
1163 hir
::ExprType(ref e
, _
) |
1164 hir
::ExprUnary(_
, ref e
) => {
1165 self.propagate_through_expr(&**e
, succ
)
1168 hir
::ExprInlineAsm(ref ia
) => {
1170 let succ
= ia
.outputs
.iter().rev().fold(succ
,
1172 // see comment on lvalues
1173 // in propagate_through_lvalue_components()
1174 if out
.is_indirect
{
1175 self.propagate_through_expr(&*out
.expr
, succ
)
1177 let acc
= if out
.is_rw { ACC_WRITE|ACC_READ }
else { ACC_WRITE }
;
1178 let succ
= self.write_lvalue(&*out
.expr
, succ
, acc
);
1179 self.propagate_through_lvalue_components(&*out
.expr
, succ
)
1183 // Inputs are executed first. Propagate last because of rev order
1184 ia
.inputs
.iter().rev().fold(succ
, |succ
, &(_
, ref expr
)| {
1185 self.propagate_through_expr(&**expr
, succ
)
1189 hir
::ExprLit(..) => {
1193 hir
::ExprBlock(ref blk
) => {
1194 self.propagate_through_block(&**blk
, succ
)
1199 fn propagate_through_lvalue_components(&mut self,
1205 // In general, the full flow graph structure for an
1206 // assignment/move/etc can be handled in one of two ways,
1207 // depending on whether what is being assigned is a "tracked
1208 // value" or not. A tracked value is basically a local
1209 // variable or argument.
1211 // The two kinds of graphs are:
1213 // Tracked lvalue Untracked lvalue
1214 // ----------------------++-----------------------
1218 // (rvalue) || (rvalue)
1221 // (write of lvalue) || (lvalue components)
1226 // ----------------------++-----------------------
1228 // I will cover the two cases in turn:
1230 // # Tracked lvalues
1232 // A tracked lvalue is a local variable/argument `x`. In
1233 // these cases, the link_node where the write occurs is linked
1234 // to node id of `x`. The `write_lvalue()` routine generates
1235 // the contents of this node. There are no subcomponents to
1238 // # Non-tracked lvalues
1240 // These are lvalues like `x[5]` or `x.f`. In that case, we
1241 // basically ignore the value which is written to but generate
1242 // reads for the components---`x` in these two examples. The
1243 // components reads are generated by
1244 // `propagate_through_lvalue_components()` (this fn).
1246 // # Illegal lvalues
1248 // It is still possible to observe assignments to non-lvalues;
1249 // these errors are detected in the later pass borrowck. We
1250 // just ignore such cases and treat them as reads.
1253 hir
::ExprPath(..) => succ
,
1254 hir
::ExprField(ref e
, _
) => self.propagate_through_expr(&**e
, succ
),
1255 hir
::ExprTupField(ref e
, _
) => self.propagate_through_expr(&**e
, succ
),
1256 _
=> self.propagate_through_expr(expr
, succ
)
1260 // see comment on propagate_through_lvalue()
1261 fn write_lvalue(&mut self, expr
: &Expr
, succ
: LiveNode
, acc
: u32)
1264 hir
::ExprPath(..) => {
1265 self.access_path(expr
, succ
, acc
)
1268 // We do not track other lvalues, so just propagate through
1269 // to their subcomponents. Also, it may happen that
1270 // non-lvalues occur here, because those are detected in the
1271 // later pass borrowck.
1276 fn access_path(&mut self, expr
: &Expr
, succ
: LiveNode
, acc
: u32)
1278 match self.ir
.tcx
.def_map
.borrow().get(&expr
.id
).unwrap().full_def() {
1279 DefLocal(_
, nid
) => {
1280 let ln
= self.live_node(expr
.id
, expr
.span
);
1282 self.init_from_succ(ln
, succ
);
1283 let var
= self.variable(nid
, expr
.span
);
1284 self.acc(ln
, var
, acc
);
1292 fn propagate_through_loop(&mut self,
1301 We model control flow like this:
1319 let mut first_merge
= true;
1320 let ln
= self.live_node(expr
.id
, expr
.span
);
1321 self.init_empty(ln
, succ
);
1325 // If this is not a `loop` loop, then it's possible we bypass
1326 // the body altogether. Otherwise, the only way is via a `break`
1327 // in the loop body.
1328 self.merge_from_succ(ln
, succ
, first_merge
);
1329 first_merge
= false;
1332 debug
!("propagate_through_loop: using id for loop body {} {}",
1333 expr
.id
, block_to_string(body
));
1335 let cond_ln
= match kind
{
1337 WhileLoop(ref cond
) => self.propagate_through_expr(&**cond
, ln
),
1339 let body_ln
= self.with_loop_nodes(expr
.id
, succ
, ln
, |this
| {
1340 this
.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.with_loop_nodes(expr
.id
, succ
, ln
,
1355 |this
| this
.propagate_through_block(body
, cond_ln
)));
1361 fn with_loop_nodes
<R
, F
>(&mut self,
1362 loop_node_id
: NodeId
,
1367 F
: FnOnce(&mut Liveness
<'a
, 'tcx
>) -> R
,
1369 debug
!("with_loop_nodes: {} {}", loop_node_id
, break_ln
.get());
1370 self.loop_scope
.push(loop_node_id
);
1371 self.break_ln
.insert(loop_node_id
, break_ln
);
1372 self.cont_ln
.insert(loop_node_id
, cont_ln
);
1374 self.loop_scope
.pop();
1379 // _______________________________________________________________________
1380 // Checking for error conditions
1382 fn check_local(this
: &mut Liveness
, local
: &hir
::Local
) {
1385 this
.warn_about_unused_or_dead_vars_in_pat(&*local
.pat
);
1388 this
.pat_bindings(&*local
.pat
, |this
, ln
, var
, sp
, id
| {
1389 this
.warn_about_unused(sp
, id
, ln
, var
);
1394 intravisit
::walk_local(this
, local
);
1397 fn check_arm(this
: &mut Liveness
, arm
: &hir
::Arm
) {
1398 // only consider the first pattern; any later patterns must have
1399 // the same bindings, and we also consider the first pattern to be
1400 // the "authoritative" set of ids
1401 this
.arm_pats_bindings(arm
.pats
.first().map(|p
| &**p
), |this
, ln
, var
, sp
, id
| {
1402 this
.warn_about_unused(sp
, id
, ln
, var
);
1404 intravisit
::walk_arm(this
, arm
);
1407 fn check_expr(this
: &mut Liveness
, expr
: &Expr
) {
1409 hir
::ExprAssign(ref l
, _
) => {
1410 this
.check_lvalue(&**l
);
1412 intravisit
::walk_expr(this
, expr
);
1415 hir
::ExprAssignOp(_
, ref l
, _
) => {
1416 this
.check_lvalue(&**l
);
1418 intravisit
::walk_expr(this
, expr
);
1421 hir
::ExprInlineAsm(ref ia
) => {
1422 for &(_
, ref input
) in &ia
.inputs
{
1423 this
.visit_expr(&**input
);
1426 // Output operands must be lvalues
1427 for out
in &ia
.outputs
{
1428 if !out
.is_indirect
{
1429 this
.check_lvalue(&*out
.expr
);
1431 this
.visit_expr(&*out
.expr
);
1434 intravisit
::walk_expr(this
, expr
);
1437 // no correctness conditions related to liveness
1438 hir
::ExprCall(..) | hir
::ExprMethodCall(..) | hir
::ExprIf(..) |
1439 hir
::ExprMatch(..) | hir
::ExprWhile(..) | hir
::ExprLoop(..) |
1440 hir
::ExprIndex(..) | hir
::ExprField(..) | hir
::ExprTupField(..) |
1441 hir
::ExprVec(..) | hir
::ExprTup(..) | hir
::ExprBinary(..) |
1442 hir
::ExprCast(..) | hir
::ExprUnary(..) | hir
::ExprRet(..) |
1443 hir
::ExprBreak(..) | hir
::ExprAgain(..) | hir
::ExprLit(_
) |
1444 hir
::ExprBlock(..) | hir
::ExprAddrOf(..) |
1445 hir
::ExprStruct(..) | hir
::ExprRepeat(..) |
1446 hir
::ExprClosure(..) | hir
::ExprPath(..) | hir
::ExprBox(..) |
1447 hir
::ExprRange(..) | hir
::ExprType(..) => {
1448 intravisit
::walk_expr(this
, expr
);
1453 fn check_fn(_v
: &Liveness
,
1455 _decl
: &hir
::FnDecl
,
1459 // do not check contents of nested fns
1462 impl<'a
, 'tcx
> Liveness
<'a
, 'tcx
> {
1463 fn fn_ret(&self, id
: NodeId
) -> ty
::PolyFnOutput
<'tcx
> {
1464 let fn_ty
= self.ir
.tcx
.node_id_to_type(id
);
1466 ty
::TyClosure(closure_def_id
, ref substs
) =>
1467 self.ir
.tcx
.closure_type(closure_def_id
, substs
).sig
.output(),
1479 // within the fn body, late-bound regions are liberated
1480 // and must outlive the *call-site* of the function.
1482 self.ir
.tcx
.liberate_late_bound_regions(
1483 self.ir
.tcx
.region_maps
.call_site_extent(id
, body
.id
),
1487 ty
::FnConverging(t_ret
)
1488 if self.live_on_entry(entry_ln
, self.s
.no_ret_var
).is_some() => {
1491 // for nil return types, it is ok to not return a value expl.
1493 let ends_with_stmt
= match body
.expr
{
1494 None
if !body
.stmts
.is_empty() =>
1495 match body
.stmts
.first().unwrap().node
{
1496 hir
::StmtSemi(ref e
, _
) => {
1497 self.ir
.tcx
.expr_ty(&**e
) == t_ret
1503 let mut err
= struct_span_err
!(self.ir
.tcx
.sess
,
1506 "not all control paths return a value");
1508 let last_stmt
= body
.stmts
.first().unwrap();
1509 let original_span
= original_sp(self.ir
.tcx
.sess
.codemap(),
1510 last_stmt
.span
, sp
);
1511 let span_semicolon
= Span
{
1512 lo
: original_span
.hi
- BytePos(1),
1513 hi
: original_span
.hi
,
1514 expn_id
: original_span
.expn_id
1516 err
.span_help(span_semicolon
, "consider removing this semicolon:");
1522 if self.live_on_entry(entry_ln
, self.s
.clean_exit_var
).is_some() => {
1523 span_err
!(self.ir
.tcx
.sess
, sp
, E0270
,
1524 "computation may converge in a function marked as diverging");
1531 fn check_lvalue(&mut self, expr
: &Expr
) {
1533 hir
::ExprPath(..) => {
1534 if let DefLocal(_
, nid
) = self.ir
.tcx
.def_map
.borrow().get(&expr
.id
)
1537 // Assignment to an immutable variable or argument: only legal
1538 // if there is no later assignment. If this local is actually
1539 // mutable, then check for a reassignment to flag the mutability
1541 let ln
= self.live_node(expr
.id
, expr
.span
);
1542 let var
= self.variable(nid
, expr
.span
);
1543 self.warn_about_dead_assign(expr
.span
, expr
.id
, ln
, var
);
1547 // For other kinds of lvalues, no checks are required,
1548 // and any embedded expressions are actually rvalues
1549 intravisit
::walk_expr(self, expr
);
1554 fn should_warn(&self, var
: Variable
) -> Option
<String
> {
1555 let name
= self.ir
.variable_name(var
);
1556 if name
.is_empty() || name
.as_bytes()[0] == ('_'
as u8) {
1563 fn warn_about_unused_args(&self, decl
: &hir
::FnDecl
, entry_ln
: LiveNode
) {
1564 for arg
in &decl
.inputs
{
1565 pat_util
::pat_bindings(&self.ir
.tcx
.def_map
,
1567 |_bm
, p_id
, sp
, path1
| {
1568 let var
= self.variable(p_id
, sp
);
1569 // Ignore unused self.
1570 let name
= path1
.node
;
1571 if name
!= special_idents
::self_
.name
{
1572 if !self.warn_about_unused(sp
, p_id
, entry_ln
, var
) {
1573 if self.live_on_entry(entry_ln
, var
).is_none() {
1574 self.report_dead_assign(p_id
, sp
, var
, true);
1582 fn warn_about_unused_or_dead_vars_in_pat(&mut self, pat
: &hir
::Pat
) {
1583 self.pat_bindings(pat
, |this
, ln
, var
, sp
, id
| {
1584 if !this
.warn_about_unused(sp
, id
, ln
, var
) {
1585 this
.warn_about_dead_assign(sp
, id
, ln
, var
);
1590 fn warn_about_unused(&self,
1596 if !self.used_on_entry(ln
, var
) {
1597 let r
= self.should_warn(var
);
1598 if let Some(name
) = r
{
1600 // annoying: for parameters in funcs like `fn(x: i32)
1601 // {ret}`, there is only one node, so asking about
1602 // assigned_on_exit() is not meaningful.
1603 let is_assigned
= if ln
== self.s
.exit_ln
{
1606 self.assigned_on_exit(ln
, var
).is_some()
1610 self.ir
.tcx
.sess
.add_lint(lint
::builtin
::UNUSED_VARIABLES
, id
, sp
,
1611 format
!("variable `{}` is assigned to, but never used",
1613 } else if name
!= "self" {
1614 self.ir
.tcx
.sess
.add_lint(lint
::builtin
::UNUSED_VARIABLES
, id
, sp
,
1615 format
!("unused variable: `{}`", name
));
1624 fn warn_about_dead_assign(&self,
1629 if self.live_on_exit(ln
, var
).is_none() {
1630 self.report_dead_assign(id
, sp
, var
, false);
1634 fn report_dead_assign(&self, id
: NodeId
, sp
: Span
, var
: Variable
, is_argument
: bool
) {
1635 if let Some(name
) = self.should_warn(var
) {
1637 self.ir
.tcx
.sess
.add_lint(lint
::builtin
::UNUSED_ASSIGNMENTS
, id
, sp
,
1638 format
!("value passed to `{}` is never read", name
));
1640 self.ir
.tcx
.sess
.add_lint(lint
::builtin
::UNUSED_ASSIGNMENTS
, id
, sp
,
1641 format
!("value assigned to `{}` is never read", name
));