Debian Codegraph @

src/com/google/javascript/jscomp/UnreachableCodeElimination.java

raw symbols SCIP
1 /*
2 * Copyright 2008 The Closure Compiler Authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.google.javascript.jscomp;
18
19 import com.google.common.base.Preconditions;
20 import com.google.javascript.jscomp.ControlFlowGraph.Branch;
21 import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
22 import com.google.javascript.jscomp.NodeTraversal.AbstractShallowCallback;
23 import com.google.javascript.jscomp.NodeTraversal.ScopedCallback;
24 import com.google.javascript.jscomp.graph.DiGraph.DiGraphEdge;
25 import com.google.javascript.jscomp.graph.DiGraph.DiGraphNode;
26 import com.google.javascript.jscomp.graph.GraphReachability;
27 import com.google.javascript.rhino.Node;
28 import com.google.javascript.rhino.Token;
29
30 import java.util.List;
31 import java.util.logging.Level;
32 import java.util.logging.Logger;
33
34 /**
35 * Removes dead code from a parse tree. The kinds of dead code that this pass
36 * removes are:
37 * - Any code following a return statement, such as the <code>alert</code>
38 * call in: <code>if (x) { return; alert('unreachable'); }</code>.
39 * - Statements that have no side effects, such as:
40 * <code>a.b.MyClass.prototype.propertyName;</code> or <code>true;</code>.
41 * That first kind of statement sometimes appears intentionally, so that
42 * prototype properties can be annotated using JSDoc without actually
43 * being initialized.
44 *
45 */
46
47 // TODO(user): Besides dead code after returns, this pass removes useless live
48 // code such as breaks/continues/returns and stms w/out side effects.
49 // These things don't require reachability info, consider making them their own
50 // pass or putting them in some other, more related pass.
51
52 class UnreachableCodeElimination extends AbstractPostOrderCallback
53 implements CompilerPass, ScopedCallback {
54 private static final Logger logger =
55 Logger.getLogger(UnreachableCodeElimination.class.getName());
56
57 private final AbstractCompiler compiler;
58 private final boolean removeNoOpStatements;
59 private boolean codeChanged;
60
61 UnreachableCodeElimination(AbstractCompiler compiler,
62 boolean removeNoOpStatements) {
63 this.compiler = compiler;
64 this.removeNoOpStatements = removeNoOpStatements;
65 }
66
67 @Override
68 public void exitScope(NodeTraversal t) {
69 Scope scope = t.getScope();
70 Node root = scope.getRootNode();
71
72 // Computes the control flow graph.
73 ControlFlowAnalysis cfa = new ControlFlowAnalysis(compiler, false, false);
74 cfa.process(null, root);
75 ControlFlowGraph<Node> cfg = cfa.getCfg();
76
77 new GraphReachability<Node, ControlFlowGraph.Branch>(cfg)
78 .compute(cfg.getEntry().getValue());
79
80 if (scope.isLocal()) {
81 root = root.getLastChild();
82 }
83
84 do {
85 codeChanged = false;
86 NodeTraversal.traverse(compiler, root, new EliminationPass(cfg));
87 } while (codeChanged);
88 }
89
90 @Override
91 public void process(Node externs, Node root) {
92 NodeTraversal.traverse(compiler, root, this);
93 }
94
95 private class EliminationPass extends AbstractShallowCallback {
96 private final ControlFlowGraph<Node> cfg;
97 private EliminationPass(ControlFlowGraph<Node> cfg) {
98 this.cfg = cfg;
99 }
100
101 @Override
102 public void visit(NodeTraversal t, Node n, Node parent) {
103 if (parent == null || n.isFunction() || n.isScript()) {
104 return;
105 }
106 DiGraphNode<Node, Branch> gNode = cfg.getDirectedGraphNode(n);
107 if (gNode == null) { // Not in CFG.
108 return;
109 }
110 if (gNode.getAnnotation() != GraphReachability.REACHABLE ||
111 (removeNoOpStatements && !NodeUtil.mayHaveSideEffects(n, compiler))) {
112 removeDeadExprStatementSafely(n);
113 return;
114 }
115 tryRemoveUnconditionalBranching(n);
116 }
117
118 /**
119 * Tries to remove n if it is an unconditional branch node (break, continue,
120 * or return) and the target of n is the same as the the follow of n.
121 * That is, if removing n preserves the control flow. Also if n targets
122 * another unconditional branch, this function will recursively try to
123 * remove the target branch as well. The reason why we want to cascade this
124 * removal is because we only run this pass once. If we have code such as
125 *
126 * break -> break -> break
127 *
128 * where all 3 breaks are useless, then the order of removal matters. When
129 * we first look at the first break, we see that it branches to the 2nd
130 * break. However, if we remove the last break, the 2nd break becomes
131 * useless and finally the first break becomes useless as well.
132 *
133 * @returns The target of this jump. If the target is also useless jump,
134 * the target of that useless jump recursively.
135 */
136 @SuppressWarnings("fallthrough")
137 private void tryRemoveUnconditionalBranching(Node n) {
138 /*
139 * For each unconditional branching control flow node, check to see
140 * if the ControlFlowAnalysis.computeFollowNode of that node is same as
141 * the branching target. If it is, the branch node is safe to be removed.
142 *
143 * This is not as clever as MinimizeExitPoints because it doesn't do any
144 * if-else conversion but it handles more complicated switch statements
145 * much more nicely.
146 */
147
148 // If n is null the target is the end of the function, nothing to do.
149 if (n == null) {
150 return;
151 }
152
153 DiGraphNode<Node, Branch> gNode = cfg.getDirectedGraphNode(n);
154
155 if (gNode == null) {
156 return;
157 }
158
159 switch (n.getType()) {
160 case Token.RETURN:
161 if (n.hasChildren()) {
162 break;
163 }
164 case Token.BREAK:
165 case Token.CONTINUE:
166 // We are looking for a control flow changing statement that always
167 // branches to the same node. If after removing it control still
168 // branches to the same node, it is safe to remove.
169 List<DiGraphEdge<Node, Branch>> outEdges = gNode.getOutEdges();
170 if (outEdges.size() == 1 &&
171 // If there is a next node, this jump is not useless.
172 (n.getNext() == null || n.getNext().isFunction())) {
173
174 Preconditions.checkState(
175 outEdges.get(0).getValue() == Branch.UNCOND);
176 Node fallThrough = computeFollowing(n);
177 Node nextCfgNode = outEdges.get(0).getDestination().getValue();
178 if (nextCfgNode == fallThrough) {
179 removeNode(n);
180 }
181 }
182 }
183 }
184
185 private Node computeFollowing(Node n) {
186 Node next = ControlFlowAnalysis.computeFollowNode(n);
187 while (next != null && next.isBlock()) {
188 if (next.hasChildren()) {
189 next = next.getFirstChild();
190 } else {
191 next = computeFollowing(next);
192 }
193 }
194 return next;
195 }
196
197 private void removeDeadExprStatementSafely(Node n) {
198 Node parent = n.getParent();
199 if (n.isEmpty() || (n.isBlock() && !n.hasChildren())) {
200 // Not always trivial to remove, let FoldConstants work its magic later.
201 return;
202 }
203
204 // TODO(user): This is a problem with removeNoOpStatements.
205 // Every expression in a FOR-IN header looks side effect free on its own.
206 if (NodeUtil.isForIn(parent)) {
207 return;
208 }
209
210 switch (n.getType()) {
211 // Removing an unreachable DO node is messy b/c it means we still have
212 // to execute one iteration. If the DO's body has breaks in the middle,
213 // it can get even more tricky and code size might actually increase.
214 case Token.DO:
215 return;
216
217 case Token.BLOCK:
218 // BLOCKs are used in several ways including wrapping CATCH
219 // blocks in TRYs
220 if (parent.isTry() && NodeUtil.isTryCatchNodeContainer(n)) {
221 return;
222 }
223 break;
224
225 case Token.CATCH:
226 Node tryNode = parent.getParent();
227 NodeUtil.maybeAddFinally(tryNode);
228 break;
229 }
230
231 if (n.isVar() && !n.getFirstChild().hasChildren()) {
232 // Very unlikely case, Consider this:
233 // File 1: {throw 1}
234 // File 2: {var x}
235 // The node var x is unreachable in the global scope.
236 // Before we remove the node, redeclareVarsInsideBranch
237 // would basically move var x to the beginning of File 2,
238 // which resulted in zero changes to the AST but triggered
239 // reportCodeChange().
240 // Instead, we should just ignore dead variable declarations.
241 return;
242 }
243
244 removeNode(n);
245 }
246
247 private void removeNode(Node n) {
248 codeChanged = true;
249 NodeUtil.redeclareVarsInsideBranch(n);
250 compiler.reportCodeChange();
251 if (logger.isLoggable(Level.FINE)) {
252 logger.fine("Removing " + n.toString());
253 }
254 NodeUtil.removeChild(n.getParent(), n);
255 }
256 }
257
258 @Override
259 public void visit(NodeTraversal t, Node n, Node parent) {}
260
261 @Override
262 public void enterScope(NodeTraversal t) {}
263 }