Skip to content

Commit 0e46c8d

Browse files
committed
dart2js cps: Add logical rewriter rules to favor null-aware operators.
These useful patterns arise with null-aware operators: x ? y : x ==> x && y x ? x : y ==> x || y BUG= [email protected] Review URL: https://codereview.chromium.org//1291073002 .
1 parent c659bda commit 0e46c8d

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

pkg/compiler/lib/src/tree_ir/optimization/logical_rewriter.dart

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -306,6 +306,15 @@ class LogicalRewriter extends RecursiveTransformer
306306
node.elseExpression = tmp;
307307
}
308308

309+
// x ? y : x ==> x && y
310+
if (isSameVariable(node.condition, node.elseExpression)) {
311+
return new LogicalOperator.and(node.condition, node.thenExpression);
312+
}
313+
// x ? x : y ==> x || y
314+
if (isSameVariable(node.condition, node.thenExpression)) {
315+
return new LogicalOperator.or(node.condition, node.elseExpression);
316+
}
317+
309318
return node;
310319
}
311320

@@ -468,6 +477,16 @@ class LogicalRewriter extends RecursiveTransformer
468477
e.elseExpression = (e.elseExpression as Not).operand;
469478
return new Not(e);
470479
}
480+
481+
// x ? y : x ==> x && y
482+
if (isSameVariable(e.condition, e.elseExpression)) {
483+
return new LogicalOperator.and(e.condition, e.thenExpression);
484+
}
485+
// x ? x : y ==> x || y
486+
if (isSameVariable(e.condition, e.thenExpression)) {
487+
return new LogicalOperator.or(e.condition, e.elseExpression);
488+
}
489+
471490
return e;
472491
}
473492
if (e is Constant && e.value.isBool) {
@@ -509,5 +528,19 @@ class LogicalRewriter extends RecursiveTransformer
509528
return new LogicalOperator.or(e1, e2);
510529
}
511530
}
531+
532+
/// True if [e2] is known to return the same value as [e1]
533+
/// (with no additional side effects) if evaluated immediately after [e1].
534+
///
535+
/// Concretely, this is true if [e1] and [e2] are uses of the same variable,
536+
/// or if [e2] is a use of a variable assigned by [e1].
537+
bool isSameVariable(Expression e1, Expression e2) {
538+
if (e1 is VariableUse) {
539+
return e2 is VariableUse && e1.variable == e2.variable;
540+
} else if (e1 is Assign) {
541+
return e2 is VariableUse && e1.variable == e2.variable;
542+
}
543+
return false;
544+
}
512545
}
513546

0 commit comments

Comments
 (0)