Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2004 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.common.base.Predicates;
21 import com.google.javascript.rhino.IR;
22 import com.google.javascript.rhino.Node;
23 import com.google.javascript.rhino.Token;
24 import com.google.javascript.rhino.jstype.TernaryValue;
25
26 import javax.annotation.Nullable;
27
28 /**
29 * Peephole optimization to remove useless code such as IF's with false
30 * guard conditions, comma operator left hand sides with no side effects, etc.
31 *
32 */
33 class PeepholeRemoveDeadCode extends AbstractPeepholeOptimization {
34
35 // TODO(dcc): Some (all) of these can probably be better achieved
36 // using the control flow graph (like CheckUnreachableCode).
37 // There is an existing CFG pass (UnreachableCodeElimination) that
38 // could be changed to use code from CheckUnreachableCode to do this.
39
40 @Override
41 Node optimizeSubtree(Node subtree) {
42 switch(subtree.getType()) {
43 case Token.ASSIGN:
44 return tryFoldAssignment(subtree);
45 case Token.COMMA:
46 return tryFoldComma(subtree);
47 case Token.SCRIPT:
48 case Token.BLOCK:
49 return tryOptimizeBlock(subtree);
50 case Token.EXPR_RESULT:
51 subtree = tryFoldExpr(subtree);
52 return subtree;
53 case Token.HOOK:
54 return tryFoldHook(subtree);
55 case Token.SWITCH:
56 return tryOptimizeSwitch(subtree);
57 case Token.IF:
58 return tryFoldIf(subtree);
59 case Token.WHILE:
60 return tryFoldWhile(subtree);
61 case Token.FOR: {
62 Node condition = NodeUtil.getConditionExpression(subtree);
63 if (condition != null) {
64 tryFoldForCondition(condition);
65 }
66 }
67 return tryFoldFor(subtree);
68 case Token.DO:
69 return tryFoldDo(subtree);
70 case Token.TRY:
71 return tryFoldTry(subtree);
72 default:
73 return subtree;
74 }
75 }
76
77 /**
78 * Remove try blocks without catch blocks and with empty or not
79 * existent finally blocks.
80 * Or, only leave the finally blocks if try body blocks are empty
81 * @return the replacement node, if changed, or the original if not
82 */
83 private Node tryFoldTry(Node n) {
84 Preconditions.checkState(n.isTry());
85 Node body = n.getFirstChild();
86 Node catchBlock = body.getNext();
87 Node finallyBlock = catchBlock.getNext();
88
89 // Removes TRYs that had its CATCH removed and/or empty FINALLY.
90 if (!catchBlock.hasChildren() &&
91 (finallyBlock == null || !finallyBlock.hasChildren())) {
92 n.removeChild(body);
93 n.getParent().replaceChild(n, body);
94 reportCodeChange();
95 return body;
96 }
97
98 // Only leave FINALLYs if TRYs are empty
99 if (!body.hasChildren()) {
100 NodeUtil.redeclareVarsInsideBranch(catchBlock);
101 if (finallyBlock != null) {
102 n.removeChild(finallyBlock);
103 n.getParent().replaceChild(n, finallyBlock);
104 } else {
105 n.getParent().removeChild(n);
106 }
107 reportCodeChange();
108 return finallyBlock;
109 }
110
111 return n;
112 }
113
114 /**
115 * Try removing identity assignments
116 * @return the replacement node, if changed, or the original if not
117 */
118 private Node tryFoldAssignment(Node subtree) {
119 Preconditions.checkState(subtree.isAssign());
120 Node left = subtree.getFirstChild();
121 Node right = subtree.getLastChild();
122 // Only names
123 if (left.isName()
124 && right.isName()
125 && left.getString().equals(right.getString())) {
126 subtree.getParent().replaceChild(subtree, right.detachFromParent());
127 reportCodeChange();
128 return right;
129 }
130 return subtree;
131 }
132
133 /**
134 * Try folding EXPR_RESULT nodes by removing useless Ops and expressions.
135 * @return the replacement node, if changed, or the original if not
136 */
137 private Node tryFoldExpr(Node subtree) {
138 Node result = trySimplifyUnusedResult(subtree.getFirstChild());
139 if (result == null) {
140 Node parent = subtree.getParent();
141 // If the EXPR_RESULT no longer has any children, remove it as well.
142 if (parent.isLabel()) {
143 Node replacement = IR.block().srcref(subtree);
144 parent.replaceChild(subtree, replacement);
145 subtree = replacement;
146 } else {
147 subtree.detachFromParent();
148 subtree = null;
149 }
150 }
151 return subtree;
152 }
153
154 /**
155 * General cascading unused operation node removal.
156 * @param n The root of the expression to simplify.
157 * @return The replacement node, or null if the node was is not useful.
158 */
159 private Node trySimplifyUnusedResult(Node n) {
160 return trySimplifyUnusedResult(n, true);
161 }
162
163 /**
164 * General cascading unused operation node removal.
165 * @param n The root of the expression to simplify.
166 * @param removeUnused If true, the node is removed from the AST if
167 * it is not useful, otherwise it replaced with an EMPTY node.
168 * @return The replacement node, or null if the node was is not useful.
169 */
170 private Node trySimplifyUnusedResult(Node n, boolean removeUnused) {
171 Node result = n;
172
173 // Simplify the results of conditional expressions
174 switch (n.getType()) {
175 case Token.HOOK:
176 Node trueNode = trySimplifyUnusedResult(n.getFirstChild().getNext());
177 Node falseNode = trySimplifyUnusedResult(n.getLastChild());
178 // If one or more of the conditional children were removed,
179 // transform the HOOK to an equivalent operation:
180 // x() ? foo() : 1 --> x() && foo()
181 // x() ? 1 : foo() --> x() || foo()
182 // x() ? 1 : 1 --> x()
183 // x ? 1 : 1 --> null
184 if (trueNode == null && falseNode != null) {
185 n.setType(Token.OR);
186 Preconditions.checkState(n.getChildCount() == 2);
187 } else if (trueNode != null && falseNode == null) {
188 n.setType(Token.AND);
189 Preconditions.checkState(n.getChildCount() == 2);
190 } else if (trueNode == null && falseNode == null) {
191 result = trySimplifyUnusedResult(n.getFirstChild());
192 } else {
193 // The structure didn't change.
194 result = n;
195 }
196 break;
197 case Token.AND:
198 case Token.OR:
199 // Try to remove the second operand from a AND or OR operations:
200 // x() || f --> x()
201 // x() && f --> x()
202 Node conditionalResultNode = trySimplifyUnusedResult(
203 n.getLastChild());
204 if (conditionalResultNode == null) {
205 Preconditions.checkState(n.hasOneChild());
206 // The conditionally executed code was removed, so
207 // replace the AND/OR with its LHS or remove it if it isn't useful.
208 result = trySimplifyUnusedResult(n.getFirstChild());
209 }
210 break;
211 case Token.FUNCTION:
212 // A function expression isn't useful if it isn't used, remove it and
213 // don't bother to look at its children.
214 result = null;
215 break;
216 case Token.COMMA:
217 // We rewrite other operations as COMMA expressions (which will later
218 // get split into individual EXPR_RESULT statement, if possible), so
219 // we special case COMMA (we don't want to rewrite COMMAs as new COMMAs
220 // nodes.
221 Node left = trySimplifyUnusedResult(n.getFirstChild());
222 Node right = trySimplifyUnusedResult(n.getLastChild());
223 if (left == null && right == null) {
224 result = null;
225 } else if (left == null) {
226 result = right;
227 } else if (right == null){
228 result = left;
229 } else {
230 // The structure didn't change.
231 result = n;
232 }
233 break;
234 default:
235 if (!nodeTypeMayHaveSideEffects(n)) {
236 // This is the meat of this function. The node itself doesn't generate
237 // any side-effects but preserve any side-effects in the children.
238 Node resultList = null;
239 for (Node next, c = n.getFirstChild(); c != null; c = next) {
240 next = c.getNext();
241 c = trySimplifyUnusedResult(c);
242 if (c != null) {
243 c.detachFromParent();
244 if (resultList == null) {
245 // The first side-effect can be used stand-alone.
246 resultList = c;
247 } else {
248 // Leave the side-effects in-place, simplifying it to a COMMA
249 // expression.
250 resultList = IR.comma(resultList, c).srcref(c);
251 }
252 }
253 }
254 result = resultList;
255 }
256 }
257
258 // Fix up the AST, replace or remove the an unused node (if requested).
259 if (n != result) {
260 Node parent = n.getParent();
261 if (result == null) {
262 if (removeUnused) {
263 parent.removeChild(n);
264 } else {
265 result = IR.empty().srcref(n);
266 parent.replaceChild(n, result);
267 }
268 } else {
269 // A new COMMA expression may not have an existing parent.
270 if (result.getParent() != null) {
271 result.detachFromParent();
272 }
273 n.getParent().replaceChild(n, result);
274 }
275 reportCodeChange();
276 }
277
278 return result;
279 }
280
281 /**
282 * Remove useless switches and cases.
283 */
284 private Node tryOptimizeSwitch(Node n) {
285 Preconditions.checkState(n.isSwitch());
286
287 Node defaultCase = tryOptimizeDefaultCase(n);
288
289 // Removing cases when there exists a default case is not safe.
290 if (defaultCase == null) {
291 Node cond = n.getFirstChild(), prev = null, next = null, cur;
292
293 for (cur = cond.getNext(); cur != null; cur = next) {
294 next = cur.getNext();
295 if (!mayHaveSideEffects(cur.getFirstChild()) &&
296 isUselessCase(cur, prev)) {
297 removeCase(n, cur);
298 } else {
299 prev = cur;
300 }
301 }
302
303 // Optimize switches with constant condition
304 if (NodeUtil.isLiteralValue(cond, false)) {
305 Node caseLabel;
306 TernaryValue caseMatches = TernaryValue.TRUE;
307 // Remove cases until you find one that may match
308 for (cur = cond.getNext(); cur != null; cur = next) {
309 next = cur.getNext();
310 caseLabel = cur.getFirstChild();
311 caseMatches = PeepholeFoldConstants.evaluateComparison(
312 Token.SHEQ, cond, caseLabel);
313 if (caseMatches == TernaryValue.TRUE) {
314 break;
315 } else if (caseMatches == TernaryValue.UNKNOWN) {
316 break;
317 } else {
318 removeCase(n, cur);
319 }
320 }
321 if (caseMatches != TernaryValue.UNKNOWN) {
322 Node block, lastStm;
323 // Skip cases until you find one whose last stm is a break
324 while (cur != null) {
325 block = cur.getLastChild();
326 lastStm = block.getLastChild();
327 cur = cur.getNext();
328 if (lastStm != null && lastStm.isBreak()) {
329 block.removeChild(lastStm);
330 reportCodeChange();
331 break;
332 }
333 }
334 // Remove any remaining cases
335 for (; cur != null; cur = next) {
336 next = cur.getNext();
337 removeCase(n, cur);
338 }
339 // If there is one case left, we may be able to fold it
340 cur = cond.getNext();
341 if (cur != null && cur.getNext() == null) {
342 block = cur.getLastChild();
343 if (!(NodeUtil.containsType(block, Token.BREAK,
344 NodeUtil.MATCH_NOT_FUNCTION))) {
345 cur.removeChild(block);
346 n.getParent().replaceChild(n, block);
347 reportCodeChange();
348 return block;
349 }
350 }
351 }
352 }
353 }
354
355 // Remove the switch if there are no remaining cases.
356 if (n.hasOneChild()) {
357 Node condition = n.removeFirstChild();
358 Node replacement = IR.exprResult(condition).srcref(n);
359 n.getParent().replaceChild(n, replacement);
360 reportCodeChange();
361 return replacement;
362 }
363
364 return null;
365 }
366
367 /**
368 * @return the default case node or null if there is no default case or
369 * if the default case is removed.
370 */
371 private Node tryOptimizeDefaultCase(Node n) {
372 Preconditions.checkState(n.isSwitch());
373
374 Node lastNonRemovable = n.getFirstChild(); // The switch condition
375
376 // The first child is the switch conditions skip it when looking for cases.
377 for (Node c = n.getFirstChild().getNext(); c != null; c = c.getNext()) {
378 if (c.isDefaultCase()) {
379 // Remove cases that fall-through to the default case
380 Node caseToRemove = lastNonRemovable.getNext();
381 for (Node next; caseToRemove != c; caseToRemove = next) {
382 next = caseToRemove.getNext();
383 removeCase(n, caseToRemove);
384 }
385
386 // Don't use the switch condition as the previous case.
387 Node prevCase = (lastNonRemovable == n.getFirstChild())
388 ? null : lastNonRemovable;
389
390 // Remove the default case if we can
391 if (isUselessCase(c, prevCase)) {
392 removeCase(n, c);
393 return null;
394 }
395 return c;
396 } else {
397 Preconditions.checkState(c.isCase());
398 if (c.getLastChild().hasChildren()
399 || mayHaveSideEffects(c.getFirstChild())) {
400 lastNonRemovable = c;
401 }
402 }
403 }
404 return null;
405 }
406
407 /**
408 * Remove the case from the switch redeclaring any variables declared in it.
409 * @param caseNode The case to remove.
410 */
411 private void removeCase(Node switchNode, Node caseNode) {
412 NodeUtil.redeclareVarsInsideBranch(caseNode);
413 switchNode.removeChild(caseNode);
414 reportCodeChange();
415 }
416
417 /**
418 * The function assumes that when checking a CASE node there is no
419 * DEFAULT node in the SWITCH.
420 * @return Whether the CASE or DEFAULT block does anything useful.
421 */
422 private boolean isUselessCase(Node caseNode, @Nullable Node previousCase) {
423 Preconditions.checkState(
424 previousCase == null || previousCase.getNext() == caseNode);
425 // A case isn't useless can't be useless if a previous case falls
426 // through to it unless it happens to be the last case in the switch.
427 Node switchNode = caseNode.getParent();
428 if (switchNode.getLastChild() != caseNode
429 && previousCase != null) {
430 Node previousBlock = previousCase.getLastChild();
431 if (!previousBlock.hasChildren()
432 || !isExit(previousBlock.getLastChild())) {
433 return false;
434 }
435 }
436
437 Node executingCase = caseNode;
438 while (executingCase != null) {
439 Preconditions.checkState(executingCase.isDefaultCase()
440 || executingCase.isCase());
441 // We only expect a DEFAULT case if the case we are checking is the
442 // DEFAULT case. Otherwise, we assume the DEFAULT case has already
443 // been removed.
444 Preconditions.checkState(caseNode == executingCase
445 || !executingCase.isDefaultCase());
446 Node block = executingCase.getLastChild();
447 Preconditions.checkState(block.isBlock());
448 if (block.hasChildren()) {
449 for (Node blockChild : block.children()) {
450 // If this is a block with a labelless break, it is useless.
451 switch (blockChild.getType()) {
452 case Token.BREAK:
453 // A break to a different control structure isn't useless.
454 return blockChild.getFirstChild() == null;
455 case Token.VAR:
456 if (blockChild.hasOneChild()
457 && blockChild.getFirstChild().getFirstChild() == null) {
458 // Variable declarations without initializations are OK.
459 continue;
460 }
461 return false;
462 default:
463 return false;
464 }
465 }
466 } else {
467 // Look at the fallthrough case
468 executingCase = executingCase.getNext();
469 }
470 }
471 return true;
472 }
473
474 /**
475 * @return Whether the node is an obvious control flow exit.
476 */
477 private boolean isExit(Node n) {
478 switch (n.getType()) {
479 case Token.BREAK:
480 case Token.CONTINUE:
481 case Token.RETURN:
482 case Token.THROW:
483 return true;
484 default:
485 return false;
486 }
487 }
488
489 private Node tryFoldComma(Node n) {
490 // If the left side does nothing replace the comma with the result.
491 Node parent = n.getParent();
492 Node left = n.getFirstChild();
493 Node right = left.getNext();
494
495 left = trySimplifyUnusedResult(left);
496 if (left == null || !mayHaveSideEffects(left)) {
497 // Fold it!
498 n.removeChild(right);
499 parent.replaceChild(n, right);
500 reportCodeChange();
501 return right;
502 }
503 return n;
504 }
505
506 /**
507 * Try removing unneeded block nodes and their useless children
508 */
509 Node tryOptimizeBlock(Node n) {
510 // Remove any useless children
511 for (Node c = n.getFirstChild(); c != null; ) {
512 Node next = c.getNext(); // save c.next, since 'c' may be removed
513 if (!isUnremovableNode(c) && !mayHaveSideEffects(c)) {
514 // TODO(johnlenz): determine what this is actually removing. Candidates
515 // include: EMPTY nodes, control structures without children
516 // (removing infinite loops), empty try blocks. What else?
517 n.removeChild(c); // lazy kids
518 reportCodeChange();
519 } else {
520 tryOptimizeConditionalAfterAssign(c);
521 }
522 c = next;
523 }
524
525 if (n.isSyntheticBlock() || n.isScript() || n.getParent() == null) {
526 return n;
527 }
528
529 // Try to remove the block.
530 if (NodeUtil.tryMergeBlock(n)) {
531 reportCodeChange();
532 return null;
533 }
534
535 return n;
536 }
537
538 /**
539 * Some nodes unremovable node don't have side-effects.
540 */
541 private boolean isUnremovableNode(Node n) {
542 return (n.isBlock() && n.isSyntheticBlock()) || n.isScript();
543 }
544
545 // TODO(johnlenz): Consider moving this to a separate peephole pass.
546 /**
547 * Attempt to replace the condition of if or hook immediately that is a
548 * reference to a name that is assigned immediately before.
549 */
550 private void tryOptimizeConditionalAfterAssign(Node n) {
551 Node next = n.getNext();
552
553 // Look for patterns like the following and replace the if-condition with
554 // a constant value so it can later be folded:
555 // var a = /a/;
556 // if (a) {foo(a)}
557 // or
558 // a = 0;
559 // a ? foo(a) : c;
560 // or
561 // a = 0;
562 // a || foo(a);
563 // or
564 // a = 0;
565 // a && foo(a)
566 //
567 // TODO(johnlenz): This would be better handled by control-flow sensitive
568 // constant propagation. As the other case that I want to handle is:
569 // i=0; for(;i<0;i++){}
570 // as right now nothing facilitates removing a loop like that.
571 // This is here simply to remove the cruft left behind goog.userAgent and
572 // similar cases.
573
574 if (isSimpleAssignment(n) && isConditionalStatement(next)) {
575 Node lhsAssign = getSimpleAssignmentName(n);
576
577 Node condition = getConditionalStatementCondition(next);
578 if (lhsAssign.isName() && condition.isName()
579 && lhsAssign.getString().equals(condition.getString())) {
580 Node rhsAssign = getSimpleAssignmentValue(n);
581 TernaryValue value = NodeUtil.getImpureBooleanValue(rhsAssign);
582 if (value != TernaryValue.UNKNOWN) {
583 Node replacementConditionNode =
584 NodeUtil.booleanNode(value.toBoolean(true));
585 condition.getParent().replaceChild(condition,
586 replacementConditionNode);
587 reportCodeChange();
588 }
589 }
590 }
591 }
592
593 /**
594 * @return whether the node is a assignment to a simple name, or simple var
595 * declaration with initialization.
596 */
597 private boolean isSimpleAssignment(Node n) {
598 // For our purposes we define a simple assignment to be a assignment
599 // to a NAME node, or a VAR declaration with one child and a initializer.
600 if (NodeUtil.isExprAssign(n)
601 && n.getFirstChild().getFirstChild().isName()) {
602 return true;
603 } else if (n.isVar() && n.hasOneChild() &&
604 n.getFirstChild().getFirstChild() != null) {
605 return true;
606 }
607
608 return false;
609 }
610
611 /**
612 * @return The name being assigned to.
613 */
614 private Node getSimpleAssignmentName(Node n) {
615 Preconditions.checkState(isSimpleAssignment(n));
616 if (NodeUtil.isExprAssign(n)) {
617 return n.getFirstChild().getFirstChild();
618 } else {
619 // A var declaration.
620 return n.getFirstChild();
621 }
622 }
623
624 /**
625 * @return The value assigned in the simple assignment
626 */
627 private Node getSimpleAssignmentValue(Node n) {
628 Preconditions.checkState(isSimpleAssignment(n));
629 return n.getFirstChild().getLastChild();
630 }
631
632 /**
633 * @return Whether the node is a conditional statement.
634 */
635 private boolean isConditionalStatement(Node n) {
636 // We defined a conditional statement to be a IF or EXPR_RESULT rooted with
637 // a HOOK, AND, or OR node.
638 return n != null && (n.isIf() || isExprConditional(n));
639 }
640
641 /**
642 * @return Whether the node is a rooted with a HOOK, AND, or OR node.
643 */
644 private boolean isExprConditional(Node n) {
645 if (n.isExprResult()) {
646 switch (n.getFirstChild().getType()) {
647 case Token.HOOK:
648 case Token.AND:
649 case Token.OR:
650 return true;
651 }
652 }
653 return false;
654 }
655
656 /**
657 * @return The condition of a conditional statement.
658 */
659 private Node getConditionalStatementCondition(Node n) {
660 if (n.isIf()) {
661 return NodeUtil.getConditionExpression(n);
662 } else {
663 Preconditions.checkState(isExprConditional(n));
664 return n.getFirstChild().getFirstChild();
665 }
666 }
667
668 /**
669 * Try folding IF nodes by removing dead branches.
670 * @return the replacement node, if changed, or the original if not
671 */
672 private Node tryFoldIf(Node n) {
673 Preconditions.checkState(n.isIf());
674 Node parent = n.getParent();
675 Preconditions.checkNotNull(parent);
676 int type = n.getType();
677 Node cond = n.getFirstChild();
678 Node thenBody = cond.getNext();
679 Node elseBody = thenBody.getNext();
680
681 // if (x) { .. } else { } --> if (x) { ... }
682 if (elseBody != null && !mayHaveSideEffects(elseBody)) {
683 n.removeChild(elseBody);
684 elseBody = null;
685 reportCodeChange();
686 }
687
688 // if (x) { } else { ... } --> if (!x) { ... }
689 if (!mayHaveSideEffects(thenBody) && elseBody != null) {
690 n.removeChild(elseBody);
691 n.replaceChild(thenBody, elseBody);
692 Node notCond = new Node(Token.NOT);
693 n.replaceChild(cond, notCond);
694 notCond.addChildToFront(cond);
695 cond = notCond;
696 thenBody = cond.getNext();
697 elseBody = null;
698 reportCodeChange();
699 }
700
701 // if (x()) { }
702 if (!mayHaveSideEffects(thenBody) && elseBody == null) {
703 if (mayHaveSideEffects(cond)) {
704 // x() has side effects, just leave the condition on its own.
705 n.removeChild(cond);
706 Node replacement = NodeUtil.newExpr(cond);
707 parent.replaceChild(n, replacement);
708 reportCodeChange();
709 return replacement;
710 } else {
711 // x() has no side effects, the whole tree is useless now.
712 NodeUtil.removeChild(parent, n);
713 reportCodeChange();
714 return null;
715 }
716 }
717
718 // Try transforms that apply to both IF and HOOK.
719 TernaryValue condValue = NodeUtil.getImpureBooleanValue(cond);
720 if (condValue == TernaryValue.UNKNOWN) {
721 return n; // We can't remove branches otherwise!
722 }
723
724 if (mayHaveSideEffects(cond)) {
725 // Transform "if (a = 2) {x =2}" into "if (true) {a=2;x=2}"
726 boolean newConditionValue = condValue == TernaryValue.TRUE;
727 // Add an elseBody if it is needed.
728 if (!newConditionValue && elseBody == null) {
729 elseBody = IR.block().srcref(n);
730 n.addChildToBack(elseBody);
731 }
732 Node newCond = NodeUtil.booleanNode(newConditionValue);
733 n.replaceChild(cond, newCond);
734 Node branchToKeep = newConditionValue ? thenBody : elseBody;
735 branchToKeep.addChildToFront(IR.exprResult(cond).srcref(cond));
736 reportCodeChange();
737 cond = newCond;
738 }
739
740 boolean condTrue = condValue.toBoolean(true);
741 if (n.getChildCount() == 2) {
742 Preconditions.checkState(type == Token.IF);
743
744 if (condTrue) {
745 // Replace "if (true) { X }" with "X".
746 Node thenStmt = n.getFirstChild().getNext();
747 n.removeChild(thenStmt);
748 parent.replaceChild(n, thenStmt);
749 reportCodeChange();
750 return thenStmt;
751 } else {
752 // Remove "if (false) { X }" completely.
753 NodeUtil.redeclareVarsInsideBranch(n);
754 NodeUtil.removeChild(parent, n);
755 reportCodeChange();
756 return null;
757 }
758 } else {
759 // Replace "if (true) { X } else { Y }" with X, or
760 // replace "if (false) { X } else { Y }" with Y.
761 Node trueBranch = n.getFirstChild().getNext();
762 Node falseBranch = trueBranch.getNext();
763 Node branchToKeep = condTrue ? trueBranch : falseBranch;
764 Node branchToRemove = condTrue ? falseBranch : trueBranch;
765 NodeUtil.redeclareVarsInsideBranch(branchToRemove);
766 n.removeChild(branchToKeep);
767 parent.replaceChild(n, branchToKeep);
768 reportCodeChange();
769 return branchToKeep;
770 }
771 }
772
773 /**
774 * Try folding HOOK (?:) if the condition results of the condition is known.
775 * @return the replacement node, if changed, or the original if not
776 */
777 private Node tryFoldHook(Node n) {
778 Preconditions.checkState(n.isHook());
779 Node parent = n.getParent();
780 Preconditions.checkNotNull(parent);
781 Node cond = n.getFirstChild();
782 Node thenBody = cond.getNext();
783 Node elseBody = thenBody.getNext();
784
785 TernaryValue condValue = NodeUtil.getImpureBooleanValue(cond);
786 if (condValue == TernaryValue.UNKNOWN) {
787 // If the result nodes are equivalent, then one of the nodes can be
788 // removed and it doesn't matter which.
789 if (!areNodesEqualForInlining(thenBody, elseBody)) {
790 return n; // We can't remove branches otherwise!
791 }
792 }
793
794 // Transform "(a = 2) ? x =2 : y" into "a=2,x=2"
795 n.detachChildren();
796 Node branchToKeep = condValue.toBoolean(true) ? thenBody : elseBody;
797 Node replacement;
798 if (mayHaveSideEffects(cond)) {
799 replacement = IR.comma(cond, branchToKeep).srcref(n);
800 } else {
801 replacement = branchToKeep;
802 }
803
804 parent.replaceChild(n, replacement);
805 reportCodeChange();
806 return replacement;
807 }
808
809 /**
810 * Removes WHILEs that always evaluate to false.
811 */
812 Node tryFoldWhile(Node n) {
813 Preconditions.checkArgument(n.isWhile());
814 Node cond = NodeUtil.getConditionExpression(n);
815 if (NodeUtil.getPureBooleanValue(cond) != TernaryValue.FALSE) {
816 return n;
817 }
818 NodeUtil.redeclareVarsInsideBranch(n);
819 NodeUtil.removeChild(n.getParent(), n);
820 reportCodeChange();
821
822 return null;
823 }
824
825 /**
826 * Removes FORs that always evaluate to false.
827 */
828 Node tryFoldFor(Node n) {
829 Preconditions.checkArgument(n.isFor());
830 // If this is a FOR-IN loop skip it.
831 if (NodeUtil.isForIn(n)) {
832 return n;
833 }
834
835 Node init = n.getFirstChild();
836 Node cond = init.getNext();
837 Node increment = cond.getNext();
838
839 if (!init.isEmpty() && !init.isVar()) {
840 init = trySimplifyUnusedResult(init, false);
841 }
842
843 if (!increment.isEmpty()) {
844 increment = trySimplifyUnusedResult(increment, false);
845 }
846
847 // There is an initializer skip it
848 if (!n.getFirstChild().isEmpty()) {
849 return n;
850 }
851
852 if (NodeUtil.getImpureBooleanValue(cond) != TernaryValue.FALSE) {
853 return n;
854 }
855
856 NodeUtil.redeclareVarsInsideBranch(n);
857 if (!mayHaveSideEffects(cond)) {
858 NodeUtil.removeChild(n.getParent(), n);
859 } else {
860 Node statement = IR.exprResult(cond.detachFromParent())
861 .copyInformationFrom(cond);
862 n.getParent().replaceChild(n, statement);
863 }
864 reportCodeChange();
865 return null;
866 }
867
868 /**
869 * Removes DOs that always evaluate to false. This leaves the
870 * statements that were in the loop in a BLOCK node.
871 * The block will be removed in a later pass, if possible.
872 */
873 Node tryFoldDo(Node n) {
874 Preconditions.checkArgument(n.isDo());
875
876 Node cond = NodeUtil.getConditionExpression(n);
877 if (NodeUtil.getImpureBooleanValue(cond) != TernaryValue.FALSE) {
878 return n;
879 }
880
881 // TODO(johnlenz): The do-while can be turned into a label with
882 // named breaks and the label optimized away (maybe).
883 if (hasBreakOrContinue(n)) {
884 return n;
885 }
886
887 Preconditions.checkState(
888 NodeUtil.isControlStructureCodeBlock(n, n.getFirstChild()));
889 Node block = n.removeFirstChild();
890
891 Node parent = n.getParent();
892 parent.replaceChild(n, block);
893 if (mayHaveSideEffects(cond)) {
894 Node condStatement = IR.exprResult(cond.detachFromParent())
895 .srcref(cond);
896 parent.addChildAfter(condStatement, block);
897 }
898 reportCodeChange();
899
900 return n;
901 }
902
903 /**
904 *
905 */
906 boolean hasBreakOrContinue(Node n) {
907 // TODO(johnlenz): This is overkill as named breaks may refer to outer
908 // loops or labels, and any break my refer to an inner loop.
909 // More generally, this check may be more expensive than we like.
910 return NodeUtil.has(
911 n,
912 Predicates.<Node>or(
913 new NodeUtil.MatchNodeType(Token.BREAK),
914 new NodeUtil.MatchNodeType(Token.CONTINUE)),
915 NodeUtil.MATCH_NOT_FUNCTION);
916 }
917
918 /**
919 * Remove always true loop conditions.
920 */
921 private void tryFoldForCondition(Node forCondition) {
922 if (NodeUtil.getPureBooleanValue(forCondition) == TernaryValue.TRUE) {
923 forCondition.getParent().replaceChild(forCondition,
924 IR.empty());
925 reportCodeChange();
926 }
927 }
928 }