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 use rustc_data_structures::graph;
15 use middle::region::CodeExtent;
21 struct CFGBuilder<'a, 'tcx: 'a> {
22 tcx: &'a ty::ctxt<'tcx>,
25 loop_scopes: Vec<LoopScope>,
28 #[derive(Copy, Clone)]
30 loop_id: ast::NodeId, // id of loop/while node
31 continue_index: CFGIndex, // where to go on a `loop`
32 break_index: CFGIndex, // where to go on a `break
35 pub fn construct(tcx: &ty::ctxt,
36 blk: &ast::Block) -> CFG {
37 let mut graph = graph::Graph::new();
38 let entry = graph.add_node(CFGNodeData::Entry);
40 // `fn_exit` is target of return exprs, which lies somewhere
41 // outside input `blk`. (Distinguishing `fn_exit` and `block_exit`
42 // also resolves chicken-and-egg problem that arises if you try to
43 // have return exprs jump to `block_exit` during construction.)
44 let fn_exit = graph.add_node(CFGNodeData::Exit);
47 let mut cfg_builder = CFGBuilder {
51 loop_scopes: Vec::new()
53 block_exit = cfg_builder.block(blk, entry);
54 cfg_builder.add_contained_edge(block_exit, fn_exit);
55 let CFGBuilder {graph, ..} = cfg_builder;
61 impl<'a, 'tcx> CFGBuilder<'a, 'tcx> {
62 fn block(&mut self, blk: &ast::Block, pred: CFGIndex) -> CFGIndex {
63 let mut stmts_exit = pred;
64 for stmt in &blk.stmts {
65 stmts_exit = self.stmt(&**stmt, stmts_exit);
68 let expr_exit = self.opt_expr(&blk.expr, stmts_exit);
70 self.add_ast_node(blk.id, &[expr_exit])
73 fn stmt(&mut self, stmt: &ast::Stmt, pred: CFGIndex) -> CFGIndex {
75 ast::StmtDecl(ref decl, id) => {
76 let exit = self.decl(&**decl, pred);
77 self.add_ast_node(id, &[exit])
80 ast::StmtExpr(ref expr, id) | ast::StmtSemi(ref expr, id) => {
81 let exit = self.expr(&**expr, pred);
82 self.add_ast_node(id, &[exit])
86 self.tcx.sess.span_bug(stmt.span, "unexpanded macro");
91 fn decl(&mut self, decl: &ast::Decl, pred: CFGIndex) -> CFGIndex {
93 ast::DeclLocal(ref local) => {
94 let init_exit = self.opt_expr(&local.init, pred);
95 self.pat(&*local.pat, init_exit)
104 fn pat(&mut self, pat: &ast::Pat, pred: CFGIndex) -> CFGIndex {
106 ast::PatIdent(_, _, None) |
107 ast::PatEnum(_, None) |
112 self.add_ast_node(pat.id, &[pred])
115 ast::PatBox(ref subpat) |
116 ast::PatRegion(ref subpat, _) |
117 ast::PatIdent(_, _, Some(ref subpat)) => {
118 let subpat_exit = self.pat(&**subpat, pred);
119 self.add_ast_node(pat.id, &[subpat_exit])
122 ast::PatEnum(_, Some(ref subpats)) |
123 ast::PatTup(ref subpats) => {
124 let pats_exit = self.pats_all(subpats.iter(), pred);
125 self.add_ast_node(pat.id, &[pats_exit])
128 ast::PatStruct(_, ref subpats, _) => {
130 self.pats_all(subpats.iter().map(|f| &f.node.pat), pred);
131 self.add_ast_node(pat.id, &[pats_exit])
134 ast::PatVec(ref pre, ref vec, ref post) => {
135 let pre_exit = self.pats_all(pre.iter(), pred);
136 let vec_exit = self.pats_all(vec.iter(), pre_exit);
137 let post_exit = self.pats_all(post.iter(), vec_exit);
138 self.add_ast_node(pat.id, &[post_exit])
142 self.tcx.sess.span_bug(pat.span, "unexpanded macro");
147 fn pats_all<'b, I: Iterator<Item=&'b P<ast::Pat>>>(&mut self,
149 pred: CFGIndex) -> CFGIndex {
150 //! Handles case where all of the patterns must match.
151 pats.fold(pred, |pred, pat| self.pat(&**pat, pred))
154 fn expr(&mut self, expr: &ast::Expr, pred: CFGIndex) -> CFGIndex {
156 ast::ExprBlock(ref blk) => {
157 let blk_exit = self.block(&**blk, pred);
158 self.add_ast_node(expr.id, &[blk_exit])
161 ast::ExprIf(ref cond, ref then, None) => {
176 let cond_exit = self.expr(&**cond, pred); // 1
177 let then_exit = self.block(&**then, cond_exit); // 2
178 self.add_ast_node(expr.id, &[cond_exit, then_exit]) // 3,4
181 ast::ExprIf(ref cond, ref then, Some(ref otherwise)) => {
196 let cond_exit = self.expr(&**cond, pred); // 1
197 let then_exit = self.block(&**then, cond_exit); // 2
198 let else_exit = self.expr(&**otherwise, cond_exit); // 3
199 self.add_ast_node(expr.id, &[then_exit, else_exit]) // 4, 5
202 ast::ExprIfLet(..) => {
203 self.tcx.sess.span_bug(expr.span, "non-desugared ExprIfLet");
206 ast::ExprWhile(ref cond, ref body, _) => {
221 // Note that `break` and `continue` statements
222 // may cause additional edges.
224 // Is the condition considered part of the loop?
225 let loopback = self.add_dummy_node(&[pred]); // 1
226 let cond_exit = self.expr(&**cond, loopback); // 2
227 let expr_exit = self.add_ast_node(expr.id, &[cond_exit]); // 3
228 self.loop_scopes.push(LoopScope {
230 continue_index: loopback,
231 break_index: expr_exit
233 let body_exit = self.block(&**body, cond_exit); // 4
234 self.add_contained_edge(body_exit, loopback); // 5
235 self.loop_scopes.pop();
239 ast::ExprWhileLet(..) => {
240 self.tcx.sess.span_bug(expr.span, "non-desugared ExprWhileLet");
243 ast::ExprForLoop(..) => {
244 self.tcx.sess.span_bug(expr.span, "non-desugared ExprForLoop");
247 ast::ExprLoop(ref body, _) => {
259 // Note that `break` and `loop` statements
260 // may cause additional edges.
262 let loopback = self.add_dummy_node(&[pred]); // 1
263 let expr_exit = self.add_ast_node(expr.id, &[]); // 2
264 self.loop_scopes.push(LoopScope {
266 continue_index: loopback,
267 break_index: expr_exit,
269 let body_exit = self.block(&**body, loopback); // 3
270 self.add_contained_edge(body_exit, loopback); // 4
271 self.loop_scopes.pop();
275 ast::ExprMatch(ref discr, ref arms, _) => {
276 self.match_(expr.id, &discr, &arms, pred)
279 ast::ExprBinary(op, ref l, ref r) if ast_util::lazy_binop(op.node) => {
294 let l_exit = self.expr(&**l, pred); // 1
295 let r_exit = self.expr(&**r, l_exit); // 2
296 self.add_ast_node(expr.id, &[l_exit, r_exit]) // 3,4
299 ast::ExprRet(ref v) => {
300 let v_exit = self.opt_expr(v, pred);
301 let b = self.add_ast_node(expr.id, &[v_exit]);
302 self.add_returning_edge(expr, b);
303 self.add_unreachable_node()
306 ast::ExprBreak(label) => {
307 let loop_scope = self.find_scope(expr, label);
308 let b = self.add_ast_node(expr.id, &[pred]);
309 self.add_exiting_edge(expr, b,
310 loop_scope, loop_scope.break_index);
311 self.add_unreachable_node()
314 ast::ExprAgain(label) => {
315 let loop_scope = self.find_scope(expr, label);
316 let a = self.add_ast_node(expr.id, &[pred]);
317 self.add_exiting_edge(expr, a,
318 loop_scope, loop_scope.continue_index);
319 self.add_unreachable_node()
322 ast::ExprVec(ref elems) => {
323 self.straightline(expr, pred, elems.iter().map(|e| &**e))
326 ast::ExprCall(ref func, ref args) => {
327 self.call(expr, pred, &**func, args.iter().map(|e| &**e))
330 ast::ExprMethodCall(_, _, ref args) => {
331 self.call(expr, pred, &*args[0], args[1..].iter().map(|e| &**e))
334 ast::ExprIndex(ref l, ref r) |
335 ast::ExprBinary(_, ref l, ref r) if self.tcx.is_method_call(expr.id) => {
336 self.call(expr, pred, &**l, Some(&**r).into_iter())
339 ast::ExprRange(ref start, ref end) => {
340 let fields = start.as_ref().map(|e| &**e).into_iter()
341 .chain(end.as_ref().map(|e| &**e));
342 self.straightline(expr, pred, fields)
345 ast::ExprUnary(_, ref e) if self.tcx.is_method_call(expr.id) => {
346 self.call(expr, pred, &**e, None::<ast::Expr>.iter())
349 ast::ExprTup(ref exprs) => {
350 self.straightline(expr, pred, exprs.iter().map(|e| &**e))
353 ast::ExprStruct(_, ref fields, ref base) => {
354 let field_cfg = self.straightline(expr, pred, fields.iter().map(|f| &*f.expr));
355 self.opt_expr(base, field_cfg)
358 ast::ExprRepeat(ref elem, ref count) => {
359 self.straightline(expr, pred, [elem, count].iter().map(|&e| &**e))
362 ast::ExprAssign(ref l, ref r) |
363 ast::ExprAssignOp(_, ref l, ref r) => {
364 self.straightline(expr, pred, [r, l].iter().map(|&e| &**e))
367 ast::ExprBox(Some(ref l), ref r) |
368 ast::ExprIndex(ref l, ref r) |
369 ast::ExprBinary(_, ref l, ref r) => { // NB: && and || handled earlier
370 self.straightline(expr, pred, [l, r].iter().map(|&e| &**e))
373 ast::ExprBox(None, ref e) |
374 ast::ExprAddrOf(_, ref e) |
375 ast::ExprCast(ref e, _) |
376 ast::ExprUnary(_, ref e) |
377 ast::ExprParen(ref e) |
378 ast::ExprField(ref e, _) |
379 ast::ExprTupField(ref e, _) => {
380 self.straightline(expr, pred, Some(&**e).into_iter())
383 ast::ExprInlineAsm(ref inline_asm) => {
384 let inputs = inline_asm.inputs.iter();
385 let outputs = inline_asm.outputs.iter();
386 let post_inputs = self.exprs(inputs.map(|a| {
387 debug!("cfg::construct InlineAsm id:{} input:{:?}", expr.id, a);
388 let &(_, ref expr) = a;
391 let post_outputs = self.exprs(outputs.map(|a| {
392 debug!("cfg::construct InlineAsm id:{} output:{:?}", expr.id, a);
393 let &(_, ref expr, _) = a;
396 self.add_ast_node(expr.id, &[post_outputs])
400 ast::ExprClosure(..) |
402 ast::ExprPath(..) => {
403 self.straightline(expr, pred, None::<ast::Expr>.iter())
408 fn call<'b, I: Iterator<Item=&'b ast::Expr>>(&mut self,
409 call_expr: &ast::Expr,
411 func_or_rcvr: &ast::Expr,
412 args: I) -> CFGIndex {
413 let method_call = ty::MethodCall::expr(call_expr.id);
414 let fn_ty = match self.tcx.tables.borrow().method_map.get(&method_call) {
415 Some(method) => method.ty,
416 None => self.tcx.expr_ty_adjusted(func_or_rcvr)
419 let func_or_rcvr_exit = self.expr(func_or_rcvr, pred);
420 let ret = self.straightline(call_expr, func_or_rcvr_exit, args);
421 if fn_ty.fn_ret().diverges() {
422 self.add_unreachable_node()
428 fn exprs<'b, I: Iterator<Item=&'b ast::Expr>>(&mut self,
430 pred: CFGIndex) -> CFGIndex {
431 //! Constructs graph for `exprs` evaluated in order
432 exprs.fold(pred, |p, e| self.expr(e, p))
435 fn opt_expr(&mut self,
436 opt_expr: &Option<P<ast::Expr>>,
437 pred: CFGIndex) -> CFGIndex {
438 //! Constructs graph for `opt_expr` evaluated, if Some
439 opt_expr.iter().fold(pred, |p, e| self.expr(&**e, p))
442 fn straightline<'b, I: Iterator<Item=&'b ast::Expr>>(&mut self,
445 subexprs: I) -> CFGIndex {
446 //! Handles case of an expression that evaluates `subexprs` in order
448 let subexprs_exit = self.exprs(subexprs, pred);
449 self.add_ast_node(expr.id, &[subexprs_exit])
452 fn match_(&mut self, id: ast::NodeId, discr: &ast::Expr,
453 arms: &[ast::Arm], pred: CFGIndex) -> CFGIndex {
454 // The CFG for match expression is quite complex, so no ASCII
457 // The CFG generated below matches roughly what trans puts
458 // out. Each pattern and guard is visited in parallel, with
459 // arms containing multiple patterns generating multiple nodes
460 // for the same guard expression. The guard expressions chain
461 // into each other from top to bottom, with a specific
462 // exception to allow some additional valid programs
463 // (explained below). Trans differs slightly in that the
464 // pattern matching may continue after a guard but the visible
465 // behaviour should be the same.
467 // What is going on is explained in further comments.
469 // Visit the discriminant expression
470 let discr_exit = self.expr(discr, pred);
472 // Add a node for the exit of the match expression as a whole.
473 let expr_exit = self.add_ast_node(id, &[]);
475 // Keep track of the previous guard expressions
476 let mut prev_guards = Vec::new();
477 // Track if the previous pattern contained bindings or wildcards
478 let mut prev_has_bindings = false;
481 // Add an exit node for when we've visited all the
482 // patterns and the guard (if there is one) in the arm.
483 let arm_exit = self.add_dummy_node(&[]);
485 for pat in &arm.pats {
486 // Visit the pattern, coming from the discriminant exit
487 let mut pat_exit = self.pat(&**pat, discr_exit);
489 // If there is a guard expression, handle it here
490 if let Some(ref guard) = arm.guard {
491 // Add a dummy node for the previous guard
492 // expression to target
493 let guard_start = self.add_dummy_node(&[pat_exit]);
494 // Visit the guard expression
495 let guard_exit = self.expr(&**guard, guard_start);
497 let this_has_bindings = pat_util::pat_contains_bindings_or_wild(
498 &self.tcx.def_map, &**pat);
500 // If both this pattern and the previous pattern
501 // were free of bindings, they must consist only
502 // of "constant" patterns. Note we cannot match an
503 // all-constant pattern, fail the guard, and then
504 // match *another* all-constant pattern. This is
505 // because if the previous pattern matches, then
506 // we *cannot* match this one, unless all the
507 // constants are the same (which is rejected by
510 // We can use this to be smarter about the flow
511 // along guards. If the previous pattern matched,
512 // then we know we will not visit the guard in
513 // this one (whether or not the guard succeeded),
514 // if the previous pattern failed, then we know
515 // the guard for that pattern will not have been
516 // visited. Thus, it is not possible to visit both
517 // the previous guard and the current one when
518 // both patterns consist only of constant
521 // However, if the above does not hold, then all
522 // previous guards need to be wired to visit the
523 // current guard pattern.
524 if prev_has_bindings || this_has_bindings {
525 while let Some(prev) = prev_guards.pop() {
526 self.add_contained_edge(prev, guard_start);
530 prev_has_bindings = this_has_bindings;
532 // Push the guard onto the list of previous guards
533 prev_guards.push(guard_exit);
535 // Update the exit node for the pattern
536 pat_exit = guard_exit;
539 // Add an edge from the exit of this pattern to the
541 self.add_contained_edge(pat_exit, arm_exit);
544 // Visit the body of this arm
545 let body_exit = self.expr(&arm.body, arm_exit);
547 // Link the body to the exit of the expression
548 self.add_contained_edge(body_exit, expr_exit);
554 fn add_dummy_node(&mut self, preds: &[CFGIndex]) -> CFGIndex {
555 self.add_node(CFGNodeData::Dummy, preds)
558 fn add_ast_node(&mut self, id: ast::NodeId, preds: &[CFGIndex]) -> CFGIndex {
559 assert!(id != ast::DUMMY_NODE_ID);
560 self.add_node(CFGNodeData::AST(id), preds)
563 fn add_unreachable_node(&mut self) -> CFGIndex {
564 self.add_node(CFGNodeData::Unreachable, &[])
567 fn add_node(&mut self, data: CFGNodeData, preds: &[CFGIndex]) -> CFGIndex {
568 let node = self.graph.add_node(data);
570 self.add_contained_edge(pred, node);
575 fn add_contained_edge(&mut self,
578 let data = CFGEdgeData {exiting_scopes: vec!() };
579 self.graph.add_edge(source, target, data);
582 fn add_exiting_edge(&mut self,
583 from_expr: &ast::Expr,
584 from_index: CFGIndex,
586 to_index: CFGIndex) {
587 let mut data = CFGEdgeData {exiting_scopes: vec!() };
588 let mut scope = CodeExtent::from_node_id(from_expr.id);
589 let target_scope = CodeExtent::from_node_id(to_loop.loop_id);
590 while scope != target_scope {
592 data.exiting_scopes.push(scope.node_id());
593 scope = self.tcx.region_maps.encl_scope(scope);
595 self.graph.add_edge(from_index, to_index, data);
598 fn add_returning_edge(&mut self,
599 _from_expr: &ast::Expr,
600 from_index: CFGIndex) {
601 let mut data = CFGEdgeData {
602 exiting_scopes: vec!(),
604 for &LoopScope { loop_id: id, .. } in self.loop_scopes.iter().rev() {
605 data.exiting_scopes.push(id);
607 self.graph.add_edge(from_index, self.fn_exit, data);
612 label: Option<ast::Ident>) -> LoopScope {
614 return *self.loop_scopes.last().unwrap();
617 match self.tcx.def_map.borrow().get(&expr.id).map(|d| d.full_def()) {
618 Some(def::DefLabel(loop_id)) => {
619 for l in &self.loop_scopes {
620 if l.loop_id == loop_id {
624 self.tcx.sess.span_bug(expr.span,
625 &format!("no loop scope for id {}", loop_id));
629 self.tcx.sess.span_bug(expr.span,
630 &format!("bad entry `{:?}` in def_map for label", r));